Have you ever wondered how computers come to the decision of which actions to perform? A program selects what action to perform based on the information it receives; that is where conditional statements in C come into play.
When we are coding, often the program needs to choose between any number of possible actions depending upon the input given by the user or, perhaps checking some condition. These types of decisions within C programming are handled using conditional statements. The ability to “decide” makes our programs dynamic and flexible. Without conditional statements, our programs would be stiff, and unable to take into account changing scenarios.
Consider if we were developing a program that must determine whether someone was old enough to vote or not. Of course, ideally, we would need some way to check their age, but that’s a fairly simplistic example of what conditional statements can do for you. They guide the flow of the program based on conditions you may have defined.
In this blog, we’ll dig deep into how these statements work, look at some of the types of them, and see them in action with some examples. Whether you are a newcomer to C or just want to refresh your knowledge, it’s about time you are here.
What are Conditional Statements in C?
Conditional statements in C are used to perform different actions depending on whether a condition evaluates to true or false. Conditions are mainly comparisons or expressions that evaluate a Boolean result, that is, a true or false value. If this condition evaluates to true, the program runs a particular block of code. If it is false, it either skips that block or runs an alternate block.
Without conditional statements, every line of code would have been executed in sequence, limited only to the ability of the program to react appropriately to changing inputs or scenarios. In other words, conditional statements in C make your program flexible, responsive, and able to handle different situations as the traffic light system guides cars through intersections on the basis of various signals.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Why Conditional Statements Are Vital for Program Flow Control
Imagine you were in a car and reached a traffic signal; you either stop or go, depending on whether the light is red or green. Conditional statements in programming serve like traffic signals for your code-they help with the flow of control, and a program can then decide which way to go based on certain conditions.
Without conditional statements, our programs would simply run through in a straight line from start to finish and wouldn’t even be able to react if there were changes made to input or environment. Conditional statements allow us to:
Do different things based on different user input.
Execute different blocks of code based on calculated results.
Control whether certain parts of the code even run at all.
In other words, without conditional statements, we won’t be able to handle scenarios well in real life. They are the foundation of decision-making in C programming.
The Different Types of Conditional Statements in C Programming
There is not one general conditional statement. The beauty of C is that it gives us several different tools for different situations, and the art is in knowing which to use. Let’s cover them one at a time.
1. if Statement in C
The if statement is the simplest form of conditional statement in C. It allows us to run a block of code only if a specific condition is true.
Syntax:
if (condition) {
// Block of code to execute if the condition is true
}
The condition is an expression that evaluates to true or false.
If it evaluates to true, the code within braces {} is executed.
If the condition is false, the block is skipped entirely.
2. if-else Statement in C
The if-else statement is an extension of the if statement. It helps us execute one block of code if the condition meets the true state, and the other block if the condition meets a false state.
Syntax:
if (condition) {
// Block of code to execute if the condition is true
} else {
// Block of code to execute if the condition is false
}
If the condition is true, the first block runs.
If the condition is false, the second block inside the else statement runs.
The nested if-else statement is used when we need to check many conditions. Such a situation helps us place one if or else statement inside another, creating a hierarchy of decisions.
Syntax:
if (condition1) {
if (condition2) {
// Block of code to execute if both condition1 and condition2 are true
} else {
// Block of code to execute if condition1 is true and condition2 is false
}
} else {
// Block of code to execute if condition1 is false
}
Each if can contain another if-else structure, allowing us to check conditions in a nested manner.
This structure helps handle more complex logic where multiple conditions must be evaluated in a specific order.
4. else-if Ladder for Multiple Conditions
We can use the else-if ladder when we wish to check several conditions in sequence. It allows linking several if and else-if statements together, and only one of the blocks will be executed.
Syntax:
if (condition1) {
// Block of code to execute if condition1 is true
} else if (condition2) {
// Block of code to execute if condition1 is false and condition2 is true
} else if (condition3) {
// Block of code to execute if both condition1 and condition2 are false, but condition3 is true
} else {
// Block of code to execute if none of the conditions are true
}
The program evaluates the conditions one by one.
As soon as one condition is true, its corresponding block runs and the rest of the ladder is skipped.
The switch statement is cleaner than handling lots of conditions based on the value of just a single variable. It helps clean up our code when we have a large number of if-else conditions comparing the same variable.
Syntax:
switch (expression) {
case constant1:
// Block of code to execute if expression == constant1
break;
case constant2:
// Block of code to execute if expression == constant2
break;
// More cases can be added here
default:
// Block of code to execute if no case matches
}
The expression is evaluated once, and its value is compared against each case.
If a match is found, the code block for that case is executed.
The break statement is used to exit the switch after executing the matching case.
The default case is optional and runs if no match is found.
The ternary operator is shorthand for an if-else statement. It is helpful when the condition is relatively simple and returns some value based on that condition.
Syntax:
condition ? expression1 : expression2;
If condition is true, expression1 is executed.
If condition is false, expression2 is executed.
This operator is ideal for simple, two-way decisions where a full if-else would be overkill.
Jump Statements for Unconditional Control of Loop Flow
We have loops, but sometimes we need to get out of a loop earlier, skip over part of the loop or jump to another place in the program. That’s what jump statements do.
Jump statements give additional unconditional control over the execution of our code in C programming. These are break, continue, goto and return. Let’s briefly review each one.
Use Break to Exit Loops or Switches
Sometimes we want to exit a loop or a switch early. We can do just this with the break statement. Often we use it once we have what we are seeking and we don’t want to continue looping inside of the loop.
Example: Breaking Out of a Loop
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
if (i == 5) {
break; // Stop the loop when i equals 5
}
printf("%d ", i);
}
return 0;
}
Output:
1 2 3 4
Here, the loop prints numbers from 1 to 4 and stops when i reaches 5. The break statement immediately exits the loop.
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1: printf("Sundayn"); break;
case 2: printf("Mondayn"); break;
case 3: printf("Tuesdayn"); break; // Execution stops after case 3
default: printf("Invalid dayn");
}
return 0;
}
Output:
Tuesday
In the switch statement, once case 3 is executed, the break ensures no other cases are run.
Understanding Continue to Skip Current Loop Iterations
The key difference between continue and break is that in using continue, we are not leaving the loop. What happens is that the continue skips what is left inside the iteration of the present loop and moves to the next one.
Example: Skipping Even Numbers in a Loop
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", i);
}
return 0;
}
Output:
1 3 5 7 9
In this loop, whenever i is even, the continue statement skips the printf line and jumps to the next iteration, printing only the odd numbers.
Employing goto for Unconditional Code Jumps
The goto statement lets us jump ahead to where we have a named label in the code. Powerful, but rather not suggested; the code becomes that much harder to read.
Example: Using goto to Skip Part of the Code
#include <stdio.h>
int main() {
int num = 5;
if (num == 5) {
goto skip; // Jump to the label 'skip'
}
printf("This will not print.n");
skip:
printf("Skipped to this part of the program.n");
return 0;
}
Output:
Skipped to this part of the program.
Here, the program jumps directly to the skip label, skipping the part where the first printf would have executed.
Utilising Return to Exit Functions and Return Values
The return statement exits a function and returns control to the place where the function is called. Plus, we can use return to pass back a value to the caller.
Example: Using return to Exit a Function Early
#include <stdio.h>
int checkNumber(int num) {
if (num < 0) {
return 0; // Exit the function if the number is negative
}
return 1;
}
int main() {
int result = checkNumber(-5);
printf("Result: %dn", result);
return 0;
}
Output:
Result: 0
In this case, the function exits early and returns 0 because the input number is negative.
Example for if Statement: Check if a Number is Positive
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num > 0) {
printf("The number is positive.n");
}
return 0;
}
Output:
Input
Output
5
The number is positive.
-2
(No output)
Example for if-else: Determine Even or Odd Number
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number % 2 == 0) {
printf("%d is an even number.n", number);
} else {
printf("%d is an odd number.n", number);
}
return 0;
}
Output:
Input
Output
4
4 is an even number.
7
7 is an odd number.
Example for Nested if-else: Determine the Largest of Three Numbers
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
if (a > b) {
if (a > c) {
printf("%d is the largest number.n", a);
} else {
printf("%d is the largest number.n", c);
}
} else {
if (b > c) {
printf("%d is the largest number.n", b);
} else {
printf("%d is the largest number.n", c);
}
}
return 0;
}
Output:
Input
Output
5 12 9
12 is the largest.
23 18 22
23 is the largest.
Example for else-if Ladder: Assign Grades Based on Marks
#include <stdio.h>
int main() {
int marks;
printf("Enter your marks: ");
scanf("%d", &marks);
if (marks >= 85) {
printf("You scored grade A.n");
} else if (marks >= 70) {
printf("You scored grade B.n");
} else if (marks >= 50) {
printf("You scored grade C.n");
} else {
printf("You failed.n");
}
return 0;
}
Output:
Input
Output
90
You scored grade A.
65
You scored grade C.
45
You failed.
Example for switch: Determine the Day of the Week
#include <stdio.h>
int main() {
int day;
printf("Enter a day number (1-7): ");
scanf("%d", &day);
switch (day) {
case 1: printf("Sundayn"); break;
case 2: printf("Mondayn"); break;
case 3: printf("Tuesdayn"); break;
case 4: printf("Wednesdayn"); break;
case 5: printf("Thursdayn"); break;
case 6: printf("Fridayn"); break;
case 7: printf("Saturdayn"); break;
default: printf("Invalid day number.n");
}
return 0;
}
Output:
Input
Output
3
Tuesday
8
Invalid day number.
Example for Ternary Operator: Condensed Conditional Logic
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
num % 2 == 0 ? printf("Evenn") : printf("Oddn");
return 0;
}
Knowing how to apply conditional statements in C properly means you can create dynamic and efficient programs. These enable us to control the flow of a program, make decisions, and handle complex logic in a clean manner. Some ways we can ensure that our code remains readable and efficient, avoid deep nesting, use switch for multiple conditions, and minimise redundant checks.
Mastering conditional statements in C makes you a smarter programmer since your code will be able to be written much better. But the good part is that such code can be understood and maintained quite easily. This is an important lesson for every C programmer.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.