For Loop in C programming with examples

For loop in C programming is a statement to repeat the set of statements until a condition to be satisfied.

Syntax of for loop statement:

for(initialization; conditionCheck; updation )
{
statement 1;
statement 2;
————–
}

“for-statement” has a initialization , condition and iteration (increment/ decrement) part separated by semicolon.

Initialization : This phase allows you to initialize loop control variables.

ConditionCheck : If condition of for-loop is true, then the body of the loop will execute.

The body of the loop does not execute if the condition is false, and the flow of control jumps to the next statement just after the ‘for’ loop

Updation: This statement allows you to update(increment/ decrement any loop control variables.

Example: Write a program to print 1 to 10 using for-loop.

OUTPUT

In a for loop either initialization or iteration , or both may be absent but condition must be present in a for loop.

OUTPUT

1
2
3
4
5
6
7
8
9
10

Example: Write a program to take a number from user and find its factorial.

Example: Write a program to take a number from user and check whether an number (entered by the user) is a prime number or not.

Prime Number : prime number is a number which  satisfies the following conditions.

  • It should be whole number
  • It should be greated than 1
  • It should have only 2 factors. They are, 1 and the number itself.

 Example for prime numbers: 2, 3, 5, 7, 11, 13, 17, 19, 23,29 etc. because this numbers is only divided by 1 and the number itself.

Number  4, 6, 8, 9, 10, 12, 14, 15, 16 etc are not prime numbers. Because, the number 4 can be divided by 2. 

As per the rule of prime number,  should be divide 2 numbers only. They are 1 and the number itself. 

But, number 4 is also divided by 2. Similarly , all remaining numbers 6, 8, 9, 10, 12, 14……..  also divided by a number other than 1 and the number itself.

Therefore these are not a  prime numbers.

Number 1 is neither a prime nor a composite number.

OUTPUT

OUTPUT

Multiple Initialization in For Loop

we can provide multiple initialization and updation of variables in for loop

for(i=0,j=0,i<=10;i++,j++)

Consider one example

Program Print the value of i and j using for loop

i=1,j=10
i=2,j=9
i=3,j=8
i=4,j=7
i=5,j=6
i=6,j=5
i=7,j=4
i=8,j=3
i=9,j=2
i=10,j=1

Nested For Loop

A for loop can be used inside another for loop this condition is known as nesting of for loop.

Other then for you can also use while or do while loop.

We can also use other statements like if else as per our requirement inside any loop.

Example: Printing numbers using nested for loop in C

OUTPUT

i=1, j=1
i=1, j=2
i=2, j=1
i=2, j=2
i=3, j=1
i=3, j=2