In: Computer Science
1) Write a function that receives a pointer to an array along with the size of the array, it returns the largest number in the array.
2) Write a function that receives a string and returns the length of it.
1. Function to find the largest number in an array
int largest(int arr[],int size)
//arr is the pointer to the first element of the array & size is the number of elements in the array
{
//max initially stores the minimum value possible. If there are negative elements also in the array, then please //initialize max=INT_MIN and include the header file which contains INT_MIN
int max=-1;
for(int i=0;i<size;i++)
{
// if an element in the array is greater than max, that element is copied to max
if(arr[i]>=max)
max=arr[i];
}
return max; //max stores the largest element in the array and it is returned
}
2. Function to receive a string and return its length
int string_length_func(string str)
{
int count=0,i=0;
while(str[i]!='\0'){ // '\0' is null character which is used to terminate all strings
count++;
i++;
}
// the while loop will run and keep increasing count value till the null character,which is the last character, is not //encountered in the string. As soon as null character is encountered , control exits the loop and returns the //value of count
return count;
}
Please note that these are just user defined functions. You need to write a main function and call these user defined functions in order to execute the program and get the output.
Since no specific programming language was specified in the question, I have written the code using very simple syntax which should work in almost all programming languages.
Here is the complete code in C++.
#include <iostream>
using namespace std;
int largest(int arr[],int size)
{
int max=-1;
for(int i=0;i<size;i++)
{
if(arr[i]>=max)
max=arr[i];
}
return max;
}
int string_length_func(string str)
{
int count=0,i=0;
while(str[i]!='\0'){
count++;
i++;
}
return count;
}
int main()
{
int n;
cout<<"Enter no of elements in array"<<endl;
cin>>n;
cout<<"Enter the elements of array"<<endl;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
cout<<largest(arr,n)<<endl;
string str;
cout<<"Enter a string"<<endl;
cin>>str;
cout<<string_length_func(str)<<endl;
return 0;
}