Differences between for and while Loop in C

21 May 2023 Balmiki Mandal 0 C Programming

Difference Between for and while Loop in C

In the C programming language, for and while loops are the two most popular looping structures. Both of these types of loops serve the same purpose, but there are some notable differences between them. This article will discuss the differences between for and while loops in C.

For Loop

A for loop is a type of loop that runs a set amount of times, according to an initialization, condition, and incremental/decremental statement. The syntax for a for loop in C is:

for (initialization; condition; incremental/decremental) 
{ 
    // code here 
}

The "initialization" statement usually sets up a variable which will be used as the loop counter. The "condition" statement is evaluated at the beginning of each loop and decides if the loop should keep running. The "incremental/decremental" statement executes at the end of every iteration and updates the loop counter variable.

While Loop

A while loop is a type of loop that runs until a certain condition is met. The syntax for a while loop in C is:

while (condition) 
{ 
    // code here 
}

The condition is evaluated at the start of each iteration, and if it is true the loop runs and if it is false the loop terminates. Unlike a for loop, a while loop does not have an initialization or incremental/decremental statement.

Differences

The major difference between a for and while loop is that in a for loop the number of iterations is predetermined while in a while loop the condition is tested and the loop is run an unknown number of times, depending upon the condition.

The for loop is usually preferable when the number of iterations is known in advance, while the while loop is more suited to situations where the number of iterations is unknown. Generally, a for loop is more concise and easier to read than a while loop.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.