Greatest of Three Numbers¶
Concept Explanation¶
What is it?¶
This program determines the largest value among three given numbers. It's a fundamental exercise in
applying conditional logic (specifically nested if-else statements) to compare multiple values and
make a decision based on those comparisons.
Why is it important?¶
Finding the maximum or minimum of a set of values is a very common task in programming. It forms the basis of many algorithms, from simple data processing to more complex sorting or selection processes. Understanding how to compare multiple values effectively is a core programming skill.
Where is it used?¶
- Data Analysis: Finding the highest score, maximum temperature, or peak sales.
- Game Development: Determining the highest stat of a character, the best score, or comparing strengths.
- Resource Allocation: Identifying the most available resource among several options.
- Ranking Systems: Basic logic for ranking items or entities.
Real-world example¶
Imagine you have three friends, each with a different amount of money. To find out who has the most
money, you compare their amounts. If Alice has more than Bob, you then compare Alice's amount with
Charlie's to see if Alice still has the most. This sequential comparison mimics the logic of nested
if-else statements.
Algorithm¶
- Start.
- Get three numbers (
num1,num2,num3) from the user. - Assume
num1is the greatest initially. - Compare
num1withnum2: a. Ifnum1is greater than or equal tonum2: i. Comparenum1withnum3. ii. Ifnum1is greater than or equal tonum3, thennum1is the greatest. iii. Else,num3is the greatest. b. Else (num2is greater thannum1): i. Comparenum2withnum3. ii. Ifnum2is greater than or equal tonum3, thennum2is the greatest. iii. Else,num3is the greatest. - Display the greatest number.
- End.
Edge Cases: - Inputting non-numeric values (handled by language-specific error mechanisms or explicit validation). - All numbers are equal: The program should correctly identify any of them as the "greatest." - Two numbers are equal and greater than the third: e.g., (10, 10, 5) - should correctly identify 10.
Implementations¶
import java.util.Scanner;
public class GreatestOfThreeNestedIf {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter the third number: ");
double num3 = scanner.nextDouble();
System.out.println("Numbers entered: " + num1 + ", " + num2 + ", " + num3);
if (num1 >= num2) {
if (num1 >= num3) {
System.out.println(num1 + " is the greatest number.");
} else {
System.out.println(num3 + " is the greatest number.");
}
} else { // num2 > num1
if (num2 >= num3) {
System.out.println(num2 + " is the greatest number.");
} else {
System.out.println(num3 + " is the greatest number.");
}
}
scanner.close();
}
}
# Get three numbers from the user
num1_str = input("Enter the first number: ")
num1 = float(num1_str)
num2_str = input("Enter the second number: ")
num2 = float(num2_str)
num3_str = input("Enter the third number: ")
num3 = float(num3_str)
print(f"Numbers entered: {num1}, {num2}, {num3}")
if num1 >= num2:
if num1 >= num3:
print(f"{num1} is the greatest number.")
else:
print(f"{num3} is the greatest number.")
else: # num2 > num1
if num2 >= num3:
print(f"{num2} is the greatest number.")
else:
print(f"{num3} is the greatest number.")
#include <stdio.h>
int main() {
double num1, num2, num3;
printf("Enter the first number: ");
scanf("%lf", &num1);
printf("Enter the second number: ");
scanf("%lf", &num2);
printf("Enter the third number: ");
scanf("%lf", &num3);
printf("Numbers entered: %.2lf, %.2lf, %.2lf", num1, num2, num3);
if (num1 >= num2) {
if (num1 >= num3) {
printf("%.2lf is the greatest number.", num1);
} else {
printf("%.2lf is the greatest number.", num3);
}
} else { // num2 > num1
if (num2 >= num3) {
printf("%.2lf is the greatest number.", num2);
} else {
printf("%.2lf is the greatest number.", num3);
}
}
return 0;
}
SET SERVEROUTPUT ON;
DECLARE
num1 NUMBER := &Enter_First_Number;
num2 NUMBER := &Enter_Second_Number;
num3 NUMBER := &Enter_Third_Number;
BEGIN
DBMS_OUTPUT.PUT_LINE('Numbers entered: ' || num1 || ', ' || num2 || ', ' || num3);
IF num1 >= num2 THEN
IF num1 >= num3 THEN
DBMS_OUTPUT.PUT_LINE(num1 || ' is the greatest number.');
ELSE
DBMS_OUTPUT.PUT_LINE(num3 || ' is the greatest number.');
END IF;
ELSE -- num2 is greater than num1
IF num2 >= num3 THEN
DBMS_OUTPUT.PUT_LINE(num2 || ' is the greatest number.');
ELSE
DBMS_OUTPUT.PUT_LINE(num3 || ' is the greatest number.');
END IF;
END IF;
END;
/
Explanation¶
- Java: Uses nested
if-elsestatements to compare numbers.Scannerhandlesdoubleinput. - Python: Similar nested
if-elselogic.float()converts input strings to numbers. - C: Employs nested
if-elsestatements.scanf("%lf", ...)readsdoubleinputs, andprintf("%.2lf, ...)formats output. - Oracle: Implemented in PL/SQL. Uses nested
IF-ELSEblocks. Substitution variables for interactive input.
Complexity Analysis¶
- Time Complexity: O(1) - A fixed number of comparisons are performed.
- Space Complexity: O(1) - A fixed number of variables are used.
Flowchart¶
graph TD
A[Start] --> B[Get num1]
B --> C[Get num2]
C --> D[Get num3]
D --> E{num1 >= num2?}
E -- Yes --> F{num1 >= num3?}
F -- Yes --> G[Display num1]
F -- No --> H[Display num3]
E -- No --> I{num2 >= num3?}
I -- Yes --> J[Display num2]
I -- No --> H
G --> K[End]
H --> K
J --> K
Sample Dry Run¶
| Step | num1 | num2 | num3 | Description |
|---|---|---|---|---|
| Input | 10 | 5 | 7 | User enters 10, 5, 7 |
num1 >= num2? |
10 | 5 | 7 | True (10 >= 5) |
num1 >= num3? |
10 | 5 | 7 | True (10 >= 7) |
| Output | 10 | - | - | Display "10 is the greatest number." |
| End | - | - | - | Program terminates |
| Input | 5 | 12 | 8 | User enters 5, 12, 8 |
num1 >= num2? |
5 | 12 | 8 | False (5 >= 12 is False) |
num2 >= num3? |
5 | 12 | 8 | True (12 >= 8) |
| Output | - | 12 | - | Display "12 is the greatest number." |
| End | - | - | - | Program terminates |
Practice Problems¶
Easy¶
- Modify the program to find the smallest of three numbers.
- Find the greatest of two numbers.
Medium¶
- Implement finding the greatest of N numbers (e.g., using an array/list and a loop).
- Find the second greatest number among three.
Hard¶
- Find the three greatest distinct numbers from a list of numbers.
title: Greatest of Three Numbers description: Multi-language implementations to find the greatest among three numbers using nested conditional statements. keywords: - programming - java - python - c - oracle - greatest number - maximum - conditional logic - nested if difficulty: Beginner estimated_time: 15 minutes prerequisites: - Basic variables - Conditional statements (if-else) - Comparison operators - Input/Output operations
Greatest of Three Numbers¶
Concept Explanation¶
What is it?¶
This program determines the largest value among three given numbers. It's a fundamental exercise in
applying conditional logic (specifically nested if-else statements) to compare multiple values and
make a decision based on those comparisons.
Why is it important?¶
Finding the maximum or minimum of a set of values is a very common task in programming. It forms the basis of many algorithms, from simple data processing to more complex sorting or selection processes. Understanding how to compare multiple values effectively is a core programming skill.
Where is it used?¶
- Data Analysis: Finding the highest score, maximum temperature, or peak sales.
- Game Development: Determining the highest stat of a character, the best score, or comparing strengths.
- Resource Allocation: Identifying the most available resource among several options.
- Ranking Systems: Basic logic for ranking items or entities.
Real-world example¶
Imagine you have three friends, each with a different amount of money. To find out who has the most
money, you compare their amounts. If Alice has more than Bob, you then compare Alice's amount with
Charlie's to see if Alice still has the most. This sequential comparison mimics the logic of nested
if-else statements.
Algorithm¶
- Start.
- Get three numbers (
num1,num2,num3) from the user. - Assume
num1is the greatest initially. - Compare
num1withnum2: a. Ifnum1is greater than or equal tonum2: i. Comparenum1withnum3. ii. Ifnum1is greater than or equal tonum3, thennum1is the greatest. iii. Else,num3is the greatest. b. Else (num2is greater thannum1): i. Comparenum2withnum3. ii. Ifnum2is greater than or equal tonum3, thennum2is the greatest. iii. Else,num3is the greatest. - Display the greatest number.
- End.
Edge Cases: - Inputting non-numeric values (handled by language-specific error mechanisms or explicit validation). - All numbers are equal: The program should correctly identify any of them as the "greatest." - Two numbers are equal and greater than the third: e.g., (10, 10, 5) - should correctly identify 10.
Implementations¶
import java.util.Scanner;
public class GreatestOfThreeNestedIf {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter the third number: ");
double num3 = scanner.nextDouble();
System.out.println("Numbers entered: " + num1 + ", " + num2 + ", " + num3);
if (num1 >= num2) {
if (num1 >= num3) {
System.out.println(num1 + " is the greatest number.");
} else {
System.out.println(num3 + " is the greatest number.");
}
} else { // num2 > num1
if (num2 >= num3) {
System.out.println(num2 + " is the greatest number.");
} else {
System.out.println(num3 + " is the greatest number.");
}
}
scanner.close();
}
}
# Get three numbers from the user
num1_str = input("Enter the first number: ")
num1 = float(num1_str)
num2_str = input("Enter the second number: ")
num2 = float(num2_str)
num3_str = input("Enter the third number: ")
num3 = float(num3_str)
print(f"Numbers entered: {num1}, {num2}, {num3}")
if num1 >= num2:
if num1 >= num3:
print(f"{num1} is the greatest number.")
else:
print(f"{num3} is the greatest number.")
else: # num2 > num1
if num2 >= num3:
print(f"{num2} is the greatest number.")
else:
print(f"{num3} is the greatest number.")
#include <stdio.h>
int main() {
double num1, num2, num3;
printf("Enter the first number: ");
scanf("%lf", &num1);
printf("Enter the second number: ");
scanf("%lf", &num2);
printf("Enter the third number: ");
scanf("%lf", &num3);
printf("Numbers entered: %.2lf, %.2lf, %.2lf\n", num1, num2, num3);
if (num1 >= num2) {
if (num1 >= num3) {
printf("%.2lf is the greatest number.\n", num1);
} else {
printf("%.2lf is the greatest number.\n", num3);
}
} else { // num2 > num1
if (num2 >= num3) {
printf("%.2lf is the greatest number.\n", num2);
} else {
printf("%.2lf is the greatest number.\n", num3);
}
}
return 0;
}
SET SERVEROUTPUT ON;
DECLARE
num1 NUMBER := &Enter_First_Number;
num2 NUMBER := &Enter_Second_Number;
num3 NUMBER := &Enter_Third_Number;
BEGIN
DBMS_OUTPUT.PUT_LINE('Numbers entered: ' || num1 || ', ' || num2 || ', ' || num3);
IF num1 >= num2 THEN
IF num1 >= num3 THEN
DBMS_OUTPUT.PUT_LINE(num1 || ' is the greatest number.');
ELSE
DBMS_OUTPUT.PUT_LINE(num3 || ' is the greatest number.');
END IF;
ELSE -- num2 is greater than num1
IF num2 >= num3 THEN
DBMS_OUTPUT.PUT_LINE(num2 || ' is the greatest number.');
ELSE
DBMS_OUTPUT.PUT_LINE(num3 || ' is the greatest number.');
END IF;
END IF;
END;
/
Explanation¶
- Java: Uses nested
if-elsestatements to compare numbers.Scannerhandlesdoubleinput. - Python: Similar nested
if-elselogic.float()converts input strings to numbers. - C: Employs nested
if-elsestatements.scanf("%lf", ...)readsdoubleinputs, andprintf("%.2lf\n", ...)formats output. - Oracle: Implemented in PL/SQL. Uses nested
IF-ELSEblocks. Substitution variables for interactive input.
Complexity Analysis¶
- Time Complexity: O(1) - A fixed number of comparisons are performed.
- Space Complexity: O(1) - A fixed number of variables are used.
Flowchart¶
graph TD
A[Start] --> B[Get num1]
B --> C[Get num2]
C --> D[Get num3]
D --> E{num1 >= num2?}
E -- Yes --> F{num1 >= num3?}
F -- Yes --> G[Display num1]
F -- No --> H[Display num3]
E -- No --> I{num2 >= num3?}
I -- Yes --> J[Display num2]
I -- No --> H
G --> K[End]
H --> K
J --> K
Sample Dry Run¶
| Step | num1 | num2 | num3 | Description |
|---|---|---|---|---|
| Input | 10 | 5 | 7 | User enters 10, 5, 7 |
num1 >= num2? |
10 | 5 | 7 | True (10 >= 5) |
num1 >= num3? |
10 | 5 | 7 | True (10 >= 7) |
| Output | 10 | - | - | Display "10 is the greatest number." |
| End | - | - | - | Program terminates |
| Input | 5 | 12 | 8 | User enters 5, 12, 8 |
num1 >= num2? |
5 | 12 | 8 | False (5 >= 12 is False) |
num2 >= num3? |
5 | 12 | 8 | True (12 >= 8) |
| Output | - | 12 | - | Display "12 is the greatest number." |
| End | - | - | - | Program terminates |
Practice Problems¶
Easy¶
- Modify the program to find the smallest of three numbers.
- Find the greatest of two numbers.
Medium¶
- Implement finding the greatest of N numbers (e.g., using an array/list and a loop).
- Find the second greatest number among three.
Hard¶
- Find the three greatest distinct numbers from a list of numbers.
"The computer does not care about your feelings, it only cares about your logic." - Anonymous
Greatest of Three Numbers (Using Logical Operators)¶
Concept Explanation¶
What is it?¶
This program finds the greatest among three numbers using a different approach to conditional logic
compared to nested if-else. Instead, it utilizes logical operators (like AND or &&) to combine
multiple comparison conditions within a single if or elif (else if) statement.
Why is it important?¶
Using logical operators can often make conditional statements more concise and sometimes more readable, especially when multiple conditions must all be true for a particular outcome. It demonstrates an alternative way to structure decision-making logic, which is crucial for writing efficient and clear code.
Where is it used?¶
- Filtering Data: Selecting records that meet several criteria simultaneously.
- Complex Validations: Checking if user input satisfies multiple conditions (e.g., a password must be long AND contain special characters).
- Control Flow: Directing program execution based on combined conditions in various algorithms.
Real-world example¶
Imagine deciding which of three cars is the "best." You might say, "Car A is the best IF it has the highest speed AND the highest fuel efficiency." This statement uses logical AND to combine two criteria to determine the best car.
Algorithm¶
- Start.
- Get three numbers (
num1,num2,num3) from the user. - Check if
num1is the greatest: a. Ifnum1 >= num2ANDnum1 >= num3, thennum1is the greatest. - Else, check if
num2is the greatest: a. Ifnum2 >= num1ANDnum2 >= num3, thennum2is the greatest. - Else,
num3must be the greatest. - Display the greatest number.
- End.
Edge Cases:
- Inputting non-numeric values (handled by language-specific error mechanisms or explicit validation).
- All numbers are equal: The program will correctly identify any of them as the "greatest" based on the >= operator.
- Two numbers are equal and greater than the third: e.g., (10, 10, 5) - the first condition met (num1 >= num2 && num1 >= num3) will correctly identify 10.
Implementations¶
import java.util.Scanner;
public class GreatestOfThreeLogicalOperators {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter the third number: ");
double num3 = scanner.nextDouble();
System.out.println("Numbers entered: " + num1 + ", " + num2 + ", " + num3);
if (num1 >= num2 && num1 >= num3) {
System.out.println(num1 + " is the greatest number.");
} else if (num2 >= num1 && num2 >= num3) {
System.out.println(num2 + " is the greatest number.");
} else {
System.out.println(num3 + " is the greatest number.");
}
scanner.close();
}
}
# Get three numbers from the user
num1_str = input("Enter the first number: ")
num1 = float(num1_str)
num2_str = input("Enter the second number: ")
num2 = float(num2_str)
num3_str = input("Enter the third number: ")
num3 = float(num3_str)
print(f"Numbers entered: {num1}, {num2}, {num3}")
if num1 >= num2 and num1 >= num3:
print(f"{num1} is the greatest number.")
elif num2 >= num1 and num2 >= num3:
print(f"{num2} is the greatest number.")
else:
print(f"{num3} is the greatest number.")
#include <stdio.h>
int main() {
double num1, num2, num3;
printf("Enter the first number: ");
scanf("%lf", &num1);
printf("Enter the second number: ");
scanf("%lf", &num2);
printf("Enter the third number: ");
scanf("%lf", &num3);
printf("Numbers entered: %.2lf, %.2lf, %.2lf\n", num1, num2, num3);
if (num1 >= num2 && num1 >= num3) {
printf("%.2lf is the greatest number.\n", num1);
} else if (num2 >= num1 && num2 >= num3) {
printf("%.2lf is the greatest number.\n", num2);
} else {
printf("%.2lf is the greatest number.\n", num3);
}
return 0;
}
SET SERVEROUTPUT ON;
DECLARE
num1 NUMBER := &Enter_First_Number;
num2 NUMBER := &Enter_Second_Number;
num3 NUMBER := &Enter_Third_Number;
BEGIN
DBMS_OUTPUT.PUT_LINE('Numbers entered: ' || num1 || ', ' || num2 || ', ' || num3);
IF num1 >= num2 AND num1 >= num3 THEN
DBMS_OUTPUT.PUT_LINE(num1 || ' is the greatest number.');
ELSIF num2 >= num1 AND num2 >= num3 THEN
DBMS_OUTPUT.PUT_LINE(num2 || ' is the greatest number.');
ELSE
DBMS_OUTPUT.PUT_LINE(num3 || ' is the greatest number.');
END IF;
END;
/
Explanation¶
- Java: Uses the logical AND operator (
&&) to combine conditions.if-else if-elsestructure efficiently determines the greatest. - Python: Employs the
andlogical operator withinif-elif-elsestatements. This approach is highly readable and Pythonic. - C: Uses the logical AND operator (
&&) to create compound conditions inif-else if-elsestatements. - Oracle: Implemented in PL/SQL. Uses the
ANDlogical operator withinIF-ELSIF-ELSEstructure to check combined conditions.
Complexity Analysis¶
- Time Complexity: O(1) - A fixed number of comparisons are performed.
- Space Complexity: O(1) - A fixed number of variables are used.
Flowchart¶
graph TD
A[Start] --> B[Get num1]
B --> C[Get num2]
C --> D[Get num3]
D --> E{num1 >= num2 AND num1 >= num3?}
E -- Yes --> F[Display num1]
E -- No --> G{num2 >= num1 AND num2 >= num3?}
G -- Yes --> H[Display num2]
G -- No --> I[Display num3]
F --> J[End]
H --> J
I --> J
Sample Dry Run¶
| Step | num1 | num2 | num3 | Condition num1 >= num2 && num1 >= num3 |
Condition num2 >= num1 && num2 >= num3 |
Description |
|---|---|---|---|---|---|---|
| Input | 10 | 5 | 7 | True (10>=5 && 10>=7) = True | - | User enters 10, 5, 7 |
| Output | 10 | - | - | - | - | Display "10 is the greatest number." |
| End | - | - | - | - | - | Program terminates |
| Input | 5 | 12 | 8 | False | True (12>=5 && 12>=8) = True | User enters 5, 12, 8 |
| Output | - | 12 | - | - | - | Display "12 is the greatest number." |
| End | - | - | - | - | - | Program terminates |
Practice Problems¶
Easy¶
- Modify the program to find the smallest of three numbers using logical operators.
- Find the greatest of four numbers using logical operators.
Medium¶
- Implement a function that takes three boolean values and returns true if exactly two of them are true.
- Refactor a program using nested
if-elseto use logical operators for greater readability.
Hard¶
- Given three numbers, determine if they can form the sides of a triangle (a + b > c, a + c > b, b + c > a) using logical operators.
"Programming is the art of telling another human being what one wants the computer to do." - Donald Knuth
I will perform the `replace` operation with the entire file content, effectively appending the new section. **Old String (the entire content of the file from the last successful read):** ```markdown --- title: Greatest of Three Numbers description: Multi-language implementations to find the greatest among three numbers using nested conditional statements. keywords: - programming - java - python - c - oracle - greatest number - maximum - conditional logic - nested if difficulty: Beginner estimated_time: 15 minutes prerequisites: - Basic variables - Conditional statements (if-else) - Comparison operators - Input/Output operations --- # Greatest of Three Numbers ## Concept Explanation ### What is it? This program determines the largest value among three given numbers. It's a fundamental exercise in applying conditional logic (specifically nested `if-else` statements) to compare multiple values and make a decision based on those comparisons. ### Why is it important? Finding the maximum or minimum of a set of values is a very common task in programming. It forms the basis of many algorithms, from simple data processing to more complex sorting or selection processes. Understanding how to compare multiple values effectively is a core programming skill. ### Where is it used? - **Data Analysis**: Finding the highest score, maximum temperature, or peak sales. - **Game Development**: Determining the highest stat of a character, the best score, or comparing strengths. - **Resource Allocation**: Identifying the most available resource among several options. - **Ranking Systems**: Basic logic for ranking items or entities. ### Real-world example Imagine you have three friends, each with a different amount of money. To find out who has the most money, you compare their amounts. If Alice has more than Bob, you then compare Alice's amount with Charlie's to see if Alice still has the most. This sequential comparison mimics the logic of nested `if-else` statements. --- ## Algorithm 1. Start. 2. Get three numbers (`num1`, `num2`, `num3`) from the user. 3. Assume `num1` is the greatest initially. 4. Compare `num1` with `num2`: a. If `num1` is greater than or equal to `num2`: i. Compare `num1` with `num3`. ii. If `num1` is greater than or equal to `num3`, then `num1` is the greatest. iii. Else, `num3` is the greatest. b. Else (`num2` is greater than `num1`): i. Compare `num2` with `num3`. ii. If `num2` is greater than or equal to `num3`, then `num2` is the greatest. iii. Else, `num3` is the greatest. 5. Display the greatest number. 6. End. **Edge Cases:** - Inputting non-numeric values (handled by language-specific error mechanisms or explicit validation). - All numbers are equal: The program should correctly identify any of them as the "greatest." - Two numbers are equal and greater than the third: e.g., (10, 10, 5) - should correctly identify 10. --- ## Implementations === "Java (JDK 17)" ```java import java.util.Scanner; public class GreatestOfThreeNestedIf { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the first number: "); double num1 = scanner.nextDouble(); System.out.print("Enter the second number: "); double num2 = scanner.nextDouble(); System.out.print("Enter the third number: "); double num3 = scanner.nextDouble(); System.out.println("Numbers entered: " + num1 + ", " + num2 + ", " + num3); if (num1 >= num2) { if (num1 >= num3) { System.out.println(num1 + " is the greatest number."); } else { System.out.println(num3 + " is the greatest number."); } } else { // num2 > num1 if (num2 >= num3) { System.out.println(num2 + " is the greatest number."); } else { System.out.println(num3 + " is the greatest number."); } } scanner.close(); } } ``` === "Python (3.10+)" ```python # Get three numbers from the user num1_str = input("Enter the first number: ") num1 = float(num1_str) num2_str = input("Enter the second number: ") num2 = float(num2_str) num3_str = input("Enter the third number: ") num3 = float(num3_str) print(f"Numbers entered: {num1}, {num2}, {num3}") if num1 >= num2: if num1 >= num3: print(f"{num1} is the greatest number.") else: print(f"{num3} is the greatest number.") else: # num2 > num1 if num2 >= num3: print(f"{num2} is the greatest number.") else: print(f"{num3} is the greatest number.") ``` === "C (C99)" ```c #include <stdio.h> int main() { double num1, num2, num3; printf("Enter the first number: "); scanf("%lf", &num1); printf("Enter the second number: "); scanf("%lf", &num2); printf("Enter the third number: "); scanf("%lf", &num3); printf("Numbers entered: %.2lf, %.2lf, %.2lf\n", num1, num2, num3); if (num1 >= num2) { if (num1 >= num3) { printf("%.2lf is the greatest number.\n", num1); } else { printf("%.2lf is the greatest number.\n", num3); } } else { // num2 > num1 if (num2 >= num3) { printf("%.2lf is the greatest number.\n", num2); } else { printf("%.2lf is the greatest number.\n", num3); } } return 0; } ``` === "Oracle (19c)" ```sql SET SERVEROUTPUT ON; DECLARE num1 NUMBER := &Enter_First_Number; num2 NUMBER := &Enter_Second_Number; num3 NUMBER := &Enter_Third_Number; BEGIN DBMS_OUTPUT.PUT_LINE('Numbers entered: ' || num1 || ', ' || num2 || ', ' || num3); IF num1 >= num2 THEN IF num1 >= num3 THEN DBMS_OUTPUT.PUT_LINE(num1 || ' is the greatest number.'); ELSE DBMS_OUTPUT.PUT_LINE(num3 || ' is the greatest number.'); END IF; ELSE -- num2 is greater than num1 IF num2 >= num3 THEN DBMS_OUTPUT.PUT_LINE(num2 || ' is the greatest number.'); ELSE DBMS_OUTPUT.PUT_LINE(num3 || ' is the greatest number.'); END IF; END IF; END; / ``` ## Explanation - **Java**: Uses nested `if-else` statements to compare numbers. `Scanner` handles `double` input. - **Python**: Similar nested `if-else` logic. `float()` converts input strings to numbers. - **C**: Employs nested `if-else` statements. `scanf("%lf", ...)` reads `double` inputs, and `printf("%.2lf\n", ...)` formats output. - **Oracle**: Implemented in PL/SQL. Uses nested `IF-ELSE` blocks. Substitution variables for interactive input. ## Complexity Analysis * **Time Complexity:** O(1) - A fixed number of comparisons are performed. * **Space Complexity:** O(1) - A fixed number of variables are used. ## Flowchart ```mermaid graph TD A[Start] --> B[Get num1] B --> C[Get num2] C --> D[Get num3] D --> E{num1 >= num2?} E -- Yes --> F{num1 >= num3?} F -- Yes --> G[Display num1] F -- No --> H[Display num3] E -- No --> I{num2 >= num3?} I -- Yes --> J[Display num2] I -- No --> H G --> K[End] H --> K J --> K
Sample Dry Run¶
| Step | num1 | num2 | num3 | Description |
|---|---|---|---|---|
| Input | 10 | 5 | 7 | User enters 10, 5, 7 |
num1 >= num2? |
10 | 5 | 7 | True (10 >= 5) |
num1 >= num3? |
10 | 5 | 7 | True (10 >= 7) |
| Output | 10 | - | - | Display "10 is the greatest number." |
| End | - | - | - | Program terminates |
| Input | 5 | 12 | 8 | User enters 5, 12, 8 |
num1 >= num2? |
5 | 12 | 8 | False (5 >= 12 is False) |
num2 >= num3? |
5 | 12 | 8 | True (12 >= 8) |
| Output | - | 12 | - | Display "12 is the greatest number." |
| End | - | - | - | Program terminates |
Practice Problems¶
Easy¶
- Modify the program to find the smallest of three numbers.
- Find the greatest of two numbers.
Medium¶
- Implement finding the greatest of N numbers (e.g., using an array/list and a loop).
- Find the second greatest number among three.
Hard¶
- Find the three greatest distinct numbers from a list of numbers.
"The computer does not care about your feelings, it only cares about your logic." - Anonymous
Greatest of Three Numbers (Using Logical Operators)¶
Concept Explanation¶
What is it?¶
This program finds the greatest among three numbers using a different approach to conditional logic
compared to nested if-else. Instead, it utilizes logical operators (like AND or &&) to combine
multiple comparison conditions within a single if or elif (else if) statement.
Why is it important?¶
Using logical operators can often make conditional statements more concise and sometimes more readable, especially when multiple conditions must all be true for a particular outcome. It demonstrates an alternative way to structure decision-making logic, which is crucial for writing efficient and clear code.
Where is it used?¶
- Filtering Data: Selecting records that meet several criteria simultaneously.
- Complex Validations: Checking if user input satisfies multiple conditions (e.g., a password must be long AND contain special characters).
- Control Flow: Directing program execution based on combined conditions in various algorithms.
Real-world example¶
Imagine deciding which of three cars is the "best." You might say, "Car A is the best IF it has the highest speed AND the highest fuel efficiency." This statement uses logical AND to combine two criteria to determine the best car.
Algorithm¶
- Start.
- Get three numbers (
num1,num2,num3) from the user. - Check if
num1is the greatest: a. Ifnum1 >= num2ANDnum1 >= num3, thennum1is the greatest. - Else, check if
num2is the greatest: a. Ifnum2 >= num1ANDnum2 >= num3, thennum2is the greatest. - Else,
num3must be the greatest. - Display the greatest number.
- End.
Edge Cases:
- Inputting non-numeric values (handled by language-specific error mechanisms or explicit validation).
- All numbers are equal: The program will correctly identify any of them as the "greatest" based on the >= operator.
- Two numbers are equal and greater than the third: e.g., (10, 10, 5) - the first condition met (num1 >= num2 && num1 >= num3) will correctly identify 10.
Implementations¶
import java.util.Scanner;
public class GreatestOfThreeLogicalOperators {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter the third number: ");
double num3 = scanner.nextDouble();
System.out.println("Numbers entered: " + num1 + ", " + num2 + ", " + num3);
if (num1 >= num2 && num1 >= num3) {
System.out.println(num1 + " is the greatest number.");
} else if (num2 >= num1 && num2 >= num3) {
System.out.println(num2 + " is the greatest number.");
} else {
System.out.println(num3 + " is the greatest number.");
}
scanner.close();
}
}
# Get three numbers from the user
num1_str = input("Enter the first number: ")
num1 = float(num1_str)
num2_str = input("Enter the second number: ")
num2 = float(num2_str)
num3_str = input("Enter the third number: ")
num3 = float(num3_str)
print(f"Numbers entered: {num1}, {num2}, {num3}")
if num1 >= num2 and num1 >= num3:
print(f"{num1} is the greatest number.")
elif num2 >= num1 and num2 >= num3:
print(f"{num2} is the greatest number.")
else:
print(f"{num3} is the greatest number.")
#include <stdio.h>
int main() {
double num1, num2, num3;
printf("Enter the first number: ");
scanf("%lf", &num1);
printf("Enter the second number: ");
scanf("%lf", &num2);
printf("Enter the third number: ");
scanf("%lf", &num3);
printf("Numbers entered: %.2lf, %.2lf, %.2lf\n", num1, num2, num3);
if (num1 >= num2 && num1 >= num3) {
printf("%.2lf is the greatest number.\n", num1);
} else if (num2 >= num1 && num2 >= num3) {
printf("%.2lf is the greatest number.\n", num2);
} else {
printf("%.2lf is the greatest number.\n", num3);
}
return 0;
}
SET SERVEROUTPUT ON;
DECLARE
num1 NUMBER := &Enter_First_Number;
num2 NUMBER := &Enter_Second_Number;
num3 NUMBER := &Enter_Third_Number;
BEGIN
DBMS_OUTPUT.PUT_LINE('Numbers entered: ' || num1 || ', ' || num2 || ', ' || num3);
IF num1 >= num2 AND num1 >= num3 THEN
DBMS_OUTPUT.PUT_LINE(num1 || ' is the greatest number.');
ELSIF num2 >= num1 AND num2 >= num3 THEN
DBMS_OUTPUT.PUT_LINE(num2 || ' is the greatest number.');
ELSE
DBMS_OUTPUT.PUT_LINE(num3 || ' is the greatest number.');
END IF;
END;
/
Explanation¶
- Java: Uses the logical AND operator (
&&) to combine conditions.if-else if-elsestructure efficiently determines the greatest. - Python: Employs the
andlogical operator withinif-elif-elsestatements. This approach is highly readable and Pythonic. - C: Uses the logical AND operator (
&&) to create compound conditions inif-else if-elsestatements. - Oracle: Implemented in PL/SQL. Uses the
ANDlogical operator withinIF-ELSIF-ELSEstructure to check combined conditions.
Complexity Analysis¶
- Time Complexity: O(1) - A fixed number of comparisons are performed.
- Space Complexity: O(1) - A fixed number of variables are used.
Flowchart¶
graph TD
A[Start] --> B[Get num1]
B --> C[Get num2]
C --> D[Get num3]
D --> E{num1 >= num2 AND num1 >= num3?}
E -- Yes --> F[Display num1]
E -- No --> G{num2 >= num1 AND num2 >= num3?}
G -- Yes --> H[Display num2]
G -- No --> I[Display num3]
F --> J[End]
H --> J
I --> J
Sample Dry Run¶
| Step | num1 | num2 | num3 | Condition num1 >= num2 && num1 >= num3 |
Condition num2 >= num1 && num2 >= num3 |
Description |
|---|---|---|---|---|---|---|
| Input | 10 | 5 | 7 | True (10>=5 && 10>=7) = True | - | User enters 10, 5, 7 |
| Output | 10 | - | - | - | - | Display "10 is the greatest number." |
| End | - | - | - | - | - | Program terminates |
| Input | 5 | 12 | 8 | False | True (12>=5 && 12>=8) = True | User enters 5, 12, 8 |
| Output | - | 12 | - | - | - | Display "12 is the greatest number." |
| End | - | - | - | - | - | Program terminates |
Practice Problems¶
Easy¶
- Modify the program to find the smallest of three numbers using logical operators.
- Find the greatest of four numbers using logical operators.
Medium¶
- Implement a function that takes three boolean values and returns true if exactly two of them are true.
- Refactor a program using nested
if-elseto use logical operators for greater readability.
Hard¶
- Given three numbers, determine if they can form the sides of a triangle (a + b > c, a + c > b, b + c > a) using logical operators.
"Programming is the art of telling another human being what one wants the computer to do." - Donald Knuth
I will perform the `replace` operation with the entire file content, effectively appending the new section. **Old String (the entire content of the file from the last successful read):** ```markdown --- title: Greatest of Three Numbers description: Multi-language implementations to find the greatest among three numbers using nested conditional statements. keywords: - programming - java - python - c - oracle - greatest number - maximum - conditional logic - nested if difficulty: Beginner estimated_time: 15 minutes prerequisites: - Basic variables - Conditional statements (if-else) - Comparison operators - Input/Output operations --- # Greatest of Three Numbers ## Concept Explanation ### What is it? This program determines the largest value among three given numbers. It's a fundamental exercise in applying conditional logic (specifically nested `if-else` statements) to compare multiple values and make a decision based on those comparisons. ### Why is it important? Finding the maximum or minimum of a set of values is a very common task in programming. It forms the basis of many algorithms, from simple data processing to more complex sorting or selection processes. Understanding how to compare multiple values effectively is a core programming skill. ### Where is it used? - **Data Analysis**: Finding the highest score, maximum temperature, or peak sales. - **Game Development**: Determining the highest stat of a character, the best score, or comparing strengths. - **Resource Allocation**: Identifying the most available resource among several options. - **Ranking Systems**: Basic logic for ranking items or entities. ### Real-world example Imagine you have three friends, each with a different amount of money. To find out who has the most money, you compare their amounts. If Alice has more than Bob, you then compare Alice's amount with Charlie's to see if Alice still has the most. This sequential comparison mimics the logic of nested `if-else` statements. --- ## Algorithm 1. Start. 2. Get three numbers (`num1`, `num2`, `num3`) from the user. 3. Assume `num1` is the greatest initially. 4. Compare `num1` with `num2`: a. If `num1` is greater than or equal to `num2`: i. Compare `num1` with `num3`. ii. If `num1` is greater than or equal to `num3`, then `num1` is the greatest. iii. Else, `num3` is the greatest. b. Else (`num2` is greater than `num1`): i. Compare `num2` with `num3`. ii. If `num2` is greater than or equal to `num3`, then `num2` is the greatest. iii. Else, `num3` is the greatest. 5. Display the greatest number. 6. End. **Edge Cases:** - Inputting non-numeric values (handled by language-specific error mechanisms or explicit validation). - All numbers are equal: The program should correctly identify any of them as the "greatest." - Two numbers are equal and greater than the third: e.g., (10, 10, 5) - should correctly identify 10. --- ## Implementations === "Java (JDK 17)" ```java import java.util.Scanner; public class GreatestOfThreeNestedIf { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the first number: "); double num1 = scanner.nextDouble(); System.out.print("Enter the second number: "); double num2 = scanner.nextDouble(); System.out.print("Enter the third number: "); double num3 = scanner.nextDouble(); System.out.println("Numbers entered: " + num1 + ", " + num2 + ", " + num3); if (num1 >= num2) { if (num1 >= num3) { System.out.println(num1 + " is the greatest number."); } else { System.out.println(num3 + " is the greatest number."); } } else { // num2 > num1 if (num2 >= num3) { System.out.println(num2 + " is the greatest number."); } else { System.out.println(num3 + " is the greatest number."); } } scanner.close(); } } ``` === "Python (3.10+)" ```python # Get three numbers from the user num1_str = input("Enter the first number: ") num1 = float(num1_str) num2_str = input("Enter the second number: ") num2 = float(num2_str) num3_str = input("Enter the third number: ") num3 = float(num3_str) print(f"Numbers entered: {num1}, {num2}, {num3}") if num1 >= num2: if num1 >= num3: print(f"{num1} is the greatest number.") else: print(f"{num3} is the greatest number.") else: # num2 > num1 if num2 >= num3: print(f"{num2} is the greatest number.") else: print(f"{num3} is the greatest number.") ``` === "C (C99)" ```c #include <stdio.h> int main() { double num1, num2, num3; printf("Enter the first number: "); scanf("%lf", &num1); printf("Enter the second number: "); scanf("%lf", &num2); printf("Enter the third number: "); scanf("%lf", &num3); printf("Numbers entered: %.2lf, %.2lf, %.2lf\n", num1, num2, num3); if (num1 >= num2) { if (num1 >= num3) { printf("%.2lf is the greatest number.\n", num1); } else { printf("%.2lf is the greatest number.\n", num3); } } else { // num2 > num1 if (num2 >= num3) { printf("%.2lf is the greatest number.\n", num2); } else { printf("%.2lf is the greatest number.\n", num3); } } return 0; } ``` === "Oracle (19c)" ```sql SET SERVEROUTPUT ON; DECLARE num1 NUMBER := &Enter_First_Number; num2 NUMBER := &Enter_Second_Number; num3 NUMBER := &Enter_Third_Number; BEGIN DBMS_OUTPUT.PUT_LINE('Numbers entered: ' || num1 || ', ' || num2 || ', ' || num3); IF num1 >= num2 THEN IF num1 >= num3 THEN DBMS_OUTPUT.PUT_LINE(num1 || ' is the greatest number.'); ELSE DBMS_OUTPUT.PUT_LINE(num3 || ' is the greatest number.'); END IF; ELSE -- num2 is greater than num1 IF num2 >= num3 THEN DBMS_OUTPUT.PUT_LINE(num2 || ' is the greatest number.'); ELSE DBMS_OUTPUT.PUT_LINE(num3 || ' is the greatest number.'); END IF; END IF; END; / ``` ## Explanation - **Java**: Uses nested `if-else` statements to compare numbers. `Scanner` handles `double` input. - **Python**: Similar nested `if-else` logic. `float()` converts input strings to numbers. - **C**: Employs nested `if-else` statements. `scanf("%lf", ...)` reads `double` inputs, and `printf("%.2lf\n", ...)` formats output. - **Oracle**: Implemented in PL/SQL. Uses nested `IF-ELSE` blocks. Substitution variables for interactive input. ## Complexity Analysis * **Time Complexity:** O(1) - A fixed number of comparisons are performed. * **Space Complexity:** O(1) - A fixed number of variables are used. ## Flowchart ```mermaid graph TD A[Start] --> B[Get num1] B --> C[Get num2] C --> D[Get num3] D --> E{num1 >= num2?} E -- Yes --> F{num1 >= num3?} F -- Yes --> G[Display num1] F -- No --> H[Display num3] E -- No --> I{num2 >= num3?} I -- Yes --> J[Display num2] I -- No --> H G --> K[End] H --> K J --> K
Sample Dry Run¶
| Step | num1 | num2 | num3 | Description |
|---|---|---|---|---|
| Input | 10 | 5 | 7 | User enters 10, 5, 7 |
num1 >= num2? |
10 | 5 | 7 | True (10 >= 5) |
num1 >= num3? |
10 | 5 | 7 | True (10 >= 7) |
| Output | 10 | - | - | Display "10 is the greatest number." |
| End | - | - | - | Program terminates |
| Input | 5 | 12 | 8 | User enters 5, 12, 8 |
num1 >= num2? |
5 | 12 | 8 | False (5 >= 12 is False) |
num2 >= num3? |
5 | 12 | 8 | True (12 >= 8) |
| Output | - | 12 | - | Display "12 is the greatest number." |
| End | - | - | - | Program terminates |
Practice Problems¶
Easy¶
- Modify the program to find the smallest of three numbers.
- Find the greatest of two numbers.
Medium¶
- Implement finding the greatest of N numbers (e.g., using an array/list and a loop).
- Find the second greatest number among three.
Hard¶
- Find the three greatest distinct numbers from a list of numbers.
"The computer does not care about your feelings, it only cares about your logic." - Anonymous
Greatest of Three Numbers (Using Logical Operators)¶
Concept Explanation¶
What is it?¶
This program finds the greatest among three numbers using a different approach to conditional logic
compared to nested if-else. Instead, it utilizes logical operators (like AND or &&) to combine
multiple comparison conditions within a single if or elif (else if) statement.
Why is it important?¶
Using logical operators can often make conditional statements more concise and sometimes more readable, especially when multiple conditions must all be true for a particular outcome. It demonstrates an alternative way to structure decision-making logic, which is crucial for writing efficient and clear code.
Where is it used?¶
- Filtering Data: Selecting records that meet several criteria simultaneously.
- Complex Validations: Checking if user input satisfies multiple conditions (e.g., a password must be long AND contain special characters).
- Control Flow: Directing program execution based on combined conditions in various algorithms.
Real-world example¶
Imagine deciding which of three cars is the "best." You might say, "Car A is the best IF it has the highest speed AND the highest fuel efficiency." This statement uses logical AND to combine two criteria to determine the best car.
Algorithm¶
- Start.
- Get three numbers (
num1,num2,num3) from the user. - Check if
num1is the greatest: a. Ifnum1 >= num2ANDnum1 >= num3, thennum1is the greatest. - Else, check if
num2is the greatest: a. Ifnum2 >= num1ANDnum2 >= num3, thennum2is the greatest. - Else,
num3must be the greatest. - Display the greatest number.
- End.
Edge Cases:
- Inputting non-numeric values (handled by language-specific error mechanisms or explicit validation).
- All numbers are equal: The program will correctly identify any of them as the "greatest" based on the >= operator.
- Two numbers are equal and greater than the third: e.g., (10, 10, 5) - the first condition met (num1 >= num2 && num1 >= num3) will correctly identify 10.
Implementations¶
import java.util.Scanner;
public class GreatestOfThreeLogicalOperators {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter the third number: ");
double num3 = scanner.nextDouble();
System.out.println("Numbers entered: " + num1 + ", " + num2 + ", " + num3);
if (num1 >= num2 && num1 >= num3) {
System.out.println(num1 + " is the greatest number.");
} else if (num2 >= num1 && num2 >= num3) {
System.out.println(num2 + " is the greatest number.");
} else {
System.out.println(num3 + " is the greatest number.");
}
scanner.close();
}
}
# Get three numbers from the user
num1_str = input("Enter the first number: ")
num1 = float(num1_str)
num2_str = input("Enter the second number: ")
num2 = float(num2_str)
num3_str = input("Enter the third number: ")
num3 = float(num3_str)
print(f"Numbers entered: {num1}, {num2}, {num3}")
if num1 >= num2 and num1 >= num3:
print(f"{num1} is the greatest number.")
elif num2 >= num1 and num2 >= num3:
print(f"{num2} is the greatest number.")
else:
print(f"{num3} is the greatest number.")
#include <stdio.h>
int main() {
double num1, num2, num3;
printf("Enter the first number: ");
scanf("%lf", &num1);
printf("Enter the second number: ");
scanf("%lf", &num2);
printf("Enter the third number: ");
scanf("%lf", &num3);
printf("Numbers entered: %.2lf, %.2lf, %.2lf\n", num1, num2, num3);
if (num1 >= num2 && num1 >= num3) {
printf("%.2lf is the greatest number.\n", num1);
} else if (num2 >= num1 && num2 >= num3) {
printf("%.2lf is the greatest number.\n", num2);
} else {
printf("%.2lf is the greatest number.\n", num3);
}
return 0;
}
SET SERVEROUTPUT ON;
DECLARE
num1 NUMBER := &Enter_First_Number;
num2 NUMBER := &Enter_Second_Number;
num3 NUMBER := &Enter_Third_Number;
BEGIN
DBMS_OUTPUT.PUT_LINE('Numbers entered: ' || num1 || ', ' || num2 || ', ' || num3);
IF num1 >= num2 AND num1 >= num3 THEN
DBMS_OUTPUT.PUT_LINE(num1 || ' is the greatest number.');
ELSIF num2 >= num1 AND num2 >= num3 THEN
DBMS_OUTPUT.PUT_LINE(num2 || ' is the greatest number.');
ELSE
DBMS_OUTPUT.PUT_LINE(num3 || ' is the greatest number.');
END IF;
END;
/
Explanation¶
- Java: Uses the logical AND operator (
&&) to combine conditions.if-else if-elsestructure efficiently determines the greatest. - Python: Employs the
andlogical operator withinif-elif-elsestatements. This approach is highly readable and Pythonic. - C: Uses the logical AND operator (
&&) to create compound conditions inif-else if-elsestatements. - Oracle: Implemented in PL/SQL. Uses the
ANDlogical operator withinIF-ELSIF-ELSEstructure to check combined conditions.
Complexity Analysis¶
- Time Complexity: O(1) - A fixed number of comparisons are performed.
- Space Complexity: O(1) - A fixed number of variables are used.
Flowchart¶
graph TD
A[Start] --> B[Get num1]
B --> C[Get num2]
C --> D[Get num3]
D --> E{num1 >= num2 AND num1 >= num3?}
E -- Yes --> F[Display num1]
E -- No --> G{num2 >= num1 AND num2 >= num3?}
G -- Yes --> H[Display num2]
G -- No --> I[Display num3]
F --> J[End]
H --> J
I --> J
Sample Dry Run¶
| Step | num1 | num2 | num3 | Condition num1 >= num2 && num1 >= num3 |
Condition num2 >= num1 && num2 >= num3 |
Description |
|---|---|---|---|---|---|---|
| Input | 10 | 5 | 7 | True (10>=5 && 10>=7) = True | - | User enters 10, 5, 7 |
| Output | 10 | - | - | - | - | Display "10 is the greatest number." |
| End | - | - | - | - | - | Program terminates |
| Input | 5 | 12 | 8 | False | True (12>=5 && 12>=8) = True | User enters 5, 12, 8 |
| Output | - | 12 | - | - | - | Display "12 is the greatest number." |
| End | - | - | - | - | - | Program terminates |
Practice Problems¶
Easy¶
- Modify the program to find the smallest of three numbers using logical operators.
- Find the greatest of four numbers using logical operators.
Medium¶
- Implement a function that takes three boolean values and returns true if exactly two of them are true.
- Refactor a program using nested
if-elseto use logical operators for greater readability.
Hard¶
- Given three numbers, determine if they can form the sides of a triangle (a + b > c, a + c > b, b + c > a) using logical operators.
"Programming is the art of telling another human being what one wants the computer to do." - Donald Knuth