Find Greatest Among Three Numbers

Beginner

Introduction

Finding the greatest number among three user-inputted numbers is a common problem in programming. In this step-by-step lab, we will learn how to solve this problem using C++.

Create the main.cpp file

First, create a main.cpp file in the ~/project directory using the following command:

touch ~/project/main.cpp

Write the code

Copy and paste the following code into the main.cpp file:

#include<bits/stdc++.h>
using namespace std;

int greatest(int a,int b,int c){
    // compares three numbers and returns the greatest one
    if(a>b&&a>c){
        return a;
    }
    else if(b>a&&b>c){
        return b;
    }
    else{
        return c;
    }
}

int main(){
    int num1,num2,num3;
    cout<<"Enter the three numbers: "; // prompt user to enter three numbers
    cin>>num1>>num2>>num3;
    cout<<"The greatest number is: "<<greatest(num1,num2,num3); // output the greatest number
    return 0;
}

Compile and run the code

Compile the code using the following command:

g++ main.cpp -o main && ./main

This will compile the code and generate an executable main file. The output will be displayed in the terminal.

Understand the code

The code first defines a function greatest that takes three integer arguments and returns the greatest of them.

int greatest(int a,int b,int c){
    if(a>b&&a>c){
        return a;
    }
    else if(b>a&&b>c){
        return b;
    }
    else{
        return c;
    }
}

In the main function, we prompt the user to enter three numbers and store them in num1, num2, and num3. Then, we call the greatest function with these three numbers and print the result.

int main(){
    int num1,num2,num3;
    cout<<"Enter the three numbers: ";
    cin>>num1>>num2>>num3;
    cout<<"The greatest number is: "<<greatest(num1,num2,num3);
    return 0;
}

Full code

#include<bits/stdc++.h>
using namespace std;

int greatest(int a,int b,int c){
    // compares three numbers and returns the greatest one
    if(a>b&&a>c){
        return a;
    }
    else if(b>a&&b>c){
        return b;
    }
    else{
        return c;
    }
}

int main(){
    int num1,num2,num3;
    cout<<"Enter the three numbers: "; // prompt user to enter three numbers
    cin>>num1>>num2>>num3;
    cout<<"The greatest number is: "<<greatest(num1,num2,num3); // output the greatest number
    return 0;
}

Summary

In this lab, we learned how to find the greatest number among three user-inputted numbers using C++. We created a function that compared three numbers and returned the greatest number. Then, we prompted the user to enter three numbers, called the function with those numbers, and printed the result.

Other Tutorials you may like