Imagine you are creating a calculator in Python. Instead of writing numbers directly inside the program, you want the user to enter two numbers and let the program calculate their sum. Or suppose you want to create a student registration program that asks for a student's name, age, roll number, and marks. How can a Python program receive information from a user? Python provides a built-in function called input() for this purpose. The input() function allows a program to pause, accept information entered by the user, and store that information in a variable. In this article, we will learn how to use input() with simple examples, understand why it returns a string, convert user input into numbers, and build a practical calculator program. 1. What Is the input() Function in Python? The input() function is a built-in Python function used to accept information from the user. When Python encounters an input() statement, it displays an optional message called a prompt and waits for ...
// Java Program to Find the Greatest of Three Numbers
import java.util.Scanner;
public class GreatestOfThree {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking input from user
System.out.print("Enter first number: ");
int num1 = sc.nextInt();
System.out.print("Enter second number: ");
int num2 = sc.nextInt();
System.out.print("Enter third number: ");
int num3 = sc.nextInt();
// Finding the greatest number
int greatest;
if (num1 >= num2 && num1 >= num3) {
greatest = num1;
} else if (num2 >= num1 && num2 >= num3) {
greatest = num2;
} else {
greatest = num3;
}
// Displaying result
System.out.println("The greatest number is: " + greatest);
sc.close();
}
}
๐ Explanation:
-
We import the
Scannerclass to take user input. -
The program reads three integers from the user.
-
It then uses if-else conditions to compare the numbers.
-
Finally, it prints the greatest number among them.
๐ป Sample Output:
Enter first number: 12
Enter second number: 45
Enter third number: 23
The greatest number is: 45
๐ช Alternative (Using Ternary Operator):
int greatest = (num1 > num2)
? (num1 > num3 ? num1 : num3)
: (num2 > num3 ? num2 : num3);
System.out.println("The greatest number is: " + greatest)
Comments
Post a Comment