For Loop in C


1.What is for loop in C ?

Ans: The for loop in C Language provides a functionality/feature to repeat a set of statements a defined number of times. The for loop is in itself a form of an entry-controlled loop.


Simple Explanation :

In this picture we can see that there is a group of best friends. We can see that all going in group.

The working of for loop is also same. The for loop is a group of initialization of a value to variable , condition and update means increment or decrement of a value.







Working of for loop :



Syntax  :

for(initialization; check/test expression; updation)
{    
     // body consisting of multiple statements
}




Example:

1. Write a C program to print numbers 1 to n numbers.
#include<stdio.h>    // Include the standard input/output header file.
int main ( )
{
        int num,i;     //Declare variables for loop and to take user input
        printf("Enter the number till you want to print ");
        scanf("%d",&num);
        for (i=0;i<=num;i++)   // Start a for loop 
        {
                printf("%d\n",i);  // Print the number.
        }
  }


Output :



2. Write a C program to display the cube of the number up to an integer.

#include <stdio.h>  // Include the standard input/output header file.
int main() 
{
    int i, num;  // Declare variables 'i' for loop counter and 'num' for user input.

    printf("Input number of terms : ");  // Print a message to prompt user input.
    scanf("%d", &num);  // Read the value of 'num' from the user.

    for (i = 1; i <= num; i++)   // Start a for loop 
{
        printf("Number is : %d and cube of the %d is :%d \n", i, i, (i * i * i));  // Print the number, its cube, and message.
    }
}

Output :



3.Write a program in C to display the multiplication table
 for a given integer.

int main() 
{
    int j, n;  // Declare variables 'j' for loop counter and 'n' for user input.

    printf("Input the number (Table to be calculated) : ");  // Print a message to prompt user input.
    scanf("%d", &n);  // Read the value of 'n' from the user.
    printf("\n");  // Print a newline for formatting.

    for (j = 1; j <= 10; j++)   // Start a for loop to calculate the table up to 10.
    {    
printf("%d X %d = %d \n", n, j, n * j);  // Print the multiplication expression and result.
    }
}

Output :