C Programming Decision Making Statements if, if else, nested if, switch case Step by step Implementation and Top 10 Questions and Answers
 .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    Last Update: April 01, 2025      19 mins read      Difficulty-Level: beginner

C Programming: Decision Making Statements

In C programming, decision making statements are used to control the flow of a program based on specific conditions. These statements allow a program to execute different sections of code depending on whether certain conditions hold true or false, thus enabling more dynamic and intelligent behavior. The primary decision-making statements in C are if, if-else, nested if, and switch-case.

1. The if Statement

The if statement is the most basic form of decision making statements in C. It executes a block of code only if a specified condition evaluates to true (non-zero). The syntax of the if statement is as follows:

if (condition) {
   // Block of code to be executed if the condition is true
}

Example:

#include <stdio.h>

int main() {
    int number = 5;

    if (number > 0) {
        printf("The number is positive.\n");
    }

    return 0;
}

In this example, the program checks whether the variable number is greater than 0. If the condition holds true, it prints "The number is positive."

2. The if-else Statement

The if-else statement is an extension of the if statement that provides an alternative execution path if the initial if condition evaluates to false. The syntax is:

if (condition) {
   // Block of code to be executed if the condition is true
} else {
   // Block of code to be executed if the condition is false
}

Example:

#include <stdio.h>

int main() {
    int number = -10;

    if (number > 0) {
        printf("The number is positive.\n");
    } else {
        printf("The number is non-positive.\n");
    }

    return 0;
}

Here, since number is less than 0, the program will print "The number is non-positive."

3. The else-if Ladder

When you need to evaluate multiple mutually exclusive conditions, you can use multiple if-else statements chained together using else if. This allows for more complex decision-making structures.

The syntax is as follows:

if (condition1) {
   // Block of code to be executed if condition1 is true
} else if (condition2) {
   // Block of code to be executed if condition1 is false but condition2 is true
} else if (condition3) {
   // Block of code to be executed if both condition1 and condition2 are false but condition3 is true
} ...
else {
   // Block of code to be executed if all conditions above are false
}

Example:

#include <stdio.h>

int main() {
    int number = 0;

    if (number > 0) {
        printf("The number is positive.\n");
    } else if (number < 0) {
        printf("The number is negative.\n");
    } else {
        printf("The number is zero.\n");
    }

    return 0;
}

In this example, the program first checks if number is greater than 0. If not, it then checks if it is less than 0. If both conditions fail, it concludes that number must be zero.

4. Nested if Statements

Nested if statements occur when one if statement is placed inside another. This is useful when you need to evaluate multiple independent conditions.

The syntax is:

if (condition1) {
    if (condition2) {
        // Code to be executed if both condition1 and condition2 are true
    }
    // More code to be executed if only condition1 is true
} else {
    // Code to be executed if condition1 is false
}

Example:

#include <stdio.h>

int main() {
    int num = 65;

    if (num >= 60) {
        if (num <= 100) {
            printf("The number is between 60 and 100.\n");
        } else {
            printf("Invalid score.\n");
        }
    } else {
        printf("The number is less than 60.\n");
    }

    return 0;
}

Here, the program checks if num is between 60 and 100 by nesting if statements within each other.

5. The switch-case Statement

The switch-case statement is used to execute one block of code from several possible alternatives based on the value of a variable. This is particularly useful when the value being tested can take one of several specific constant values.

The syntax is:

switch(expression) {
    case constant1:
       // Code to be executed if expression == constant1
       break;
    case constant2:
       // Code to be executed if expression == constant2
       break;
    ...
    default:
       // Code to be executed if expression does not match any other case
}

The break statement is crucial as it prevents fall-through (execution of subsequent cases) once a particular case is matched.

Example:

#include <stdio.h>

int main() {
    int day = 3;
    
    switch(day) {
        case 1:
            printf("Monday\n");
            break;
        case 2:
            printf("Tuesday\n");
            break;
        case 3:
            printf("Wednesday\n");
            break;
        case 4:
            printf("Thursday\n");
            break;
        case 5:
            printf("Friday\n");
            break;
        case 6:
            printf("Saturday\n");
            break;
        case 7:
            printf("Sunday\n");
            break;
        default:
            printf("Invalid day number\n");
    }

    return 0;
}

