for loop in C Programming (With Examples)
Introduction
“If a thing is worth doing, then it is worth doing multiple times.”
This famous saying holds true in various scenarios, and we can easily find ample examples of it. Be it binge-watching your favourite TV shows or movies, eating junk food, travelling, cooking, and whatnot.
The same applies to programming as well, where programmers have to repeat the same code or action to perform a task, like printing a list of names or numbers. That is where Loop comes in, a mechanism to do the same task again and again. In programming, a loop allows programmers to use a set of code or statements repeatedly without writing the code multiple times.
When users want to break out of a loop, it is called loop control. It enables programmers to change loop execution from its original sequence. As soon as the control statement is executed, the loop leaves the scope. Hence, the objects created will be destroyed in no time.
What are Loops in C?
A loop in C programming is used to repeat a block of code several times until the specified condition is met. C loops allow programmers to execute a state or a sequence of statements multiple times without repeating code. It also helps traverse elements of an array.
The C loop program has two parts:
-
body
-
control statement
A control statement is a combination of various conditions directing the body of a loop to execute code. The C loop repeats the same code many times.
Why Use Loops in C Language?
Looping in C simplifies complex problems. With loops, programmers can change the flow of a program by repeating the same code several times rather than writing the same code repeatedly.
For example, if you want to print the first 20 natural numbers or whole numbers, then rather than using the print statement 20 times, you can print inside a loop and run up to 20 iterations.
Benefits of loop in C
-
Code reusability.
-
Traverse easily through elements of data structures.
-
No need to write the same code again and again.
Types of Loops in C
Based on the control statement position in a program, the C loop is categorised into:
- Entry Controlled Loop
Also known as a pre-checking loop, in this, the test condition is checked first before executing the main body of a loop. It includes For Loop and While Loop.
- Exit Controlled Loop
It is also called a post-checking loop. In this C loop, the test condition is assessed after the loop body, which is executed at least once, whether the condition is true or false. It includes Do-while Loop.
So, there are three types of loops in C:
1. while loop
We use a while loop in scenarios when we don’t know the number of iterations. The execution is terminated according to the test condition, so it doesn’t depend on the number of iterations. A block of statement is executed until the specified condition is satisfied. If the test condition proves to be false, it will break from the loop; otherwise, the loop body will be executed.
2. do-while loop
In a do-while loop, the code will be executed until the given condition is met. Here, the loop body will be executed at least once, regardless of the test condition.
The one difference between the while loop and the do-while loop is that in the latter, the test condition is executed at the end of the loop body.
3. for loop
for loops in C programming is used when you need to execute only a section of the code until the given condition is met. It is a repetition control structure allowing programmers to write a loop to be executed a certain number of times. They can perform n number of steps in a single line. It is preferred when the number of iterations is known in advance.
Understanding for loop in C
The C for loop is a more efficient structure than the while loop and do-while loop.
C for loop syntax:
for (initial value; condition; incrementation or decrementation )
{
// Statements in the body of a loop
}
Structure of for loop in C
-
Initialisation
In for loop in C, we assign a loop variable to control the loop. First, the init step is executed only once. It allows you to declare and initialise any loop control variables, and you don’t need to put a statement as long as there is a semicolon.
-
Condition
In this step, the test condition is checked. If the condition proves to be true, then the body of the loop will have control, and there will be an update of loop variables. However, if the condition is false, the control will jump to the next statement after the ‘for’ loop, and the body loop will not be executed.
-
Update
After the loop body is executed, the variable is updated by some value. It can be decremented, incremented, multiplied, or divided by any value.
The condition is evaluated again. If it’s true, the loop is executed, and the whole process repeats itself. But if the condition is false, the loop terminates.
How Does for loop in C work?
-
The initial value or initialisation statement is performed only once.
-
The condition is a Boolean expression, assessing and comparing conditions to a fixed value after every iteration. If the test expression is false, the for loop is stopped.
-
If the test condition is evaluated to be true, the statement in the loop body is executed, and the variable is updated.
-
The test expression is assessed again, and the process continues until the test expression becomes false, after which the loop is terminated.
-
The incrementation or decrementation increases or decreases the counter respectively by a set value.
C for loop Flowchart
The for loop in C is a type of loop that repeats a block of code for a specified number of times.
It has a structure that consists of three parts:
-
initialization
-
condition
-
increment/decrement
Here is the flowchart of a for loop in C:
The flowchart has the following components:
1. Initialization
This is the part where a variable is declared and initialized to a value. It is executed only once at the beginning of the loop.
2. Condition
This is the part where the condition is checked for the loop to continue executing. If the condition is true, the loop continues to execute. If the condition is false, the loop terminates.
3. Body
This is the block of code that is executed repeatedly as long as the condition is true.
4. Increment/Decrement
This is the part where the value of the variable is incremented or decremented. It is executed after the body has been executed.
The C for loop flowchart shows that the 'for loop' starts with initialization, then checks the condition, and executes the body if the condition is true. After executing the body, it increments or decrements the variable and then checks the condition again. This process continues until the condition becomes false, and the loop terminates.
Examples of ‘for loop in C’
Here's some examples of a for loop in C:
Example 1:
#include
int main() {
int i;
for(i = 1; i <= 10; i++) {
printf("%d\n", i);
}
return 0;
}
Code Explanation:
In this example, we have a 'for loop' that will execute 10 times, printing the value of the variable 'i' on each iteration.
Here's a breakdown of the loop:
1. We declare and initialize the variable 'i' to 1.
2. We use the 'for loop' syntax to specify the initialization, condition, and increment/decrement parts of the loop.
3. The condition is set to 'i <= 10', meaning that the loop will continue as long as 'i' is less than or equal to 10.
4. The body of the loop consists of a single statement that prints the value of 'i'.
5. After each iteration, the value of 'i' is incremented by 1 using the 'i++' statement.
6. When the condition becomes false (i.e., 'i' is greater than 10), the loop terminates.
So, when we run this program, it will output the numbers 1 to 10, each on a new line:
1
2
3
4
5
6
7
8
9
10
Example 2:
#include
int main() {
int i, j;
for(i = 1, j = 10; i <= j; i++, j--) {
printf("%d + %d = %d\n", i, j, i+j);
}
return 0;
}
Code Explanation:
In this example, we have a 'for loop' that will execute 10 times, printing the sum of two variables 'i' and 'j' on each iteration.
Here's a breakdown of the loop:
1. We declare and initialize two variables 'i' and 'j' to 1 and 10, respectively.
2. We use the 'for loop' syntax to specify the initialization, condition, and increment/decrement parts of the loop.
3. The condition is set to 'i <= j', meaning that the loop will continue as long as 'i' is less than or equal to 'j'.
4. The body of the loop consists of a single statement that prints the sum of 'i' and 'j'.
5. After each iteration, the value of 'i' is incremented by 1 using the 'i++' statement, and the value of 'j' is decremented by 1 using the 'j--' statement.
6. When the condition becomes false (i.e., 'i' is greater than 'j'), the loop terminates.
So, when we run this program, it will output the sum of numbers from 1 to 10 (inclusive) in descending order:
1 + 10 = 11
2 + 9 = 11
3 + 8 = 11
4 + 7 = 11
5 + 6 = 11
Note that the loop will execute only 5 times, as we have initialized 'i' to 1 and 'j' to 10, and we are decrementing the value of 'j' by 1 in each iteration until it becomes equal to 'i'.
Nested for loops in C Programming
A nested loop is a feature in C where a loop statement is inside another loop. Hence, they are also known as loops inside loops. There can be any number of loops inside another loop, as there are no restrictions defining the number of loops. The nesting level can be at n times. For example, you can define a while loop inside a for loop in C.
Nested for Loop
It refers to any loop defined inside a for loop in C.
Syntax:
for ( initialization; condition; increment ) {
for ( initialization; condition; increment ) {
// statement of inside loop
}
// statement of outer loop
Infinite for loops
An infinite loop is constructed when the test condition never becomes false. So, the loop is executed continuously without being terminated. A program gets stuck in an infinite loop when the condition is always true. Also known as an endless loop or indefinite loop, it either produces a continuous output or no output. It is an error which is resolved using Loop Control Statements.
The for loop in C is mostly used for an infinite loop, as none of the three expressions is required to form a for loop. Leave the conditional expression empty to create an infinite loop.
Applications of ‘for loops in C Programming’
The for loop is used when programmers want to repeat a part of a code a known number of times. Even if they don’t know exactly how many times, the computer does, it counts as for loop.
The real-life applications of for loop are:
-
Print a series of numbers, be it the first ten prime numbers or the first ten odd numbers.
-
Calculate the average grade of a class. The programmer may have no idea how many grades exist, but the computer will. This is computed using the ‘length’ function on an array.
-
Search a number list to find the biggest grade. As the computer knows the number of grades, for loop is apt for it.
C for loop Benefits
-
Programmers know the number of times the loop will be executed before starting the loop.
-
It can execute a block of code repeatedly before requiring you to write the code again and again.
FAQs Related to C for loop
1. What is looping in C?
Also known as iteration, looping refers to repeating the same process again and again until a specific condition is met. When a specific block of statement is executed multiple times, it is known as looping in C.
2. Why should we use looping?
Looping is used for various reasons, including:
-
It enables to change the flow of a program so programmers don’t have to write the same code again and again. They can execute the code for a finite number of times using a loop.
-
It simplifies complicated problems and makes them easier.
For example, if you need to print ‘Programming in C’ 10 times, so rather than printing the statement 10 times, you can use print once in a loop and run 10 iterations.
3. What are the benefits of using looping in C?
There are several advantages of using looping:
-
You can traverse over data structure elements easily, whether it’s a linked list or an array.
-
Allows code reusability.
-
Eliminates the effort of writing the same code repeatedly.
4. What are the essential components of a loop in C language?
The essential components of a loop are as follows:
-
Counter
-
Initialisation with an initial value
-
Condition to assess the optimum value
-
Statement to be executed through iteration
-
Increment/decrement
5. What are different loop control statements?
When a programmer wants to break out of a loop, it is called loop control. A loop control statement helps users change the execution of a loop from its actual sequence. Once it is executed, the loop leaves the scope, and the objects created automatically in it will ultimately be destroyed.
- break statement- It is used to terminate the loop or switch statement and then transfer the execution after the switch or loop. A loop would skip the remainder in the body and retest the actual condition immediately before reiteration.
- continue statement- It skips a few statements based on the given condition.
- goto statement- It transfers control to another labelled statement.
6. What is a while loop?
Syntax of a while loop in C:
while (condition) {
statements;
}
A while loop is an entry-controlled loop where a condition is checked before executing the loop body. If statement is true, the loop body is executed, after which control moves to the beginning and the condition is checked again. This process is repeated until the condition becomes false and the control moves out of the loop. As the control goes out of the loop, it moves to the statements immediately after the loop. The body loop can contain more than one statement. However, if there is just one statement, the curly brackets are not required, but it is recommended to use these brackets in every case. If the condition is false in a while loop, the loop body is not executed even once.
7. Can you explain the do-while in detail with syntax?
Syntax of the do-while loop in C programming:
do {
// statements
} while (expression);
In a while loop, a loop body is executed only when the condition is true. However, there are cases where the loop body must be executed at least once, even if the condition is false. That is where the do-while loop comes into the picture.
Here, the loop body is executed at least once. Once it is executed, it evaluates the condition, and if it’s true, the loop body will be executed again else the control moves out of the loop, and the statement after that loop is executed.
There is also a difference in the syntax of the while loop and the do-while loop. In the former, while is written at the beginning, whereas in the latter, while is written at the end, followed by a semicolon.
8. Which is the best loop to select?
Selecting the right loop is tough row to hoe for any programmer. However, a few steps can help anyone make a better decision:
-
Evaluate the problem to know if it needs a pre-test or post-test loop.
-
In the case of a pre-test loop, a while loop and for loop are available options.
-
In case a post-test is required, opt for a do-while loop.
9. What is the role of initialization in a 'for loop' in C?
Initialization is used to declare and initialize a variable that will be used in the loop. It is executed only once at the beginning of the loop.
10. What is the role of condition in a 'for loop' in C?
Condition is used to specify the condition for the loop to continue executing. It is evaluated before each iteration of the loop, and if the condition is true, the loop continues to execute. If the condition is false, the loop terminates.
11. What is the role of increment/decrement in a 'for loop' in C?
Increment/decrement is used to change the value of the variable used in the loop. It is executed after the body of the loop has executed. It is used to increment or decrement the value of the variable to ensure that the condition of the loop eventually becomes false.
12. Can the initialization, condition, and increment/decrement parts of a 'for loop' in C be omitted?
Yes, any of the three parts of a 'for loop' in C can be omitted, although at least one of them must be present.
13. Can a 'for loop' in C have multiple conditions?
No, a 'for loop' in C can have only one condition. However, the condition can be a compound condition that uses logical operators such as '&&' (logical AND) and '||' (logical OR) to combine multiple conditions.
14. Can the body of a 'for loop' in C be empty?
Yes, the body of a 'for loop' in C can be empty, although it is not recommended.