Detailed Explanation of For Loop in C Language

The for loop in C language is used to execute a statement or a part of a program multiple times. It is often used to traverse data structures such as arrays and linked lists.
The syntax of the for loop in C is as follows:
for (Expression 1; Expression 2; Expression 3) {    // Code to execute}

Example of For Loop in C

Here is a simple for loop program to print the multiplication table of 1:

👇 Click to get👇

👉 Collection of C Language Knowledge Materials

#include <stdio.h>
int main() {    int i;        for (i = 1; i <= 10; i++) {        printf("%d \n", i);    }
    return 0;}
Output:
12345678910
Program to print the multiplication table of a given number using for loop:
#include <stdio.h>
int main() {    int i, number;        printf("Enter a number: ");    scanf("%d", &number);
    for (i = 1; i <= 10; i++) {        printf("%d \n", (number * i));    }
    return 0;}
Output:
Enter a number: 22468101214161820

Loop Body

The curly braces {} are used to define the scope of the loop. However, if the loop contains only a single statement, we do not need to use curly braces. A loop can exist without a loop body. The curly braces act as block delimiters, meaning that variables declared within the for loop are only valid within that block and not outside of it. Consider the following example:
#include <stdio.h>
int main() {    int i;        for (i = 0; i < 10; i++) {        int i = 20;        printf("%d ", i);    }
    return 0;}
Output:
20 20 20 20 20 20 20 20 20 20

Infinite For Loop

To create an infinite for loop, we do not need to provide any expressions in the syntax. Instead, we just need to provide two semicolons to validate the for loop syntax. This will act as an infinite for loop.
#include <stdio.h>
int main() {    for (;;) {        printf("Welcome to javatpoint");    }}
Programmer Technical Exchange Group

Scan the code to join the group, remember to note: city, nickname, and technical direction.

Leave a Comment