C++ Program to find largest element in array
Simple C program to find largest element in array: To find largest element, first we initialize max (largest element in array) as first element of array and then compare it with all elements of array. If we find any element greater then max then we update max with that array element.
Another C++ Program using function
Here function has int return type. It will return largest element of array.
Another C++ Program using max function
/* C++ program to find largest element in array */ #include<iostream> using namespace std; int main() { int arr[]={2,7,12,8,4,6,3}; int n=sizeof(arr)/sizeof(arr[0]); int largest=arr[0]; for(int i=0;i<n;i++) { if(arr[i]>largest) { largest=arr[i]; } } cout<<"Largest element in array: "<<largest; return 0; } /* End og the program */
OR
/* C++ program to find largest element in array */ #include<iostream> using namespace std; int main() { int n; cout<<"Enter array size: "; cin>>n; int max,arr[n]; printf("Enter array elements: \n"); for(int i=0;i<n;i++) { cin>>arr[i]; } max=arr[0]; for(int i=0;i<n;i++) { if(max<arr[i]) { max=arr[i]; } } cout<<"Largest element in array: "<<max; return 0; } /* End og the program */
Another C++ Program using function
Here function has int return type. It will return largest element of array.
/* C++ program to find largest element in array */ #include<iostream> using namespace std; int FindLargest(int arr[],int n) { int max=arr[0]; for(int i=0;i<n;i++) { if(arr[i]>max) { max=arr[i]; } } return max; } int main() { int n; cout<<"Enter array size: "; cin>>n; int max,arr[n]; printf("Enter array elements: \n"); for(int i=0;i<n;i++) { cin>>arr[i]; } max=FindLargest(arr,n); cout<<"Largest element in array: "<<max; return 0; } /* End og the program */
Another C++ program using recursion /* C++ program to find largest element in array */ #include<iostream> using namespace std; int max(int a,int b) { if(a>b) return a; else return b; } int FindLargest(int arr[],int n) { if(n==0) return arr[0]; return max(FindLargest(arr,n-1),arr[n]); } int main() { int n; cout<<"Enter array size: "; cin>>n; int max_ele,arr[n]; printf("Enter array elements: \n"); for(int i=0;i<n;i++) { cin>>arr[i]; } max_ele=FindLargest(arr,n-1); cout<<"Largest element in array: "<<max_ele; return 0; } /* End og the program */
Another C++ Program using max function
/* C++ program to find largest element in array */ #include<iostream> using namespace std; int max(int a,int b) { if(a>b) return a; else return b; } int main() { int arr[]={72,70,12,90,4,46,310}; int n=sizeof(arr)/sizeof(arr[0]); int largest=arr[0]; for(int i=1;i<n;i++) { largest=max(largest,arr[i]); } cout<<"Largest element in array: "<<largest; return 0; } /* End og the program */