Difference between for loop and while loop

Can you please give me the explanation.

1 Like

@brindhubala30 Hello,

We have recieved your query.
This was a really nice question which you have asked.

Give us a couple of minutes & we will reach out with the solution for your query

Zeba Kainat| TA- Edyoda

3 Likes

For Loop :A for loop is a control flow statement that executes code for a predefined number of iterations. The keyword used in this control flow statement is “for”. When the number of iterations is already known, the for loop is used.

Syntax
for(initialization; condition; iteration){
//body of the ‘for’ loop
}

While Loop : A loop that runs a single statement or a set of statements for a given true condition. This loop is represented by the keyword “while.” When the number of iterations is unknown, a “while” loop is used. The statement is repeated until the boolean value is false. Because the condition is tested at the beginning of a while loop, it is also known as the pre-test loop.

Syntax
while ( condition) {
statements;
//body of the loop
}
Example

2 Likes

Both a while loop and a for loop are used for iteration.

Essentially a while loop is used when one does not know how many times a loop needs to iterate.

A for loop on the other hand is very helpful for circumstances where the number of iterations is known in advance or is linked to the size of a data container through which it must iterate.

In most languages any while loop can be constructed as a for loop and vice verse, but readability and comprehension are also important considerations in deciding which form of iterative construct to use.