Control statements in C, also called control constructs in C, allow developers to manage the program’s execution flow. These control instructions in C, including conditional control statements, simplify decision-making, looping, and branching, making executing instructions conditionally or repeatedly possible. This article will discuss control statements in c with examples
Key Takeaways
- Control statements in C dictate the execution flow of a program, enabling decision-making, looping, and branching based on conditions.
- There are three main types of control statements in C language: decision-making (
if, else if statement, switch-case
), iteration (for, while, do-while
), and jump (break, continue, goto
). These form the basis of control structure in C programming, enabling developers to handle various logical scenarios efficiently. - The `
if-else
` statement executes blocks of code based on a true or false condition, with syntax emphasizing the use of parentheses for conditions and braces for code blocks. - The `
switch-case
` statement provides a structured method for multi-way branching using integer values of expressions. Each case ends in a `break` to prevent a fall-through. - Iteration statements like `
for
`, `while
`, and `do-while
` loops facilitate the repeated execution of code blocks based on conditional expressions, with each loop type offering different control mechanisms. - Nested control structures, including nested if-else and switch-case within loops, allow for complex decision-making and repetitive tasks within varied programming scenarios.
What Is Control Statements in C
Control statements in C are instructions that manage the flow of execution in a program based on specific conditions or repetitions. They allow developers to make decisions, repeat tasks, or jump to specific parts of the code.
Types of Control Statements
There are three types of control statements in C:
- Decision-making statements (
if, if-else, switch-case
) - Iteration statements (
for, while, do-while
) - Jump statements (
break, continue, goto
)
Decision-Making Statements
1. if-else Statement
The if-else statement, a vital part of control flow statements in C, executes blocks of code based on a true or false condition. Complex decisions often involve multiple if-else statements or an else-if statement, ensuring different outcomes for various conditions.
Syntax
if (condition) {
} else {
}
- If the condition is true, the if block runs, and the program continues with the next statement after it.
- If the condition is false and there is no else block, the program simply skips the if block and moves to the next statement.
- The else block is used only when specific code needs to run if the condition is false.
Example 1: Check Positive or Negative Number
#include<stdio.h>
int main( ) {
int a;
printf("n Enter a number:");
scanf("%d", &a);
if(a>0)
{
printf( "n The number %d is positive.",a);
}
else
printf("n The number %d is negative.",a);
}
return 0;
}
Example 2: Compare Two Strings
#include <string.h>
int main( )
char a[20] , b[20];
printf("n Enter the first string:");
scanf("%s",a);
printf("n Enter the second string:")
scanf("%s",b);
if((strcmp(a,b)==0))
{
printf("nStrings are the same")
else
printf("nStrings are different");
}
return 0;
}
The above program compares two strings to check whether they are identical. The strcmp function is used for this purpose. It is declared in the string.h file as:
int strcmp(const char *s1, const char *s2);
It compares the string pointed to by s1 to the string pointed to by s2, and returns:
- 0 if the strings are equal.
- Negative if the first string is less than the second.
- Positive if the first string is greater than the second.
Note: The comparison is case-sensitive. For case-insensitive comparisons, use strcasecmp() (non-standard).
Nested if and if-else Statements
It is also possible to embed or to nest if-else statements one within the other. Nesting is useful when multiple conditions need to be evaluated.
The general format of a nested if-else statement is:
if(condition1) {
} else if(condition2) {
} else if(conditionN) {
} else {
}
}
else
{
}
This structure is also called the if-else ladder. During the execution of a nested if-else statement, execution stops at the first condition that evaluates to true, and the remaining blocks are skipped.
If neither of the conditions is true, either the last else-block is executed, or if the else-block is absent, the control gets transferred to the next instruction present immediately after the else-if ladder.
Example: Find the Greatest of Three Numbers
#include<stdio.h>
int main() {
int a = 6, b = 5, c = 10;
if(a > b) {
if(a > c) {
printf("\nGreatest is: %d", a);
} else {
printf("\nGreatest is: %d", c);
}
} else if(b > c) {
printf("\nGreatest is: %d", b);
} else {
printf("\nGreatest is: %d", c);
}
return 0;
}
The above program compares three integer quantities and prints the greatest. The first if statement compares the values of a and b.
- If a>b is true, it enters a nested if to compare a and c.
- If a > c, prints a. Otherwise, prints c.
- If the first condition fails (a > b is false), it checks b > c. If true, prints b, else c.
Best Practices and Common Mistakes:
- Braces for Single Statements: Always enclose statements in braces {} even if only one statement follows an if or else.
- Avoid Assignment Instead of Comparison: Use == for comparisons, not =, which assigns values.
- Indentation Matters: Maintain consistent indentation to improve readability and avoid errors.
- Test Edge Cases: Validate inputs and outputs, especially in nested if-else structures, to handle boundary conditions.
2. Switch Statement
The switch-case statement is used for multi-way branching, where a variable or expression’s value is matched against predefined cases. It’s ideal for replacing long chains of if-else when testing for equality.
However, you have to be careful when using a switch statement since missing a break statement can cause fall-through behaviour, executing subsequent cases and leading to unexpected results.
Syntax
switch (expression) {
case value1:
break;
case value2:
break;
...
case valueN:
break;
default:
}
The value of this expression is either generated during program execution or read in as user input. The case whose value is the same as that of the expression is selected and executed. The optional default label is used to specify the code segment to be executed when the value of the expression does not match any of the case values.
If no break statements were present at the end of the third case, the switch statement prematurely executes all subsequent cases, causing unintended results.
If the break is present, only the required case is selected and executed, after which the control gets transferred to the next statement immediately after the switch statement.
There is no break after default because, after the default case, the control will, either way, get transferred to the next statement immediately after the switch.
Example 1: Print the Day of the Week
#include<stdio.h>
int main( ) {
int day;
printf("nEnter the number of the day:");
scanf("%d",&day);
switch(day)
{
case 1
printf("Sunday")
break;
case 2
printf("Monday");
break
case 3
printf("Tuesday");
break
case 4
printf"Wednesday"
break;
case 5
printf"Thursday"
break;
case 6
printf("Friday")
break;
case 7
printf("Saturday");
break
default
printf"Invalid choice"
return 0;
}
This basic program demonstrates the use of the switch-case construct. The appropriate case is executed based on the user’s input, and the break statement prevents the execution of subsequent cases. For instance, if the input is 5, the output will be Thursday.
All programs written using the control structure in C, such as the switch-case statement, can also be implemented using the if-else statement.
However, the control flow statements in C, like switch-case, offer better readability and performance in multi-way branching.
Switch-case statements are particularly effective for menu-based applications or handling specific user inputs. Compared to nested if-else statements, they are more efficient and easier to read, especially when selecting from a fixed set of choices.
Example 2: Menu-Driven Program for File Processing
#include<stdio.h>
int main() {
int choice;
printf("\nPlease select from the following options:");
printf("\n1. Add a record at the end of the file.");
printf("\n2. Add a record at the beginning of the file.");
printf("\n3. Add a record after a particular record.");
printf("\nPlease enter your choice (1/2/3): ");
scanf("%d", &choice);
switch(choice) {
case 1:
break;
case 2:
break;
case 3:
break;
default:
printf("\nWrong Choice");
}
return 0;
}
The above example of switch-case generally involves nesting the switch-case construct inside an iteration construct like do-while.
Best Practices and Common Mistakes:
- Always Use Break: Include a break after each case unless intentional fall-through is required.
- Default Case Placement: Place the default at the end to improve readability.
- Test All Input Values: Ensure inputs match valid case values and handle invalid inputs properly using the default case.
- Avoid Complex Expressions: Use simple constants for cases, as variables or ranges are not supported.
- Indentation and Formatting: Follow consistent indentation to maintain clarity.
Iteration Statements
Iteration statements are used to execute a particular set of instructions repeatedly until a particular condition is met or for a fixed number of iterations.
1. for Loop
The `for` loop is a pre-test loop, which evaluates the condition before the loop executes. It is best suited for situations where the number of iterations is known beforehand.
Syntax
for(initialization; termination; increment/decrement) {
The for loop consists of three expressions:
- Initialization expression: Initializes the looping index. The looping index controls the looping action. The initialization expression is executed only once when the loop begins.
- Termination expression: Represents a condition that must be true for the loop to continue execution.
- Increment/decrement expression: Executed after every iteration to update the value of the looping index.
Example: Fibonacci Series
#include<stdio.h>
int main() {
int i, n, a = 0, b = 1, sum;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("%d %d", a, b);
for(i = 2; i < n; i++) {
sum = a + b;
printf(" %d", sum);
a = b;
b = sum;
}
return 0;
}
The above program uses the for loop to print the series: 0,1,1,2,3,5,8,13 … to n terms.
- Initialization: Sets i = 2 as the first two terms (0 and 1) are already printed.
- Condition: Continues execution until i < n.
- Increment: Increments i by 1 after each iteration.
If the input number is 7, the out put will be:
Variations of the for Loop
1. Omitting the Initialization Expression
In this case, the looping index is initialized before the for loop. Thus, the for loop takes the following form:
int i = 0;
for(; i < 5; i++) {
printf("%d ", i);
}
This method is useful when the loop variable is initialized outside the loop.
Note: The semicolon that terminates the initialization expression is present before the condition expression.
2. Omitting the Condition
In this case the condition is specified inside the body of the for loop, generally using an if statement. The while or do-while statements may also be used to specify the condition. Thus the for loop takes the following form:
for(int i = 0; ; i++) {
if(i == 5) break;
printf("%d ", i);
}
This is useful for situations where conditional exits are handled inside the loop body. Also, the semicolon that terminates the condition is present in the for statement. The following program explains how the condition can be omitted:
#include<stdio.h>
int main() {
int i,n, a, b, sum=0;
printf("Enter the number of terms:");
scanf("%d",&n);
a=0;
b=1;
printf("%dn %d", a, b);
for(i=2; ;i++) {
if(i==(n-1)) {
break;
}
sum=a+b;
printf("n%d",sum);
a=b;
b=sum;
}
return 0;
}
3. Omitting the increment /decrement Expression:
In this case, the increment/decrement expression is written inside the for loop’s body. This is useful when you only need to increment the loop count based on specific conditions.
for(int i = 0; i < 5;) {
printf("%d ", i);
i++;
}
4. Omitting all Three Expressions:
It is also possible to omit all three expressions, but they should be present in the ways discussed above. If all three expressions are omitted entirely — ie, they are not mentioned in the ways discussed above — then the for loop becomes an infinite or never-ending loop.
In this case, the for loop takes the following form:
Best Practices and Common Mistakes:
- Always Update Loop Variables: Ensure increments or decrements prevent infinite loops.
- Use Braces {} for Clarity: Even for single statements inside the loop.
- Avoid Off-By-One Errors: Double-check termination conditions, especially with < or <=.
- Test with Boundary Values: Validate behavior with minimum and maximum values.
2. while Loop
The while statement executes a block of statements repeatedly while a particular condition is true.
The statements are executed repeatedly until the condition is true.
Example 1: Sum of Digits
#include<stdio.h>
int main() {
int n, a, sum = 0;
printf("\nEnter a number: ");
scanf("%d", &n);
while(n > 0) {
a = n % 10;
sum = sum + a;
n = n / 10;
}
printf("\nSum of the digits = %d", sum);
return 0;
}
The above program uses the while loop to calculate the sum of the digits of a number. For example, if the number is 456, the while loop will calculate the sum in four iterations as follows.
Note: % gives the remainder and / the quotient.
- Iteration 1: n>0 Condition is true(n=456) a=n%10=6; sum=sum+a=6; n=n/10= 45; New value of n is 45.
- Iteration 2: n>0 Condition is true(n=45) a=n%10=5; sum=sum+a=6+5=11; n=n/10= 4; New value of n is 4.
- Iteration 3: n>0 Condition is true(n=4) a=n%10=4; sum=sum+a=11+4=15; n=n/10= 0; ew value of n is 0.
- Iteration 4: n>0 Condition is false(n=0). After the fourth iteration control exits the while loop and prints the sum to be 15.
Example 2: Palindrome Check
A palindrome is a number that remains the same when its digits are read or written from right to left or vice versa, eg 343 is a palindrome, but 342 is not.
The following program works on the logic that if the reverse of the number is the same as the original number, then the entered number is a palindrome, otherwise it is not.
#include<stdio.h>
int main() {
int n, m, a, reverse = 0;
printf("\nEnter a number: ");
scanf("%d", &n);
m = n;
while(n > 0) {
a = n % 10;
reverse = reverse * 10 + a;
n = n / 10;
}
if (m == reverse) {
printf("\nThe number is a palindrome.");
} else {
printf("\nThe number is not a palindrome.");
}
return 0;
}
The above program uses almost the same logic as the program of the sum of digits. As was seen in that program, n becomes 0 in the last iteration. However, we need to compare the original value of n to the reverse of the number to determine whether it is a palindrome or not.
Therefore, the value of n was stored in m before entering the while loop. The value of m is later compared with the reverse to decide whether the entered number is a palindrome or not.
The while loop works in the following way:
Let n=343;
- Iteration 1: a= n%10=3; reverse=reverse*10+a=0*10+3=3; n=n/10=34;
- Iteration 2: a=n%10=4; reverse=reverse*10+a=3*10+4=34; n=n/10=3;
- Iteration 3: a= n%10=3; reverse=reverse*10+a=34*10+3=343; n=n/10=0;
- Iteration 4: n>0 condition false(n=0). Control exits from the while loop.
Best Practices and Common Mistakes:
- Infinite Loops: Ensure the condition changes within the loop to avoid infinite execution.
- Initialization: Initialize variables properly before entering the loop.
- Break Conditions: Use explicit break statements when required for early exits.
- Edge Cases: Test inputs like 0 or negative values to handle all scenarios.
3. do-while loop
The do-while loop is an exit-controlled loop, meaning the loop body executes at least once before the condition is checked.
Syntax
The difference between while and do-while is that the while loop is entry-controlled — it tests the condition at the beginning of the loop and will not execute even once if the condition is false, whereas the do-while loop is exit-controlled — it tests the condition at the end of the loop after completing the first iteration.
For many applications, it is more natural to test for the continuation of a loop at the beginning rather than at the end of the loop. For this reason, the do-while statement is used less frequently than the while statement.
Example 1: Sum of Digits
The following program calculates the sum of digits in the same manner, except that it uses the do-while loop:
#include<stdio.h>
int main() {
int n, a, sum = 0;
printf("\nEnter a number: ");
scanf("%d", &n);
do {
a = n % 10;
sum = sum + a;
n = n / 10;
} while(n > 0);
printf("\nSum of the digits = %d", sum);
return 0;
}
However, the do-while statement should be used only when the loop must be executed at least once, whether or not the condition is true.
A practical use of the do-while loop is in an interactive menu-driven program where the menu is presented at least once, and then, depending upon the user’s choice, the menu is displayed again, or the session is terminated. Consider the same example that we saw in the switch case.
Example 2: Menu-Driven Program
#include<stdio.h>
int main() {
int choice;
char ch;
do {
printf("\nMain Menu");
printf("\n1. Add a record at the end of the file.");
printf("\n2. Add a record at the beginning of the file.");
printf("\n3. Add a record after a particular record.");
printf("\nPlease enter your choice (1/2/3): ");
scanf("%d", &choice);
switch(choice) {
case 1:
break;
case 2:
break;
case 3:
break;
default:
printf("\nWrong Choice");
}
printf("\nDo you want to continue updating records (y/n)? ");
scanf(" %c", &ch);
} while(ch == 'y' || ch == 'Y');
return 0;
}
Best Practices and Common Mistakes:
- Initialization: Ensure variables are initialized before entering the loop.
- Condition Validation: Handle edge cases where input might cause infinite loops.
- Interactive Programs: Prefer do-while when the loop must execute at least once.
- Readability: Maintain proper indentation and comments for clarity.
Jump Statements
Jump control flow statements in C programming alter the flow of a program unconditionally. These include `break`, `continue`, and `goto`. , which are fundamental components of control constructs in C.”
1. break Statement
The break statement is primarily used to exit early from a loop or a switch-case statement. It stops the execution of the current construct and transfers control to the statement immediately following the construct.
Syntax
When the break statement is encountered, the program immediately exits the enclosing loop or switch-case structure and resumes execution after it.
Example: Search in an Array
Consider a situation where you are searching for a specific number in an array. As soon as the number is found, the loop can be terminated using break.
#include<stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int target = 30;
for (int i = 0; i < 5; i++) {
if (arr[i] == target) {
printf("Found %d at index %d\n", target, i);
break;
}
}
return 0;
}
Output
Here, the break statement ensures the loop does not waste time checking the remaining elements once the target is found.
Best Practices:
- Use break Judiciously: Avoid excessive use, as it can make code harder to read.
- Validate Conditions: Ensure the condition triggering break is well-defined to prevent logical errors.
- Document Purpose: Add comments to explain why break is used to improve maintainability.
2. continue Statement
The `continue` statement is used to skip the remaining statements in the current iteration of a loop and proceed to the next iteration. When continue is encountered, the program jumps back to the beginning of the loop, re-evaluates the loop condition, and starts the next iteration.
Syntax
Example: Printing only odd numbers in a range
#include<stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
printf("%d ", i);
}
return 0;
}
Here, the continue statement ensures that even numbers are skipped without terminating the loop.
Output
Best Practices:
- Avoid Overuse: Frequent use of continue can reduce code readability.
- Simplify Conditions: Optimize logic to reduce reliance on continue.
- Comment Usage: Add comments to explain why continue is used, especially in loops with multiple conditions.
3. goto Statement
The goto statement performs an unconditional jump to a labeled statement within the same function. While considered harmful for code readability, it can be useful in specific cases like breaking out of deeply nested loops or error handling.
When the goto statement is encountered, the program jumps directly to the labeled statement, skipping intermediate code.
Syntax
Example: Exiting Nested Loops
In scenarios with multiple nested loops, exiting all loops simultaneously can be challenging. The goto statement simplifies this process.
#include<stdio.h>
int main() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == j) {
goto end;
}
printf("i = %d, j = %d\n", i, j);
}
}
end:
printf("Exited nested loops.\n");
return 0;
}#include<stdio.h>
int main() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == j) {
goto end;
}
printf("i = %d, j = %d\n", i, j);
}
}
end:
printf("Exited nested loops.\n");
return 0;
}
Output
i = 0, j = 1
i = 0, j = 2
Exited nested loops.
Here, the loop Iterates through i and j. When i == j, the goto statement jumps directly to the end label, skipping further iterations.
Comparison Table
Advanced Usage and Interactions
1. Using Control Statements with Arrays
Control statements in C, a key aspect of the C programming language, are often paired with arrays for tasks like searching, filtering, and processing. For example, looping structures like for and while are vital components of control instructions in C, helping to navigate array elements efficiently. For instance, here is how to find the maximum element in an array:
#include<stdio.h>
int main() {
int arr[] = {10, 20, 50, 40, 30};
int max = arr[0];
for (int i = 1; i < 5; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
printf("Maximum element: %d\n", max);
return 0;
}
The loop starts with the second element (index 1) since the first element is assumed to be the maximum initially.
The if statement compares each element with the current max.
If a larger element is found, max is updated.
2. Error Handling Using Control statements in C
Although C lacks built-in exception handling, control statements in C like if and goto can handle simple errors.
#include<stdio.h>
int main() {
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
printf("Error: File not found.\n");
return 1;
}
printf("File opened successfully.\n");
fclose(file);
return 0;
}
The if statement checks if the file pointer is NULL, indicating the file could not be opened.
If true, an error message is displayed, and the program exits early using return 1.
FAQs About Control Statements in C
What Are Control Statements in C?
Control statements in C, often referred to as control structure in C, are programming constructs that allow you to control the flow of a program. These control constructs in C language are essential for decision-making, iteration, and branching.
What Is the Purpose of Conditional Statements in C?
Conditional statements, such as if, else if, and switch, allow you to execute different blocks of code based on specified conditions. They enable your program to make decisions and perform actions accordingly.
How Do I Use the If Statement in C?
if statement, one of the most used control instructions in C, is used to execute a block of code if a specified condition is true. It can be followed by an optional “else” statement to specify an alternative action if the condition is false.
What Is the Difference Between If and Switch Statements?
if statements are used for general conditional branching, while switch statements are used for multi-way branching based on the value of an expression. if statements are more flexible and can handle complex conditions, whereas switch statements are ideal for situations where a variable can match specific values.
When Should I Use a While Loop over A for Loop?
Use a while loop when you need to repeat a block of code as long as a condition remains true but without a fixed number of iterations. for loops are more suitable for situations with a known number of iterations.
What Are the Common Mistakes to Avoid When Using Control Statements in C?
Common mistakes include not using braces for code blocks in if and loop statements, forgetting to update loop control variables, and creating infinite loops by not changing loop conditions correctly. Properly structuring your code and handling corner cases are essential.
How Do I Avoid Infinite Loops?
Ensure loop conditions are updated correctly inside the loop.
Debug by printing key variables involved in the loop condition.
Use breakpoints in an IDE to monitor the loop execution.
Can I Use Multiple Else If Conditions in an If Statement?
Yes, you can use multiple else if conditions in an if statement to evaluate a series of conditions sequentially. This allows you to choose from several alternatives based on the first true condition.
What’s the Difference Between Break and Continue?
- break: Exits the loop entirely and moves control to the statement after the loop.
- continue: Skips the rest of the loop body for the current iteration and jumps to the next iteration.