C++ Program - Find Smallest Number among three Numbers


Advertisements

Three numbers $$x$$, $$y$$ and $$z$$ are given and the smallest number among these three numbers can be found out using below methods.

Example: Using If statement

In the below example, only if conditional statements are used.

#include <iostream>
using namespace std;

static void smallest(int, int, int);

static void smallest(int x, int y, int z) {
  int min = x;
  if (x <= y && x <= z)
    {min = x;}
  if (y <= x && y <= z)
    {min = y;}
  if (z <= x && z <= y)
    {min = z;}
  cout<<"Smallest number among "<<x<<", "<<y<<" and "<<z<<" is: "<<min<<"\n";
}

int main() {
  smallest(100, 50, 25);
  smallest(50, 50, 25);
  return 0;
}

Output

Smallest number among 100 , 50 and 25 is:  25
Smallest number among 50 , 50 and 25 is:  25

Example: Using If-else statement

It can also be solved using If-else conditional statements.

#include <iostream>
using namespace std;

static void smallest(int, int, int);

static void smallest(int x, int y, int z) {
  int min = x;
  if (x <= y && x <= z)
    {min = x;}
  else if (y <= x && y <= z)
    {min = y;}
  else 
    {min = z;}
  cout<<"Smallest number among "<<x<<", "<<y<<" and "<<z<<" is: "<<min<<"\n";
}

int main() {
  smallest(100, 50, 25);
  smallest(50, 50, 25);
  return 0;
}

Output

Smallest number among 100 , 50 and 25 is:  25
Smallest number among 50 , 50 and 25 is:  25

Example: Using Nested If-else statement

The above problem can also be solved using nested if-else conditional statements.

#include <iostream>
using namespace std;

static void smallest(int, int, int);

static void smallest(int x, int y, int z) {
  int min = x;
  if (x <= y)
    {
      if(x <= z) 
        {min = x;}
      else
        {min = z;}
    }
  else
    {
      if(y <= z) 
        {min = y;}
      else
        {min = z;}
    }
  cout<<"Smallest number among "<<x<<", "<<y<<" and "<<z<<" is: "<<min<<"\n";
}

int main() {
  smallest(100, 50, 25);
  smallest(50, 50, 25);
  return 0;
}

Output

Smallest number among 100 , 50 and 25 is:  25
Smallest number among 50 , 50 and 25 is:  25

Example: Using ternary operator

The ternary operator can also be used here.

#include <iostream>
using namespace std;

static void smallest(int, int, int);

static void smallest(int x, int y, int z) {
  int min = x;
  min = (x < y)? ((x < z)? x : z) : ((y < z)? y : z);
  cout<<"Smallest number among "<<x<<", "<<y<<" and "<<z<<" is: "<<min<<"\n";
}

int main() {
  smallest(100, 50, 25);
  smallest(50, 50, 25);
  return 0;
}

Output

Smallest number among 100 , 50 and 25 is:  25
Smallest number among 50 , 50 and 25 is:  25



Recommended Pages


Advertisements