It has the following syntax:
for (initialization; condition; increment/decrement)
{
// Statements to repeat(loop body)
}
In this syntax,
- Initialization: It is used to set the loop variable before it starts (e.g., int count = 1;). It just runs once.
- Condition: The condition statement checks the given condition. If the condition is true, it executes the of for loop. If the condition is false, it terminates the for loop.
- Update (Increment/Decrement): After execution of each loop, it adjusts the loop variable (e.g., count++) to help it reach the stopping point.
- Loop Body: It represents the loop of the body. It continues to run as long as the condition holds true.
Flowchart of for Loop
In the flowchart provided, follow these steps to incorporate the for loop in C++:
Begin by navigating to the for loop section and setting up the variables along with their respective initial values.
Step 2: Subsequently, the control flow transitions to the conditional statement.
In this step, the program evaluates the condition. If the condition is met, the code within the loop is executed. Conversely, if the condition is not met, the loop is exited, and the program proceeds to the next iteration.
Afterward, the program moves on to the update expression, where the value is either incremented or decremented by 1. Following this, it loops back to step 3 to evaluate the condition again.
Step 5: Finally, it exits the loop and displays the output.
C++ Example to Display Numbers from 1 to 5
Let's consider a basic example to demonstrate how to output numbers from 1 to 5 utilizing a for loop in the C programming language.
Example
#include <stdio.h>
int main() //main function
{
for (int count = 1; count <= 5; count++)
{
printf("The number is: %d\n", count);
}
return 0;
}
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
Explanation:
In this instance, we employ a for loop to display numbers from 1 to 5. Subsequently, the iteration commences with count = 1 and increments by 1 in each cycle, displaying the present value along with a message until the count hits 5.
C Example to Print Even Numbers Between 2 and 10
Let's consider a basic example to demonstrate how to output even numbers between 2 and 10 using a for loop in the C programming language.
Example
#include <stdio.h>
int main() //main function
{
for (int num = 2; num<= 10; num += 2)
{
printf("The even number is: %d\n", num);
}
return 0;
}
Output:
The even number is: 2
The even number is: 4
The even number is: 6
The even number is: 8
The even number is: 10
Explanation:
In this instance, we produce even integers ranging from 2 to 10 by employing a for loop. The iteration commences at 2 and increases by 2 in each step, displaying the present number as an even value until it hits 10.
Nested for Loop in C
In the C programming language, a nested for loop is when one for loop is enclosed within another for loop. Each time the outer loop runs, the inner loop completes its full iteration. This approach is especially useful for handling two-dimensional data, creating patterns, or performing repetitive tasks in a structured way.
Syntax
It has the following syntax:
for (initialization; condition; increment) {
for (initialization; condition; increment) {
// statement of inner loop
}
//statement of outer loop
}
Flowchart of the Nested for Loop in C
How do we use a nested for loop in C?
- The outer loop should be used to regulate the primary sequence (for example, rows in a matrix).
- In order to accommodate sub-iterations, place the inner loop inside the outer loop (for example, columns).
- Set the correct initialization, condition, and update expressions for both loops.
- Add the logic that we want to run inside the inner loop's body.
- Structure the output by using line breaks or formatting methods as required.
C Nested for Loop Example
Let's consider a basic example to demonstrate the concept of a Nested for loop in the C programming language.
Example
#include <stdio.h>
int main() //main function
{
int rows = 7;
for (int row_num = 1; row_num <= rows; row_num++)
{
for (int col_num = 1; col_num <= row_num; col_num++)
{
printf("%d ", col_num);
}
printf("\n");
}
return 0;
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
Explanation:
In this illustration, we display a right-angled triangle composed of numbers by employing a nested for loop. For every row ranging from 1 to 7, it showcases a sequence of numbers starting from 1 up to the corresponding row number, resulting in an increasing numeric pattern.
C Example to print Star Pattern for Right-Angled Triangle
Let's consider a basic example to demonstrate how to print a Star Pattern for a Right-Angled Triangle by employing nested for loops in the C programming language.
Example
#include <stdio.h>
int main() //main function
{
for (int row_no = 1; row_no <= 5; row_no++)
{
for (int column_no = 1; column_no <= row_no; column_no ++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Output:
*
**
***
****
*****
Explanation:
In this instance, we produce a triangular pattern by using a nested for loop. The outer loop determines the quantity of lines, and the inner loop displays increasing asterisks (*) on each line to create the triangular design.
Infinite for loop in C
In C programming, a for loop that runs infinitely persists without a stopping condition or with a perpetually true condition. Such a loop proves beneficial in scenarios like real-time systems involving human input, sensor data collection, or server communication.
Syntax:
It has the following syntax:
for (;;)
{
// This code will keep running for infinite.
}
By omitting a condition, the loop will persist endlessly. If needed, we have the option to halt the loop using a break statement or alternative logic.
C Example for Infinite Loop
Let's consider a basic example to demonstrate the infinite for loop in the C programming language.
Example
#include <stdio.h>
int main() //main function
{
for (;;)
{
printf("The clock is running. Press Ctrl + C to stop the flow.\n");
}
return 0;
}
Output:
The clock is running. Press Ctrl + C to stop.
The clock is running. Press Ctrl + C to stop.
The clock is running. Press Ctrl + C to stop.
The clock is running. Press Ctrl + C to stop.
Explanation:
In this illustration, we are showcasing an infinite for loop that displays the statement "The clock is running". To terminate the loop, the user needs to press Ctrl + C on the keyboard. Since there is no specified termination condition within the loop, it will persist in execution until the user intervenes by pressing Ctrl + C.
Advantages of a for loop in C
Several advantages of a for loop in C. Some main advantages are as follows:
- If we want to make code clean, start, condition, and update are combined into a single line.
- It gives us complete control over where the loop starts, ends, and how it moves.
- Simple reasoning is extremely easy to read and understand.
- It works well with arrays that have index-based access.
- Fixed loops run well with low overhead.
Best practices for using a for Loop in C Language
Several best practices for using for a Loop in C language are as follows. Some of them are as follows:
- Instead of just i or j, use explicit labels, such as index or count.
- Avoid hardcoding integers in favor of constants.
- Keep loop updates contained inside the for loop header.
- We cannot update any variables inside the loop body.
- Comment on any complex or nested code.
Uses of the for loop in C
Several uses of the for loop in C are as follows:
- Create a loop to access or alter each element in an array.
- Print patterns such as stars, numbers, and triangles with nested loops.
- Loop through numbers to calculate a sum or factorial.
- Search for or sort elements using basic algorithms.
- Traverse 2D arrays to execute row and column operations.
Examples: for loop in C
1. Displaying Multiplication Table of a given number
Let's consider a basic example to demonstrate how to showcase the Multiplication Table of a specified number by utilizing a for loop in the C programming language.
Example
#include <stdio.h>
int main() //main function
{
int num;
printf("Enter the multiplication table number you want to print: ");
scanf("%d",&num);
for (int q = 1; q <= 10; q++)
{
printf("%d x %d = %d\n", num, q, num * q);
}
return 0;
}
Output:
Enter the multiplication table number you want to print: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Explanation:
In this instance, we receive an input number from the user and display a multiplication chart up to 10. Subsequently, a for loop is employed to calculate the product of the provided integer with numbers ranging from 1 to 10, showcasing the outcomes in an organized manner.
2. Calculating the Factorial of a Given Number
Let's consider a basic example to demonstrate the process of calculating the factorial of a specified number using a for loop in the C programming language.
Example
#include <stdio.h>
int main() //main function
{
int num, ans = 1;
printf("Enter the number: ");
scanf("%d",&num);
for (int fact_orial = 1; fact_orial <=num; fact_orial++)
{
ans *= fact_orial;
}
printf("Factorial of a given number is %d = %d", num, ans);
return 0;
}
Output:
Enter the number: 5
Factorial of a given number is 5 = 120
Explanation:
In this instance, a for loop is utilized to calculate the factorial of a variable provided by the user. Subsequently, it multiplies all whole numbers from 1 up to the inputted value and then showcases the resulting factorial.
3. Checking if a Number is Prime or not
Let's consider a basic example to demonstrate how to determine whether a number is a prime number or not by utilizing a for loop in the C programming language.
Example
#include <stdio.h>
int main() //main function
{
int number, primeFlag = 1;
printf("Enter the number: ");
scanf("%d",&number);
for (int d = 2; d <= number / 2; d++)
{
if (number % d == 0)
{
primeFlag = 0;
break;
}
}
if (primeFlag)
printf("%d is a Prime number", number);
else
printf("%d is Not Prime a number", number);
return 0;
}
Output:
Enter the number: 7
7 is a Prime number
Explanation:
In this illustration, we establish whether a provided integer is a prime number by assessing its divisibility from 2 up to half of the number. If the program identifies a divisor, it flags the number as not prime; if not, it verifies that the number is indeed prime.