Techtopz

(@techtopz)

Techtopz is a blog on programming and tech stuff.
Techtopz is now on UpHub.
Follow us for more updates.

    


C++ | Largest and smallest number in Array

This is a tutorial to find largest number and smallest number in array. The program below does so. But there is a limitation (it is not applicable for negative numbers). The program is not extendable. Go enjoy the program. Lets begin…


Program to find the largest and smallest number from array.

#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type int
int a[10],i,l=0,s;
//Input the two numbers save them in arrays.
//Here for loop is used to input multiple numbers in array.
for(i=0;i<5;i++)
{
cout<<"Enter the no."<<endl;
cin>>a[i];
}
//Find the largest and smallest number.
for(i=0;i<5;i++)
{
if(a[i]>l)
l=a[i];
}
s=l;
for(i=0;i<5;i++)
{
if(a[i]<s)
s=a[i];
}
//print the largest and smallest number
cout<<"Largest number = "<<l<<endl;
cout<<"Smallest number = "<<s;
//get character
getch();
}


Output

Enter the number
1
Enter the number
2
Enter the number
3
Enter the number
4
Enter the number
5
Largest number = 5
Smallest number = 1

How does it work
1. You enter the number.
2. The number is saved in respective array.
3. The numbers from arrays are taken and tested if largest and smallest.
4. The largest and smallest number is printed.

Explanation.
1. Include ‘iostream.h’ and ‘conio.h’ files.
2. Add void main.
3. Start program by first clearing the screen.
4. Declare the variables as int (name them as you want.)
5. Add the cout and cin of array.
6. Add a for loop to find largest and smallest number
7. Print the numbers.

At the end
You learnt creating the C++ program of Finding largest and smallest number from array. So now enjoy the program.


Login to like the post