Followers

Monday, April 10, 2023

Program To Find The Maximum Number In An Array

Program:
  #include <iostream>   
  using namespace std;   
  int main() {   
   int arr[5] = {1, 2, 3, 4, 5}, max=arr[0];    
   for(int i=0; i<5;i++){  
           if(arr[i]>max){  
                max=arr[i];  
           }  
      }  
      cout<<"\n\tThe maximum number in the array [1, 2, 3, 4, 5] is "<<max<<endl;  
    return 0;  
 }  
Output:





Working Of The Program:
The program works as follows:
1. The code defines a C++ program that finds the maximum element in an array of integers.
2. The program begins by declaring an integer array arr of size 5, and initializes its elements to the values {1, 2, 3, 4, 5}.
3. The program also declares an integer variable max and initializes it to the first element of the array arr[0].
4. The program then enters a for loop that iterates over each element of the array, using the loop counter variable i.
5. Inside the loop, the program checks if the current element of the array arr[i] is greater than the current value of max.
6. If the current element is greater than max, the program updates the value of max to be the current element arr[i].
7. After the loop completes, the program outputs the maximum element of the array to the console using cout.
8. The output message includes the phrase "The maximum number in the array", followed by the array elements in square brackets and the calculated maximum value.
9. Finally, the program terminates.

1 comment:

  1. I have been checking out all your programs. Amazed to see such work.

    ReplyDelete

Program to Find the Length of a String

Program: #include <iostream> using namespace std; int main() { string a; cout<<"Enter the string...