Logo
Unit 3 – C Control Structures: Conditional Statements

C Control Structures: Conditional Statements

Duration: 5 minutes

Hello, future C-oders!

Having acquired knowledge about operators and data types, let’s progress to control structures—an integral aspect of any programming language.

In this module, our focus will be on conditional statements, which will help you write code that can make decisions based on specific circumstances, which in turn will enhance the dynamism and interactivity of your applications.

Understanding Conditional Statements in C

Conditional statements are used to execute different code blocks based on different conditions. In C, we primarily use the if, else if, and else statements for this purpose:

// if Statement: It tests a condition. If the condition is True, it executes a block of code.
if (condition) {
// code to be executed if the condition is True
}
// else if Statement: It tests another condition if the previous if the condition is False.
if (condition1) {
// code to be executed if condition1 is True
} else if (condition2) {
// code to be executed if condition2 is True
}
// else Statement: If none of the conditions are True, the code inside the else block gets executed.
if (condition1) {
// code to be executed if condition1 is True
} else if (condition2) {
// code to be executed if condition2 is True
} else {
// code to be executed if none of the conditions are True
}

Creating a Program Using Conditional Statements

Let’s show this through a simple example. Imagine you want to categorize numbers based on their value:

int number = 42;
if (number > 0) {
printf("Positive");
} else if (number < 0) {
printf("Negative");
} else {
printf("Zero");
} // This will output: 'Positive'

Here, the program checks each condition sequentially. Since the number is 42, it satisfies the condition of being greater than 0, so the program outputs ‘Positive’.

Exercise

Now that you’ve understood what control structures are, let’s move on to your task, where you will write a program with various conditional statements. This program should demonstrate your understanding of if, if, and else statements.

You can choose any scenario that involves decision-making based on different conditions. This exercise will help you practice and improve your grasp of conditional statements.

Conclusion

Well done for delving into C’s conditional statements! The only key to incorporating dynamic and decision-making functions into your programs is through lots and lots of practice. With the study of these few fundamentals we have covered till now, you’re making steady progress toward mastering C programming. Stay curious and keep coding!

Next Tutorial: C Control Structures: Loops

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!