Â
In this, we are going to write a program to Find Greatest Of Three Numbers in C++.
Unlike the post of Greatest and Smallest of two numbers, we wont compare the input numbers directly but use a flag variable to find maximum, when there are three or more numbers, then number of cases of direct comparisons increase and become confusing, So we use this flag variable to find the maximum. (It can also be done for finding minimum). We will use nested if in this program
The code given below can be used for TURBO C++ Compiler:-
// to find greatest of three integers
// and demonstrate nested if statement
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a, b, c;
cout << "Enter three integers to find greatest...\n";
cout << "Enter first integer : \n";
cin >> a;
cout << "Enter second integer : \n";
cin >> b;
cout << "Enter third integer : \n";
cin >> c;
// to store the smallest possible value of int we use INT_MIN
// to store the greatest possible value of int we use INT_MAX
int flag = INT_MIN ;
cout << "You entered : " << a << ", " << b << " and " << c << endl;
if (a >= flag)
{
flag = a;
if (b >= flag)
{
flag = b;
if (c >= flag)
{
flag = c;
}
}
}
cout << flag << " is the greatest of all";
getch();
}
The code given below can be used for g++/gcc Compiler:-
// to find greatest of three integers
// and demonstrate nested if statement
#include <iostream>
using namespace std;
int main()
{
int a, b, c;
cout << "Enter three integers to find greatest...\n";
cout << "Enter first integer : \n";
cin >> a;
cout << "Enter second integer : \n";
cin >> b;
cout << "Enter third integer : \n";
cin >> c;
// to store the smallest possible value of int we use INT_MIN
// to store the greatest possible value of int we use INT_MAX
int flag = INT_MIN ;
cout << "You entered : " << a << ", " << b << " and " << c << endl;
if (a >= flag)
{
flag = a;
if (b >= flag)
{
flag = b;
if (c >= flag)
{
flag = c;
}
}
}
cout << flag << " is the greatest of all";
return 0;
}
#ENJOYCODING
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP