Sunday, December 15, 2013

C++ Programming: Smallest Number

Problem: Write a C++ program that finds the smallest among the five integers inputted by the user.

Solution #1:
#include <iostream>
using namespace std;
int main()
{
int a,b,c,d,e,smallest;
cout<<"Enter five numbers \n";
cout<<"Number 1: ";
cin>>a;
cout<<"Number 2: ";
cin>>b;
cout<<"Number 3: ";
cin>>c;
cout<<"Number 4: ";
cin>>d;
cout<<"Number 5: ";
cin>>e;
smallest = a;
if (smallest >b)
    smallest = b;
if (smallest >c)
    smallest = c;
if (smallest >d)
    smallest = d;
if (smallest >e)
    smallest = e;

cout<<"The smallest number is "<<smallest<<endl;
return 0;
}

Solution #2
#include <iostream>
using namespace std;
int main()
{
int a,b,c,d,e;
cout<<"Enter five numbers \n";
cout<<"Number 1: ";
cin>>a;
cout<<"Number 2: ";
cin>>b;
cout<<"Number 3: ";
cin>>c;
cout<<"Number 4: ";
cin>>d;
cout<<"Number 5: ";
cin>>e;
if (a<b && a<c && a<d && a<e)
    cout<<"The smallest number is "<<a<<endl;
else if (b<a && b<c && b<d && b<e)
    cout<<"The smallest number is "<<b<<endl;
else if (c<a && c<b && c<d && c<e)
    cout<<"The smallest number is "<<c<<endl;
else if (d<a && d<c && d<c && d<e)
    cout<<"The smallest number is "<<d<<endl;
else 
    cout<<"The smallest number is "<<e<<endl;

return 0;
}

No comments:

Post a Comment