Python/C/C++/JAVA

Basic Practice Programs with Code and Concept

By D.S

Largest among three numbers

In this example, we're going to be discussing how to find the largest among three numbers in programming. There are various methods to achieve this, but we'll focus on comparing the numbers sequentially to determine the largest one. This approach is simple and efficient for small datasets like three numbers.

(a.) C Code

#include <stdio.h>

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

        printf("Enter three numbers: ");
        scanf("%d %d %d", &num1, &num2, &num3);

        if (num1 >= num2 && num1 >= num3)
            printf("%d is the largest.", num1);
        else if (num2 >= num1 && num2 >= num3)
            printf("%d is the largest.", num2);
        else
            printf("%d is the largest.", num3);

        return 0;
    }
Output:-
Enter three numbers: 5 8 3
8 is the largest.

(b.) C++ Code

#include <iostream>
    using namespace std;

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

        cout << "Enter three numbers: ";
        cin >> num1 >> num2 >> num3;

        if (num1 >= num2 && num1 >= num3)
            cout << num1 << " is the largest.";
        else if (num2 >= num1 && num2 >= num3)
            cout << num2 << " is the largest.";
        else
            cout << num3 << " is the largest.";

        return 0;
    }
Output:-
Enter three numbers: 5 8 3
8 is the largest.

(c.) Python Code

num1, num2, num3 = map(int, input("Enter three numbers: ").split())

    if num1 >= num2 and num1 >= num3:
        print(num1, "is the largest.")
    elif num2 >= num1 and num2 >= num3:
        print(num2, "is the largest.")
    else:
        print(num3, "is the largest.")
Output:-
Enter three numbers: 5 8 3
8 is the largest.

(d.) Java Code

import java.util.Scanner;

    public class LargestNumber {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter three numbers: ");
            int num1 = scanner.nextInt();
            int num2 = scanner.nextInt();
            int num3 = scanner.nextInt();

            int largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
            System.out.println(largest + " is the largest.");
        }
    }
Output:-
Enter three numbers: 5 8 3
8 is the largest.