Program to Find Largest of 3 Numbers in C++
In this C++ Programming tutorial we write a Program to Find Largest of 3 Numbers in C++ . We will be using the If-Else Conditional control structure to find the largest number out of 3 numbers. This Program can be written in multiple ways. Following are the ways in which we can code this program:
Example 1: Find Largest Number Using if Statement
#include <iostream> using namespace std; int main() { float n1, n2, n3; cout << "Enter three numbers: "; cin >> n1 >> n2 >> n3; if(n1 >= n2 && n1 >= n3) { cout << "Largest number: " << n1; } if(n2 >= n1 && n2 >= n3) { cout << "Largest number: " << n2; } if(n3 >= n1 && n3 >= n2) { cout << "Largest number: " << n3; } return 0; }Example 2: Find Largest Number Using if…else Statement
#include <iostream> using namespace std; int main() { float n1, n2, n3; cout << "Enter three numbers: "; cin >> n1 >> n2 >> n3; if((n1 >= n2) && (n1 >= n3)) cout << "Largest number: " << n1; else if ((n2 >= n1) && (n2 >= n3)) cout << "Largest number: " << n2; else cout << "Largest number: " << n3; return 0; }Example 3: Find Largest Number Using Nested if…else statement
#include <iostream> using namespace std; int main() { float n1, n2, n3; cout << "Enter three numbers: "; cin >> n1 >> n2 >> n3; if (n1 >= n2) { if (n1 >= n3) cout << "Largest number: " << n1; else cout << "Largest number: " << n3; } else { if (n2 >= n3) cout << "Largest number: " << n2; else cout << "Largest number: " << n3; } return 0; }Output for all 3 programsEnter three numbers: 2
3
-5
Largest number: 3