Java Program - Number Checker¶
Concept Explanation¶
What is it?¶
This program uses a multi-way if-else-if ladder to classify a number based on its relationship to zero.
Why is it important?¶
Conditional logic is the foundation of decision-making in programming. This is one of the simplest examples of how code can branch.
Algorithm¶
- Start
- Accept a number from the user.
- If number > 0, display "Positive".
- Else If number < 0, display "Negative".
- Else, display "Zero".
- End
Implementations¶
import java.util.Scanner;
public class NumberChecker {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (num > 0) {
System.out.println(num + " is POSITIVE.");
} else if (num < 0) {
System.out.println(num + " is NEGATIVE.");
} else {
System.out.println("The number is ZERO.");
}
sc.close();
}
}
Complexity Analysis¶
- Time Complexity: O(1)
- Space Complexity: O(1)
Flowchart¶
graph TD
A[Start] --> B[Input num]
B --> C{num > 0?}
C -- Yes --> D[Positive]
C -- No --> E{num < 0?}
E -- Yes --> F[Negative]
E -- No --> G[Zero]
D --> H[End]
F --> H
G --> H
Interview Tips¶
- Be ready to explain the difference between
ifandif-else if. (In an ladder, only the first true condition executes).
"Programming is about making decisions based on conditions." - Anonymous