In this example, the program will print "Wednesday" because the value stored in day is 3.

Important Information

  • Conditions: Conditions in if and if-else statements must be enclosed in parentheses () and should evaluate to a boolean value (true/non-zero or false/zero).

  • Blocks of Code: Code blocks associated with each condition or case label in switch-case statements are enclosed in curly braces {}. This delineates the scope of the variables declared within these blocks.

  • Logical Operators: C provides logical operators (&&, ||, !) that can be utilized to form compound conditions in if statements.

  • Bitwise Operators: Bitwise operators (&, |, ^, ~, <<, >>) can also be used in conditions, often for more advanced bit manipulation tasks.

  • Multiple Cases in Switch: You can group multiple cases together in a switch-case statement by omitting the break statement after the first case.

    switch(number) {
        case 1:
        case 2:
        case 3:
           printf("Number is between 1 and 3\n"); 
           break;
        default:
           printf("Number is not between 1 and 3\n");
    }
    
  • Default Case: The default case in a switch-case statement is optional, but it's a good practice to include it to cover unexpected values, providing a fallback option.

  • Performance: switch-case statements can be more efficient than a long if-else ladder, especially when there are many discrete cases to consider, as they enable the compiler to generate a jump table, potentially reducing execution time.

By mastering these decision-making statements, you can create programs that react intelligently to varying inputs and conditions, making your software more flexible and robust.




Examples, Set Route and Run the Application: A Step-by-Step Guide to C Programming's Decision Making Statements—If, If Else, Nested If, Switch Case

Introduction

C programming language provides decision-making statements that allow the program to choose between two or more options depending on certain conditions. These statements include if, if-else, nested if, and switch. Below is a step-by-step guide for beginners to understand how these constructs work through examples and practical implementation.


Step 1: Setting Up Your Development Environment

Beginners often overlook the first step: setting up their development environment. For C programming, the most common tools are:

  • IDE: Visual Studio Code, Code::Blocks, CLion.
  • Compiler: GCC (GNU Compiler Collection), MSVC (Microsoft Visual C++ Compiler).

For this guide, we will use an IDE called [Code::Blocks]. Here’s how you can set it up:

  1. Download and Install Code::Blocks:

    • Go to Code::Blocks Downloads and download a version suitable for your operating system.
    • Follow the installation instructions.
  2. Create a New Project:

    • Open Code::Blocks.
    • Click on File -> New -> Project.
    • Choose Console Application under GNU GCC Compiler and click Go.
    • Enter a Project Title (e.g., DecisionMaking) and Save location.
    • Select Console application under Project type and C under Language.
    • Click Next, Finish.
  3. Configure Compiler (if necessary):

    • For most users, the default compiler settings should be fine. However, ensure GCC is installed on your machine.
      • On Windows, you might need to install MinGW (Minimalist GNU for Windows).
  4. Write Your First Program:

    • Open main.c which is created by default.
    • Write a simple Hello World program to test your setup.
#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}
  1. Compile and Run Your Program:
    • Use F9 to compile and run your code.
    • You should see "Hello, World!" printed in the console.

Step 2: Understanding and Using if Statement

The if statement allows a program to execute a specific block of code when a specified condition is true.

Example:

#include <stdio.h>

int main() {
    int number = 10;

    if (number > 0) {
        printf("Number is positive.\n");
    }

    return 0;
}

Steps to Implement:

  1. Open Your Project: In Code::Blocks, go to File -> Open Project and open the DecisionMaking project.
  2. Edit main.c: Replace existing code with the if example snippet provided.
  3. Save and Compile: Press Ctrl+S to save and F9 to compile and run.
  4. Check Output: The output should display: "Number is positive.".

Step 3: Understanding and Using if-else Statement

The if-else statement is used when you need to perform two different actions based on whether a condition is true or false.

Example:

#include <stdio.h>

