logo of SA Coder
        Menu
sign in

      References



For Loop



The for loop is one of the most commonly used control structures in programming. It allows you to repeat a set of statements multiple times based on a loop counter. In this post, we will discuss the syntax of for loop and provide some examples to help you understand the concept.



Syntax of For Loop: The for loop has the following syntax:


copy

for (initialise counter; condition; increment counter) {
    // Code to be executed
}



Here's what each of the parts of the for loop syntax means: 1. Initialise counter: This sets the initial value of the loop counter variable. It usually starts at 0 or 1. 2. Condition: This is a Boolean expression that is evaluated at the beginning of each iteration. If the condition is true, the code within the loop is executed. If the condition is false, the loop terminates. 3. Increment counter: This is used to increment or decrement the loop counter variable by a certain value. This allows the loop to move to the next iteration. Now that we understand the syntax, let's look at some examples.



Example 1:



copy

// Display all pairs in (1, 2, 3, 4, 5) except the same pairs.
#include <stdio.h>
int main() {
    int i, j;
    for (i = 1; i <= 5; i++) {
        for (j = 1; j <= 5; j++) {
            if (i == j) {
                continue;
            }
            printf("(%d %d) ", i, j);
        }
    }
    return 0;
}



In this example, we have used two for loops to display all pairs of numbers between 1 and 5 except for the same pairs. The outer for loop is used to iterate through the first number, and the inner for loop is used to iterate through the second number. We use the continue statement to skip the same pairs, and printf statement to display the pairs.



Example 2:



copy

// Input a number and display pattern as given below
// and number = line of patterns

//           *
//          ***
//         *****
//        *******
//       *********
#include <stdio.h>
int main() {
    int num;
    printf("Enter a number\n");
    scanf("%d", &num);
    for (int i = num; i > 0; i--) {
        for (int j = 0; j < (i - 1); j++) {
            printf(" ");
        }
        for (int j = 0; j < ((num - i + 1) * 2) - 1; j++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}



In this example, we have used a for loop to display a pattern of stars based on the input number. The outer for loop is used to iterate through each line of the pattern, and the inner for loop is used to print the spaces before the stars. We then use another inner for loop to print the stars, and finally, we print a new line character to move to the next line.



Conclusion:


The for loop is an essential tool in programming and can help you create efficient and optimized code. By understanding the syntax and examples provided in this post, you can start using for loops in your own programs.




Please login first to comment.