In this tutorial, we will learn and write a print the smallest element in an array in C++. To understand the coding, you should have knowledge of the following topics in C++ programming:
1. C++ program to find the smallest element in an array
The program takes user input for the size and the values of elements of an array. Lastly, displays the smallest element present in the array.
The first element in an array is assumed to be the smallest element then iterating the array using for loop, we compare each of the elements present in an array. Whenever the element is found to be smaller then the value is inserted into the smallest
variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; int main() { int arr[50], size, smallest, i; cout << "Enter the size of an array: "; cin >> size; cout << "Enter " << size << " Array Elements:\n"; for (i = 0; i < size; i++) cin >> arr[i]; smallest = arr[0]; for (i = 1; i < size; i++) { if (smallest > arr[i]) smallest = arr[i]; } cout << "\nSmallest Element in an array: " << smallest; return 0; } |
Output:
Enter the size of an array: 5
Enter 5 Array Elements:
23
65
12
19
16
Smallest Element in an array: 12
2. Using Function
The program logic is the same as the above only difference is we will create a separate function to search for the smallest element and return the value from that function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #include <iostream> using namespace std; //function to find smallest element int findSmallest(int a[], int s) { int i, small; small = a[0]; for (i = 1; i < s; i++) { if (small > a[i]) small = a[i]; } return small; } //main function int main() { int arr[50], size, smallest, i; cout << "Enter the size of an array: "; cin >> size; cout << "Enter " << size << " Array Elements:\n"; for (i = 0; i < size; i++) cin >> arr[i]; smallest = findSmallest(arr, size); cout << "\nSmallest Element in an array: " << smallest; return 0; } |
Enter the size of an array: 5
Enter 5 Array Elements:
3
56
2
98
12
Smallest Element in an array: 2
3. Find Smallest Number in Array using Pointer in C++
If you want to learn about the pointer and how it works then click the link below.
Source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include<iostream> using namespace std; int main() { int arr[50], size, i, small; int *ptr; cout << "Enter the Size for an Array: "; cin >> size; cout << "Enter " << size << " Array Elements:\n"; for(i=0; i<size; i++) cin>>arr[i]; ptr = &arr[0]; small = *ptr; while(*ptr) { if(small > (*ptr)) small = *ptr; ptr++; } //Display cout << "\nSmallest Element: " << small; return 0; } |
Output:
Enter the Size for an Array: 5
Enter 5 Array Elements:
12
45
11
36
30
Smallest Element: 11