int main() {
    int number = -5;

    if (number > 0) {
        printf("Number is positive.\n");
    } else {
        printf("Number is non-positive.\n");
    }

    return 0;
}

Steps to Implement:

  1. Edit main.c: Replace the existing if example with the if-else example provided.
  2. Save and Compile: Press Ctrl+S to save and F9 to compile and run.
  3. Check Output: The output should display: "Number is non-positive.".

Step 4: Understanding and Using nested if Statement

Nested if statements occur when one if-else statement is inside another if-else statement. This is used when multiple conditions need to be checked sequentially.

Example:

#include <stdio.h>

int main() {
    int number = 15;

    if (number > 0) {
        printf("Number is positive.\n");
        
        if (number % 2 == 0) {
            printf("Number is even.\n");
        } else {
            printf("Number is odd.\n");
        }
    } else {
        printf("Number is non-positive.\n");
    }

    return 0;
}

Steps to Implement:

  1. Edit main.c: Replace the existing if-else example with the nested if example provided.
  2. Save and Compile: Press Ctrl+S to save and F9 to compile and run.
  3. Check Output: The output should display:
    Number is positive.
    Number is odd.
    

Step 5: Understanding and Using switch Statement

The switch statement provides a more organized way to handle multiple conditions when a variable is equal to one of many values.

Example:

#include <stdio.h>

int main() {
    char grade = 'B';

    switch(grade) {
        case 'A':
            printf("Excellent!\n");
            break;
        case 'B':
            printf("Good job!\n");
            break;
        case 'C':
            printf("Well done\n");
            break;
        case 'D':
            printf("You passed\n");
            break;
        case 'F':
            printf("Better try again\n");
            break;
        default:
            printf("Invalid grade\n");
    }

    printf("Your grade is: %c\n", grade);
    
    return 0;
}

Steps to Implement:

  1. Edit main.c: Replace the existing nested if example with the switch example provided.
  2. Save and Compile: Press Ctrl+S to save and F9 to compile and run.
  3. Check Output: The output should display:
    Good job!
    Your grade is: B
    

Summary

By now, you should have a good understanding of how if, if-else, nested if, and switch statements work in C programming. You've also learned how to set up your development environment and implement these constructs practically. Always practice coding to reinforce your learning, and don’t hesitate to experiment with different conditions and inputs.

Happy Coding!




Certainly! Here’s a comprehensive guide providing the "Top 10 Questions and Answers" on "C Programming Decision Making Statements - if, if else, nested if, switch case" under 700 words:


Top 10 Questions and Answers on C Programming Decision Making Statements: if, if-else, Nested if, Switch Case

1. What is a Decision Making Statement in C?

Answer: In C Programming, decision making statements are used to control the flow of execution based on certain conditions. The decisions are made using logical and relational operators. Common decision making statements in C include if, if-else, nested if, and switch statements.

2. What is the syntax of the if statement in C?

Answer: The if statement in C is used to execute a block of code only if a specified condition is true. The basic syntax of the if statement is:

if (condition) {
    // Code to be executed if condition is true
}

Example:

int num = 10;
if (num > 0) {
    printf("Number is positive");
}

3. How does the if-else statement differ from the if statement in C?

Answer: The if-else statement in C allows you to execute one block of code if a condition is true and another block of code if the condition is false. It extends the functionality of the if statement.

Syntax:

if (condition) {
    // Code to be executed if condition is true
} else {
    // Code to be executed if condition is false
}

Example:

int num = -5;
if (num > 0) {
    printf("Number is positive");
} else {
    printf("Number is not positive");
}

4. Can you explain how nested if statements work in C with an example?

Answer: Nested if statements in C allow for multiple levels of decision making within a program. An if statement can be inside another if or else block, creating a nested structure. This is useful when more than one condition must be checked in sequence.

Syntax:

if (condition1) {
    if (condition2) {
        // Code to be executed if both condition1 and condition2 are true
    }
} else {
    // Code to be executed if condition1 is false
}

Example:

int age = 18;
int isStudent = 1;
if (age >= 18) {
    if (isStudent) {
        printf("You are an adult student.");
    } else {
        printf("You are an adult non-student.");
    }
} else {
    printf("You are not an adult.");
}

