Loading...
Loading...

C Control Flow (if, switch) Tutorial

In this tutorial, you'll learn how to use control flow statements like if, else, and switch in C programming to make decisions in your programs.

1. Using the if Statement

The if statement allows your program to execute code conditionally:

#include <stdio.h>

int main() {
    int number = 10;

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

    return 0;
}

This program checks if number is greater than zero and prints a message if the condition is true.

2. Adding an else Block

Use else to specify an alternative block of code to execute if the condition is false:

#include <stdio.h>

int main() {
    int number = -5;

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

    return 0;
}

3. Using the switch Statement

The switch statement is used for multiple conditions based on the value of a variable:

#include <stdio.h>

int main() {
    int day = 2;

    switch (day) {
        case 1:
            printf("Monday\\n");
            break;
        case 2:
            printf("Tuesday\\n");
            break;
        case 3:
            printf("Wednesday\\n");
            break;
        default:
            printf("Other day\\n");
    }

    return 0;
}

This program uses switch to print the name of a day based on its number.

4. Tips and Best Practices

  • Always include a default case in switch for unexpected values.
  • Use break in switch cases to avoid fall-through behavior.
  • Keep conditions simple and readable.

5. Conclusion

Control flow statements like if, else, and switch are essential tools in C programming. Practice using them to make your programs dynamic and responsive.

0 Interaction
126 Views
Views
35 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home