Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to find smallest number of an array

C++ Code Example — Array Programs

ADVERTISEMENT

WAP to find smallest number of an array

Objective

Write a C++ program to find the smallest number in an array.

Algorithm / Approach

  1. Read 5 elements into an array.
  2. Assume the first element is the smallest: min = a[0].
  3. Iterate through the array starting from index 1.
  4. If min > a[i], update min = a[i].
  5. Print the minimum value.
main.cpp
#include<iostream>
using namespace std;
int main() {
 int i, a[5] ;
 cout<<"Enter 5 Elements : ";
 for(i =0; i< 5; i++) {
  cin>>a[i];
 }
 int min = a[0];
 for(i =1; i 5; i++) {
  if(min>a[i]) {
   min = a[i];
  }
 }
 cout<<"Min = "<< min<< endl;
return 0;
}

Expected Output

Enter 5 Elements : 12 34 11 36 342
Min = 11

Explanation of the Program

  • This logic is identical to finding the maximum, just with the comparison operator flipped.
  • Note on the provided code: the loop condition is written as for(i =1; i 5; i++). It is missing the less-than operator (&lt;). This will cause a compilation error. It should be for(i = 1; i &lt; 5; i++).

Complexity

Time Complexity O(n)
Space Complexity O(n)

Common Mistakes

  • Typo in the loop condition: for(i =1; i 5; i++) is missing the &lt; operator.
ADVERTISEMENT