5. What is a switch statement in C, and when would you use it?

Answer: The switch statement in C is used to execute one block of code among many based on the value of a variable or an expression. It is often used as a cleaner alternative to multiple if-else statements when dealing with discrete values.

Syntax:

switch (expression) {
    case constant1:
        // Code to be executed if expression == constant1
        break;
    case constant2:
        // Code to be executed if expression == constant2
        break;
    default:
        // Code to be executed if none of the above cases match
}

Example:

int day = 3;
switch (day) {
    case 1:
        printf("Monday");
        break;
    case 2:
        printf("Tuesday");
        break;
    case 3:
        printf("Wednesday");
        break;
    default:
        printf("Invalid Day");
}

6. What is the role of the break statement in a switch block in C?

Answer: The break statement in a switch block is crucial as it terminates the switch statement once a matching case is executed. Without break, the control will continue to flow through subsequent cases, a phenomenon known as "fall-through." The break statement prevents this and ensures that only the intended block of code runs.

Example:

int choice = 2;
switch (choice) {
    case 1:
        printf("Choice 1 selected");
        break;
    case 2:
        printf("Choice 2 selected");
        break;
    case 3:
        printf("Choice 3 selected");
        break;
    default:
        printf("Invalid Choice");
}

7. Can a switch statement in C handle expressions of type float or double?

Answer: No, the switch statement in C cannot handle expressions of type float or double. The expression in a switch statement must evaluate to an integer type, such as char, int, short, or enum. This is because case labels must be compile-time constants, which cannot be float or double.

Example:

float grade = 3.5;
// The following is invalid in C
switch (grade) {
    case 3.0:
        printf("Good");
        break;
    case 3.5:
        printf("Very Good");
        break;
    default:
        printf("Invalid Grade");
}

Solution: To handle float or double values, use an if-else statement.

8. How does the switch statement handle multiple cases with the same code block in C?

Answer: In C, you can handle multiple cases with the same code block by omitting the break statement after the desired cases. This allows the control flow to pass through several cases until a break statement is encountered.

Example:

int number = 2;
switch (number) {
    case 1:
    case 2:
    case 3:
        printf("Number is between 1 and 3");
        break;
    case 4:
        printf("Number is 4");
        break;
    default:
        printf("Number is greater than 4 or less than 1");
}

9. What are the advantages of using switch statements over multiple if-else statements?

Answer: Using switch statements instead of multiple if-else statements can offer several advantages:

  • Readability: switch statements make the code cleaner and more organized, especially when dealing with multiple discrete cases.
  • Efficiency: switch statements can be more efficient than nested if-else statements for certain compilers, as they can be optimized to use jump tables.
  • Clarification: It clearly indicates that several cases are being evaluated against the same expression, making the code easier to understand.

Example:

// Using if-else
int day = 3;
if (day == 1) printf("Monday");
else if (day == 2) printf("Tuesday");
else if (day == 3) printf("Wednesday");
// ... and so on

// Using switch
switch (day) {
    case 1:
        printf("Monday");
        break;
    case 2:
        printf("Tuesday");
        break;
    case 3:
        printf("Wednesday");
        break;
    // ... and so on
}

10. How can you handle a situation where you need to execute multiple conditional checks in C, and the order of checks is important?

Answer: When you need to execute multiple conditional checks in C and the order of checks is important, use if-else if statements. The if-else if structure allows for sequential checking of conditions, and the first condition that evaluates to true is the only one that will execute. This structure ensures that the order of conditions is preserved and only the applicable block of code is executed.

Example:

int score = 85;
if (score >= 90) {
    printf("Grade: A");
} else if (score >= 80) {
    printf("Grade: B");
} else if (score >= 70) {
    printf("Grade: C");
} else {
    printf("Grade: F");
}

In this example, the conditions are checked in descending order, ensuring that the highest possible grade is assigned based on the score.


These answers cover the essential aspects of decision making statements (if, if-else, nested if, and switch cases) in C, providing examples and explanations for better understanding.