Write a C++ program to find largest number in an array. Given an unsorted array, we have to write a C++ code to find the largest number in an array.

Let's think for a moment, how do you solve this problem. You can solve this problem using sorting algorithm, first sort an array and then pick the element at n-1 position. But, let's solve this problem without using any sorting algorithm.

Also, The time complexity of sorting an array is O(nlogn) but we can solve this problem in O(n) in a single traversal.

i) Take an input array from a user.

ii) Take a variable highest and assign first element of an array. After that traverse an array and compare each element of an array with highest. If any element is greater than the highest then assign that value into highest.

Sample snippet.

C program to find highest number in an array

Enter the size of an array( Max 100) 5

Enter array elements

3

8

2

7

1

Largest number 8

Programming questions on arrays

C program to check whether a character is vowel or consonant

C program to find second smallest number in an array without sorting

Let's think for a moment, how do you solve this problem. You can solve this problem using sorting algorithm, first sort an array and then pick the element at n-1 position. But, let's solve this problem without using any sorting algorithm.

Also, The time complexity of sorting an array is O(nlogn) but we can solve this problem in O(n) in a single traversal.

### Algorithm to Find Largest Number in an Array

ii) Take a variable highest and assign first element of an array. After that traverse an array and compare each element of an array with highest. If any element is greater than the highest then assign that value into highest.

Sample snippet.

/* Assign array first element to highest variable. */ int highest = arr[0]; /* Iterate till the end of an array. */ for(i=1;i< arrcount; i++){ /* Check if array element is higher than value in highest.*/ if(arr[i]>highest){ highest = arr[i]; } }Reverse a number using recursion in C, C++

C program to find highest number in an array

## C++ Program to Find Largest Number in an Array

#include <iostream> using namespace std; int main() { int arr[100], n, i, highest; cout << "Enter the size of an array( Max 100) \n"; cin >> n; cout << "Enter array elements \n"; //Take input values for(i = 0; i < n; i++) { cin >> arr[i]; } //Assign first value highest = arr[0]; //Traverse an array for(i = 0; i < n; i++) { //If any value is greater than highest if(arr[i] > highest) { highest = arr[i]; } } //Print largest number cout << "Largest number " << highest; return 0; }

**Output**:Enter the size of an array( Max 100) 5

Enter array elements

3

8

2

7

1

Largest number 8

Programming questions on arrays

C program to check whether a character is vowel or consonant

C program to find second smallest number in an array without sorting

## 0 comments:

## Post a Comment