Conditionals#

https://files.realpython.com/media/t.78f3bacaa261.png

Overview#

Definition

Conditional statements are essential programming constructs that allow us to make decisions based on certain conditions. These statements evaluate an expression and execute specific code blocks based on whether the condition is true or false. The most common conditional statements are if, else if, else, nested if, and switch.

Use Cases

Decision-making

Executing different code based on specific conditions.

Input Validation

Checking user input for validity before processing it.

Flow Control

Controlling program flow based on conditions.

Error Handling

Handling specific error conditions.

Menu Selection

Implementing menu-driven applications.

Pros & Cons

👍
Improved Control

Allows the program to make dynamic decisions during runtime.

Readable Code

Conditional statements enhance code readability by expressing intent clearly.

Saves Resources

Prevents unnecessary execution of code, optimizing resource utilization.

👎
Complexity

Multiple nested conditions can make code harder to maintain and understand.

Code Duplication

Repeating code blocks for similar conditions can lead to code duplication.

Potential Bugs

Incorrect conditions or missing cases can introduce bugs.

if, else if, else Syntax#


 2#include <iostream>
 3using namespace std;
 4
 5int main() {
 6    int exam_score;
 7    int passing_threshold = 60;
 8
 9    cout << "Enter your exam score: ";
10    cin >> exam_score;
11
12    if (exam_score >= passing_threshold) {
13        cout << "Congratulations! You passed the exam." << endl;
14    } else {
15        cout << "Unfortunately, you did not pass the exam. Please try again." << endl;
16    }
17
18    return 0;
19}
1passing_threshold = 60
2
3exam_score = int(input("Enter your exam score: "))
4
5if exam_score >= passing_threshold:
6    print("Congratulations! You passed the exam.")
7else:
8    print("Unfortunately, you did not pass the exam. Please try again.")
 1import java.util.Scanner;
 2
 3public class Main {
 4    public static void main(String[] args) {
 5        Scanner scanner = new Scanner(System.in);
 6        int passing_threshold = 60;
 7
 8        System.out.print("Enter your exam score: ");
 9        int exam_score = scanner.nextInt();
10
11        if (exam_score >= passing_threshold) {
12            System.out.println("Congratulations! You passed the exam.");
13        } else {
14            System.out.println("Unfortunately, you did not pass the exam. Please try again.");
15        }
16    }
17}
 1use std::io;
 2
 3fn main() {
 4    let passing_threshold = 60;
 5
 6    println!("Enter your exam score: ");
 7    let mut input = String::new();
 8    io::stdin().read_line(&mut input).expect("Failed to read line");
 9    let exam_score: i32 = input.trim().parse().expect("Please enter a valid number");
10
11    if exam_score >= passing_threshold {
12        println!("Congratulations! You passed the exam.");
13    } else {
14        println!("Unfortunately, you did not pass the exam. Please try again.");
15    }
16}
 1package main
 2
 3import (
 4    "fmt"
 5)
 6
 7func main() {
 8    var passing_threshold int = 60
 9    var exam_score int
10
11    fmt.Print("Enter your exam score: ")
12    fmt.Scan(&exam_score)
13
14    if exam_score >= passing_threshold {
15        fmt.Println("Congratulations! You passed the exam.")
16    } else {
17        fmt.Println("Unfortunately, you did not pass the exam. Please try again.")
18    }
19}

switch / match Syntax#

FUNCTION name_of_function (parameter1, parameter2, ...):
    // Function implementation here
    RETURN result

Rules of Use :

 1#include <iostream>
 2using namespace std;
 3
 4int main() {
 5    int day_number;
 6
 7    cout << "Enter a day number (1 to 7): ";
 8    cin >> day_number;
 9
10    switch (day_number) {
11        case 1:
12            cout << "Sunday" << endl;
13            break;
14        case 2:
15            cout << "Monday" << endl;
16            break;
17        case 3:
18            cout << "Tuesday" << endl;
19            break;
20        case 4:
21            cout << "Wednesday" << endl;
22            break;
23        case 5:
24            cout << "Thursday" << endl;
25            break;
26        case 6:
27            cout << "Friday" << endl;
28            break;
29        case 7:
30            cout << "Saturday" << endl;
31            break;
32        default:
33            cout << "Invalid day number. Please enter a number between 1 and 7." << endl;
34            break;
35    }
36
37    return 0;
38}

Rules of Use :

 1day_number = int(input("Enter a day number (1 to 7): "))
 2
 3if day_number == 1:
 4    print("Sunday")
 5elif day_number == 2:
 6    print("Monday")
 7elif day_number == 3:
 8    print("Tuesday")
 9elif day_number == 4:
10    print("Wednesday")
11elif day_number == 5:
12    print("Thursday")
13elif day_number == 6:
14    print("Friday")
15elif day_number == 7:
16    print("Saturday")
17else:
18    print("Invalid day number. Please enter a number between 1 and 7.")

Rules of Use :

 1import java.util.Scanner;
 2
 3public class Main {
 4    public static void main(String[] args) {
 5        Scanner scanner = new Scanner(System.in);
 6        int day_number;
 7
 8        System.out.print("Enter a day number (1 to 7): ");
 9        day_number = scanner.nextInt();
10
11        switch (day_number) {
12            case 1:
13                System.out.println("Sunday");
14                break;
15            case 2:
16                System.out.println("Monday");
17                break;
18            case 3:
19                System.out.println("Tuesday");
20                break;
21            case 4:
22                System.out.println("Wednesday");
23                break;
24            case 5:
25                System.out.println("Thursday");
26                break;
27            case 6:
28                System.out.println("Friday");
29                break;
30            case 7:
31                System.out.println("Saturday");
32                break;
33            default:
34                System.out.println("Invalid day number. Please enter a number between 1 and 7.");
35                break;
36        }
37    }
38}

Rules of Use :

 1use std::io;
 2
 3fn main() {
 4    let mut day_number = String::new();
 5
 6    println!("Enter a day number (1 to 7): ");
 7    io::stdin().read_line(&mut day_number).expect("Failed to read line");
 8    let day_number: i32 = day_number.trim().parse().expect("Please enter a valid number");
 9
10    match day_number {
11        1 => println!("Sunday"),
12        2 => println!("Monday"),
13        3 => println!("Tuesday"),
14        4 => println!("Wednesday"),
15        5 => println!("Thursday"),
16        6 => println!("Friday"),
17        7 => println!("Saturday"),
18        _ => println!("Invalid day number. Please enter a number between 1 and 7."),
19    }
20}

Rules of Use :

 1package main
 2
 3import (
 4    "fmt"
 5)
 6
 7func main() {
 8    var day_number int
 9
10    fmt.Print("Enter a day number (1 to 7): ")
11    fmt.Scan(&day_number)
12
13    switch day_number {
14    case 1:
15        fmt.Println("Sunday")
16    case 2:
17        fmt.Println("Monday")
18    case 3:
19        fmt.Println("Tuesday")
20    case 4:
21        fmt.Println("Wednesday")
22    case 5:
23        fmt.Println("Thursday")
24    case 6:
25        fmt.Println("Friday")
26    case 7:
27        fmt.Println("Saturday")
28    default:
29        fmt.Println("Invalid day number. Please enter a number between 1 and 7.")
30    }
31}