c-plus-plus
  1. c-plus-plus-find-greatest-of-four-numbers

C++ Program - Find Greatest of Four Numbers

In this program, we will find the greatest of four numbers using conditional statements in C++.

Syntax

if(condition1) {
    // code
}
else if(condition2) {
    // code
}
else if(condition3) {
    // code
}
else {
    // code
}

Example

#include <iostream>
using namespace std;

int main() {
    int num1, num2, num3, num4;
    cout << "Enter four numbers: ";
    cin >> num1 >> num2 >> num3 >> num4;

    int max = num1;

    if(max < num2) {
        max = num2;
    }
    if(max < num3) {
        max = num3;
    }
    if(max < num4) {
        max = num4;
    }

    cout << "Greatest number is " << max << endl;

    return 0;
}

Output

Enter four numbers: 12 34 56 78
Greatest number is 78

Explanation

In this program, we have taken four numbers as input from the user. We have initialized the variable "max" with the first number. Then we have compared it with other numbers using "if" statements, and updated the value of "max" if a number greater than the current value of "max" is found. Finally, we have displayed the greatest number among the four numbers.

Use

This program shows how to use conditional statements to find the greatest of four numbers in C++. You can use this approach to find the greatest of any number of numbers.

Important Points

  • The "if" statement is used to check a condition and execute a block of code if the condition is true.
  • The "else if" statement is used to check multiple conditions and execute a particular block of code if any of the conditions is true.
  • The "else" statement is used as a catch-all block of code that executes if none of the conditions in the "if" or "else if" statements are true.

Summary

In summary, we have learned how to find the greatest of four numbers using conditional statements in C++. We have used "if" statements to check conditions and executed different blocks of code depending on the conditions. This program can be extended to find the greatest of any number of numbers using the same approach.

Published on: