Practical-4
Write a Java Program that will find the largest no from the given three nos.
1. Introduction
A Java program to find the largest of three numbers is a common programming assignment given during basic-level programming courses, such as a BCA. An efficient way to solve this problem is by using decision-making statements, such as if-else and other control structures. By comparing the three numbers, an algorithm can be formulated to determine which number is the largest. Knowing the fundamentals of Java programming, such as reading user input, declaring variables and printing output, is necessary for finding the largest number of three numbers.
Code
import java.util.Scanner;
public class FindLargest {
public static void main(String[] args) {
int num1, num2, num3, largest;
Scanner reader = new Scanner(System.in);
System.out.println("Enter three numbers:");
num1 = reader.nextInt();
num2 = reader.nextInt();
num3 = reader.nextInt();
if (num1 > num2)
largest = num1;
else
largest = num2;
if (num3 > largest)
largest = num3;
System.out.println("Largest number is: " + largest);
}
}
Output
Enter three numbers: 12 45 22 Largest number is: 45
Explanation
The program starts by importing the Scanner class, which is required to read user input. Then, three integer variables are declared to store the three user-entered numbers, as well as a largest variable that will store the largest of the three numbers. The user is prompted to enter three numbers which are then read using the scanner. Next, an if-else statement is used to compare the first two numbers and the larger of the two numbers is stored in the largest variable. Then, another if statement is used to compare the third number with the largest number. The program prints the largest number after the comparison process is complete.