C++ program to find and print the smallest element of the array


C++ program to find and print the smallest element of the array

        The below program searches and prints the smallest element in the array. 

        In this program, I have used a variable small and initialized it to the first element of the array. You can take any other variable but it should not be greater than the smallest element

        If you do not assign value to small it will take any random value and the program may fail to provide you the correct output.

        Simply compare small with each element of the array and if any element is less than the small assign it to small and again compare.

        When the loop ends print small, the smallest element will be printed.


Code

#include <iostream>
using namespace std;

int main()
{
    int n;                              //array size
    cin>>n;
    
    int a[n];                       //array declaration
    
    for(int i=0;i<n;i++){           //reading array
        cin>>a[i];
    }
    
    int small=a[0];              //to hold the smallest element initializing with 1st array element
    
    for(int i=0;i<n;i++){           //searching the smallest element via loop
        if(a[i]<small){                //if found update small
            small=a[i];
        }
    }
    
    cout<<"Smallest element is: "<<small;           //printing smallest element

    return 0;
}



Input

5

4 7 9 3 1

Output

Smallest element is: 1

Post a Comment

0 Comments