Overview of Control Flow
Control flow in C refers to the order in which statements are executed in a program. It involves making decisions, repeating actions, and branching based on conditions. Let's explore the fundamental control flow structures in C to gain a better understanding.
1. Sequential Execution
The default control flow in C is sequential execution, where statements are executed in the order they appear in the code.
#include <stdio.h>
int main() {
// Sequential execution
printf("Step 1\n");
printf("Step 2\n");
printf("Step 3\n");
return 0;
}
2. Conditional Statements: if, else if, else
Conditional statements allow for decision-making based on conditions.
#include <stdio.h>
int main() {
int num = 10;
// Example of if-else statement
if (num > 0) {
printf("Positive number\n");
} else if (num < 0) {
printf("Negative number\n");
} else {
printf("Zero\n");
}
return 0;
}
3. Switch Statement
The switch
statement is used for multi-way branching based on the value of an expression.
#include <stdio.h>
int main() {
char grade = 'B';
// Example of switch statement
switch (grade) {
case 'A':
printf("Excellent\n");
break;
case 'B':
printf("Good\n");
break;
case 'C':
printf("Average\n");
break;
default:
printf("Not defined\n");
}
return 0;
}
4. Looping Statements: for, while, do-while
Looping statements allow for repeated execution of a block of code.
Example of for loop:
#include <stdio.h>
int main() {
// Example of for loop
for (int i = 1; i <= 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}
Example of while loop:
#include <stdio.h>
int main() {
int count = 0;
// Example of while loop
while (count < 3) {
printf("Count: %d\n", count);
count++;
}
return 0;
}
Example of do-while loop:
#include <stdio.h>
int main() {
int x = 5;
// Example of do-while loop
do {
printf("Value of x: %d\n", x);
x--;
} while (x > 0);
return 0;
}
5. Branching Statements: break, continue, return
Branching statements alter the normal flow of control.
Example of break statement:
#include <stdio.h>
int main() {
// Example of break statement in a loop
for (int i = 1; i <= 10; i++) {
if (i == 5) {
printf("Breaking the loop at i = 5\n");
break;
}
printf("Iteration %d\n", i);
}
return 0;
}
Example of continue statement:
#include <stdio.h>
int main() {
// Example of continue statement in a loop
for (int i = 1; i <= 5; i++) {
if (i == 3) {
printf("Skipping iteration at i = 3\n");
continue;
}
printf("Iteration %d\n", i);
}
return 0;
}
Example of return statement:
#include <stdio.h>
// Example of return statement in a function
int square(int num) {
return num * num;
}
int main() {
int result = square(4);
printf("Square of 4: %d\n", result);
return 0;
}
Understanding and mastering control flow structures in C is crucial for writing structured and efficient programs. If you have specific questions or if there are additional topics you'd like to explore, feel free to ask. Happy coding!
Last modified: 25 February 2024