We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Difference between for and while loop in C, C++, Java
In C, C++, and Java, both for loop and while loop is used to repetitively execute a set of statements a specific number of times. However, there are differences in their declaration and control flow. Let’s understand the basic differences between a for loop and a while loop.
for Loop
A for loop provides a concise way of writing the loop structure. Unlike a while loop, a for loop declaration consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping.
Syntax
for (initialization condition; testing condition; increment/decrement)
{
// statement(s)
}
Flowchart of for Loop
Example: Program to Demonstrate How to Use for Loop
A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
Syntax
while (boolean condition)
{
// loop statements...
}