Control Structures and Decision Making in C

January 11, 2024

Welcome back to our ongoing journey through the fundamentals of the C programming language! In this post, we’ll be diving into the world of control structures and decision-making in C. These concepts are essential for controlling the flow of a program and making decisions based on certain conditions.

Let’s start by exploring if statements. An if statement is used to execute a block of code if a specified condition is true. Here’s a simple example:

#include <stdio.h>

int main() {
    int x = 10;
    if (x > 5) {
        printf("x is greater than 5");
    }
    return 0;
}

In this example, the program will print ‘x is greater than 5’ because the condition ‘x &gt 5’ is true.

Next, let’s move on to switch statements. A switch statement allows a variable to be tested for equality against a list of values. Here’s an example:

#include <stdio.h>

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

Now, let’s explore loops. Loops are used to execute a block of code repeatedly. C provides three types of loops: while, do-while, and for. Here’s an example of a for loop:

#include <stdio.h>

int main() {
    for (int i = 1; i <= 5; i++) {
        printf("%d\n", i);
    }
    return 0;
}

Finally, we’ll touch on conditional expressions. Conditional expressions are used to return a value based on a condition. Here’s an example:

#include <stdio.h>

int main() {
    int x = 10;
    int y = (x > 5) ? 20 : 30;
    printf("Value of y is %d", y);
    return 0;
}

In this example, the value of y will be 20 because the condition ‘x &gt 5’ is true.

That’s a wrap for our exploration of control structures and decision-making in C! I hope this post has provided you with a solid understanding of these fundamental concepts. Stay tuned for more C programming insights in our next post!