Control structures
Control Structures Control structures allow a program to execute different blocks of code based on specific conditions. These structures are commonly used t...
Control Structures Control structures allow a program to execute different blocks of code based on specific conditions. These structures are commonly used t...
Control Structures
Control structures allow a program to execute different blocks of code based on specific conditions. These structures are commonly used to improve the readability and maintainability of code by enabling programmers to express complex relationships between different parts of the program.
There are three primary control structures in C:
If-else: An if-else statement allows a program to execute different blocks of code based on a specific condition. It has two parts: the condition and the block of code to be executed if true or the block of code to be executed if false.
Switch-case: A switch-case statement allows a program to execute different blocks of code based on the value of a single variable. Each case in the switch statement corresponds to a specific value of the variable, and the code inside each case is executed accordingly.
For loop: A for loop allows a program to execute a block of code a specified number of times. It has three parts: the initialization statement, the condition statement, and the post-condition.
Here are some examples to illustrate these control structures:
c
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18) {
printf("You are eligible to vote.\n");
} else {
printf("You are not eligible to vote.\n");
}
return 0;
}
c
#include <stdio.h>
int main() {
int day;
printf("Enter a day (1-7): ");
scanf("%d", &day);
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
c
#include <stdio.h>
int main() {
int i, n;
printf("Enter a number: ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
printf("%d ", i);
}
return 0;
}
These examples demonstrate the basic concepts of control structures, showing how they allow programs to make decisions and execute different code blocks based on specific conditions