Cover Image for C++ program to find greatest of four numbers
72 views

C++ program to find greatest of four numbers

You can find the greatest of four numbers in C++ by comparing them using conditional statements. Here’s a C++ program to find the greatest of four numbers:

C++
#include <iostream>

int main() {
    int num1, num2, num3, num4;

    // Input four numbers
    std::cout << "Enter four numbers: ";
    std::cin >> num1 >> num2 >> num3 >> num4;

    int greatest = num1; // Assume the first number is the greatest initially

    // Compare the other three numbers with the greatest
    if (num2 > greatest) {
        greatest = num2;
    }
    if (num3 > greatest) {
        greatest = num3;
    }
    if (num4 > greatest) {
        greatest = num4;
    }

    // Print the greatest number
    std::cout << "The greatest number is: " << greatest << std::endl;

    return 0;
}

In this program:

  1. We declare four integer variables num1, num2, num3, and num4 to store the four input numbers.
  2. We use std::cout to prompt the user to enter the four numbers and then use std::cin to read those numbers into the respective variables.
  3. We assume that the first number (num1) is the greatest initially and store it in the greatest variable.
  4. We compare the other three numbers (num2, num3, and num4) with the greatest number using a series of if statements. If any of these numbers are greater than the current greatest, we update the greatest variable accordingly.
  5. Finally, we print the greatest number to the console.

When you run this program, it will determine and display the greatest of the four input numbers.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS