The for loop in C is a control structure that allows for repeated execution of a block of code as long as a specified condition is true. It is particularly useful for iterating a known number of times. The for loop consists of three main components: initialization, condition, and increment/decrement.
The general syntax of a for loop is as follows:
for (initialization; condition; increment/decrement) {
// Statements to be executed repeatedly
}
Initialization: This step initializes the loop control variable. It is executed only once at the beginning of the loop.
Condition: Before each iteration, the condition is evaluated. If it evaluates to true, the loop body executes; if false, the loop terminates.
Increment/Decrement: At the end of each iteration, the loop control variable is updated, which can be either incremented or decremented.
Here is a simple example of a for loop that increments a variable:
#include <stdio.h>
int main() {
for (int i = 1; i <= 3; i++) {
printf("%d\n", i);
}
return 0;
}
Output:
1
2
3
In this example, the loop starts with i initialized to 1. It continues to execute as long as i is less than or equal to 3, incrementing i by 1 after each iteration.
A for loop can also decrement a variable. Here’s an example that counts down from 10 to 1:
#include <stdio.h>
int main() {
for (int i = 10; i > 0; i--) {
printf("%d\n", i);
}
return 0;
}
Output:
10
9
8
7
6
5
4
3
2
1
In this case, the loop initializes i to 10 and decrements it by 1 each time until i is no longer greater than 0.
You can also initialize multiple variables in a for loop and use multiple conditions. Here’s an example:
#include <stdio.h>
int main() {
for (int i = 1, j = 1; i < 5 && j < 5; i++, j++) {
printf("i: %d, j: %d\n", i, j);
}
return 0;
}
Output:
i: 1, j: 1
i: 2, j: 2
i: 3, j: 3
i: 4, j: 4
This loop initializes two variables, i and j, and continues to execute as long as both are less than 5.
You can skip the initialization or increment sections of the for loop. For example:
#include <stdio.h>
int main() {
int num = 10;
for (; num < 20; num++) {
printf("%d\n", num);
}
return 0;
}
In this example, the initialization is done before the loop, and the increment is handled within the loop.
You can also nest for loops, which is useful for working with multi-dimensional arrays:
#include <stdio.h>
int main() {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
printf("%d, %d\n", i, j);
}
}
return 0;
}
Output:
0, 0
0, 1
0, 2
0, 3
1, 0
1, 1
1, 2
1, 3
In this example, the outer loop iterates twice while the inner loop iterates four times for each iteration of the outer loop.
The for loop is a powerful construct in C that allows for efficient iteration over a range of values. By utilizing increment and decrement operations, you can control the flow of your program effectively, making it a fundamental tool for programming in C.
The break statement is used to exit a loop prematurely. When a break statement is encountered inside a loop, the loop immediately terminates, and the program execution continues with the next statement outside the loop.
Here's an example of using break in an infinite for loop:
#include <stdio.h>
int main() {
for (;;) {
int num;
printf("Enter a number (0 to exit): ");
scanf("%d", &num);
if (num == 0) {
break;
}
printf("You entered: %d\n", num);
}
printf("Loop terminated.\n");
return 0;
}
In this example, the loop will continue to execute until the user enters the value 0. When 0 is entered, the break statement is executed, and the loop terminates. The program then prints "Loop terminated." and exits.
The continue statement is used to skip the current iteration of a loop and move on to the next iteration. When a continue statement is encountered inside a loop, the current iteration is terminated, and the loop control jumps to the next iteration.
Here's an example of using continue in an infinite for loop:
#include <stdio.h>
int main() {
for (;;) {
int num;
printf("Enter a number (negative number to skip): ");
scanf("%d", &num);
if (num > 20) {
continue;
}
printf("You entered: %d\n", num);
}
return 0;
}
In this example, the loop will continue to execute until the program is terminated manually (e.g., by pressing Ctrl+C). If the user enters a negative number, the continue statement is executed, and the current iteration is skipped. The loop then moves on to the next iteration, prompting the user to enter another number.
Note that in an infinite loop, using continue alone will not terminate the loop. It will simply skip the current iteration and move on to the next one. To exit an infinite loop, you need to use a break statement or terminate the program manually.
It's important to use break and continue statements judiciously to maintain the intended flow of your program and avoid unintended behavior or infinite loops.
The while loop is used to repeatedly execute a block of code as long as a given condition is true. It follows these steps:
The condition is evaluated first.
If the condition is true, the loop body is executed.
After the loop body is executed, the condition is evaluated again.
Steps 2 and 3 are repeated until the condition becomes false.
Here's an example of a while loop that prints numbers from 1 to 5:
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
return 0;
}
Output:
1
2
3
4
5
In this example, the loop condition i <= 5 is evaluated first. Since i is initially 1, the condition is true, and the loop body is executed, printing the value of i. After that, i is incremented by 1. The loop continues until i becomes greater than 5, at which point the condition becomes false, and the loop terminates.
The do-while loop is similar to the while loop, but it executes the loop body at least once before checking the condition. It follows these steps:
The loop body is executed first.
After the loop body is executed, the condition is evaluated.
If the condition is true, the loop body is executed again.
Steps 2 and 3 are repeated until the condition becomes false.
Here's an example of a do-while loop that prints numbers from 1 to 5:
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i >= 5);
return 0;
}
Output:
1
In this example, the loop body is executed first, printing the value of i. After that, i is incremented by 1. The condition i <= 5 is then evaluated. Since i is initially 1, the condition is false and the loop terminates.
Condition Evaluation: The while loop checks the condition before executing the loop body, while the do-while loop checks the condition after executing the loop body.
Minimum Execution: The do-while loop is guaranteed to execute at least once, even if the condition is false from the beginning. The while loop may not execute at all if the condition is false initially.
Termination: The while loop terminates when the condition becomes false. In the do-while loop, the loop body is executed as long as the condition is true.
Syntax: The do-while loop requires a semicolon at the end, while the while loop does not.
In summary, both while and do-while loops are used for repetitive tasks in C programming, but they differ in the way they handle the condition and the execution of the loop body. The choice between the two depends on the specific requirements of your program.
The switch statement in C is a control statement that allows you to execute different parts of code based on the value of an expression. It is particularly useful when you have multiple possible values for a variable and want to execute different code blocks depending on which value it matches.
The basic syntax of a switch statement is as follows:
switch (expression) {
case constant1:
// Code to execute if expression equals constant1
break;
case constant2:
// Code to execute if expression equals constant2
break;
// You can have any number of case statements
default:
// Code to execute if expression does not match any case
}
Expression: This is evaluated once and compared with the values in the case statements. The expression must evaluate to an integral type (such as int, char, or enum).
Case Labels: Each case label is followed by a constant value. If the expression matches a case label, the code following that label is executed.
Break Statement: The break statement is used to terminate a case and exit the switch block. If break is omitted, execution will continue into the next case (this is known as "fall-through").
Default Case: The default case is optional and is executed if none of the case values match the expression.
Here’s a simple example that demonstrates how to use a switch statement in C:
#include <stdio.h>
int main() {
int day;
printf("Enter a number (1-7) for the day of the week: ");
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 input! Please enter a number between 1 and 7.\n");
}
return 0;
}
Input: The program prompts the user to enter a number between 1 and 7, which corresponds to the days of the week.
Switch Statement: The switch statement evaluates the value of day.
Case Execution: Depending on the value entered, the corresponding case block is executed, printing the name of the day.
Default Case: If the user inputs a number outside the range of 1 to 7, the default case will execute, informing the user of the invalid input.
Fall-Through Behavior: If you omit break, execution will continue into the next case. This can be useful in some scenarios, but it can also lead to bugs if not handled carefully.
switch (value) {
case 1:
printf("hello");
case 2:
printf("Value is either 1 or 2\n");
break;
case 3:
printf("Value is 3\n");
break;
default:
printf("Value is something else\n");
}
Constant Values: The values used in case labels must be constant expressions, and they must be unique within the same switch statement.
Expression Types: The expression in a switch statement can only be of integral types (like int, char, or enum). It cannot be a floating-point type or a string.
The switch statement is a powerful control structure in C that provides a clean and efficient way to handle multiple conditional branches based on the value of a single expression. By using switch, you can improve the readability and maintainability of your code, especially when dealing with numerous conditions.
Problem: Write a C program to calculate and print a student's grade based on their average score.
Requirements:
Use a for loop to input 5 subject marks.
Calculate the average score.
Use a switch case to determine the grade based on the following criteria:
Average >= 90: Grade A
Average >= 80: Grade B
Average >= 70: Grade C
Average >= 60: Grade D
Otherwise: Grade F
Print the calculated average and the corresponding grade.
Additional Challenge:
Implement error handling for invalid input (e.g., marks outside the range of 0-100).
Allow the user to input the number of subjects.