C++ Program to Find Largest and Smallest Number in an Array using For loop
ADVERTISEMENTS
C++ program to find largest and smallest number in an array using for loop. In this article, you will learn how to make a C++ program to find largest and smallest number in an array using for loop.
Source Code
// C++ Program to Find Largest and Smallest Number in an Array using For loop
#include <iostream>
using namespace std;
int main() {
int x[50], s, i, b, sm;
// x - To store the array list of input numbers
// s - To store the size of the array
// b - To store the big element variable
// sm - To store the small element variable
cout << "\n-----Enter the size of the array-----\n";
cin >> s;
cout << "\n\n-----Enter the " << s << " elements of the array-----\n\n";
for(i = 0; i < s; i++) {
cin >> x[i];
}
// It stored first element of array to check the element
b = x[0];
for(i = 1; i < s; i++) {
// It checks one by one with each value of array
// To compare the value is smallest or largest
if(b < x[i]) {
b = x[i];
}
}
cout << "\n\n-----The largest element is: " << b << "\n\n";
// It stored first element of array to check the element
sm = x[0];
for(i = 1; i < s; i++) {
// It checks one by one with each value of array
// To compare the value is smallest or largest
if(sm > x[i]) {
sm = x[i];
}
}
cout << "\n\n-----The smallest element is: " << sm << "\n\n";
return 0;
}
Output
-----Enter the size of the array-----
7
-----Enter the 7 elements of the array-----
24
243
23
4
25
424
45
-----The largest element is: 424
-----The smallest element is: 4