Control Structure
🧭 Control Structures in C
Control structures determine the flow of execution in a program. They help in decision making, looping, and jumping to specific parts of the program.
🔀 Decision Making Structures
1. if Statement: Executes a block if a condition is true.
if (x > 0) {
printf("Positive");
}
2. if-else Statement: Executes one block if true, another if false.
if (x % 2 == 0) {
printf("Even");
} else {
printf("Odd");
}
3. Nested if-else: if or if-else inside another if or else block.
if (x > 0) {
if (x < 100) {
printf("Positive and less than 100");
}
}
4. switch Statement: Used when multiple cases depend on a single variable.
switch (choice) {
case 1: printf("One"); break;
case 2: printf("Two"); break;
default: printf("Invalid");
}
🔁 Loop Control Structures
1. while Loop: Checks condition first, then executes block repeatedly.
int i = 0;
while (i < 5) {
printf("%d", i);
i++;
}
2. do-while Loop: Executes block once before checking condition.
int i = 0;
do {
printf("%d", i);
i++;
} while (i < 5);
3. for Loop: Best for known number of iterations.
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
4. Nested for Loop: One for loop inside another.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
printf("%d %d\n", i, j);
}
}
🧩 Other Control Statements
1. break: Exits a loop or switch immediately.
for (int i = 0; i < 5; i++) {
if (i == 3) break;
printf("%d", i);
}
2. continue: Skips the rest of loop body for current iteration.
for (int i = 0; i < 5; i++) {
if (i == 2) continue;
printf("%d", i);
}
3. goto: Jumps to a labeled part of the program (use with caution).
goto label;
printf("This won't print");
label:
printf("Jumped here");
4. exit(): Terminates the program immediately.
if (error) {
printf("Exiting...");
exit(0);
}
Comments
Post a Comment
write your complements and complaints :)