For Vs. While Loop In C

In C++, various iterations of the 'for' loop are incorporated to enhance the language's versatility, potency, and adaptability. For instance, the for loop empowers us to manage the loop by incorporating multiple variables within it, along with employing the converge function alongside the 'for' loop. Conversely, the while loop does not support as many variations; it necessitates adherence to the standard syntax.

There exist notable distinctions between the for and while loops, which are elaborated upon in the following comparative table.

For Loop is defined as

There exist two variations of for loops in Java. One is the conventional form, and the other is the for-each form.

The most general form of a for loop statement.

Example

for (initialization; condition; iteration)
{
	//body of for loop
}
  • Initialization: The for loop's loop controlling variable is only initialised once, during the first iteration of the loop. The loop controlling variable is initialised here; if the loop variable is never used again in the programme and is only used as the loop's controlling variable, it is both declared and initialised in the 'for' loop.
  • Condition: The 'for' loop's condition is executed each time the loop is iterated.
  • The iteration statement is an expression that increments or decrements the loop controlling variable.

When the loop runs, it begins with the initialization condition, then proceeds to evaluate the condition. If the condition is satisfied, the loop body is executed, and subsequently, the iteration statement is processed. The condition is re-evaluated to decide if the loop will continue to iterate or end.

In Java, the initialization and iteration statements have the capability to include multiple statements. Each statement is separated by a comma. In Java, a comma serves as a separator; whereas in C++, a comma functions as an operator that can be utilized in any valid expression.

The syntax of the for-each loop

The "for-each" structure represents a more sophisticated iteration alternative to the traditional for loop. The for-each loop is structured as follows.

Example

for(type iter_variable: collection) statement-block

The "type" parameter defines the kind of iteration variable, which is then followed by the actual variable used for iteration. The iteration variable will receive elements from the collection variable. It's essential that the type matches the elements' type in the collection variable. The for-each version of the for loop streamlines the iteration process, moving from the start to the end while accessing values sequentially.

Example

There are different kinds of collections that are compatible with a for loop. Let's delve into this topic by considering an array as the collection.

Example

public class Main
{ 
	public static void main(String[] args) 
	{ 
		int array[]={10, 20, 30, 40, 50, 60}; 
		int add=0; 
		for( int c: array) 
		{ 
			System.out.println( "value in c " + c); 
			add = add+c; 
		} 
		System.out.println("additon of array elements is " +add); 
	}
}

Output:

Output

value in c 10
value in c 20
value in c 30
value in c 40
value in c 50
value in c 60
additon of array elements is 210

'c' functions as the iteration variable in this scenario, sequentially fetching the values from array, in ascending order of index, one at a time. The iteration continues until all elements within the array have been inspected. If necessary, the loop can be prematurely terminated using the "break" statement. Notably, modifications to the iteration variable do not impact the array as it is a strictly read-only entity.

While loop is defined as

The while loop stands as one of the fundamental loops in both C++ and Java. The functionality of a while loop remains consistent across C++ and Java programming languages.

Syntax

The following is the while loop declaration:

Example

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

The while loop evaluates the condition initially and proceeds to run the statements repeatedly as long as the condition remains true. The condition within a while loop can consist of any boolean expression. If the expression yields a non-zero value, the condition is considered true; conversely, if it yields a zero value, the condition is false.

If the specified condition evaluates to true, the loop will continue iterating; however, if the condition is false, the control will shift to the line of code that directly follows the loop. The loop body may consist of an empty statement, a single statement, or a group of statements.

Example

Exploring the functionality of a while loop, the provided code snippet will output numbers 1 through 10.

Example

public class Main
{ 
	public static void main (String args[]) 
	{ 
		int n=0; 
		while(n<10) 
		{ 
			n++; 
			System.out.println("n=" +n); 
		} 
	}
}

Output:

Output

n=1
n=2
n=3
n=4
n=5
n=6
n=7
n=8
n=9
n=10

The starting value of 'n' in this scenario is 0, resulting in the while loop condition being satisfied. Consequently, the program flow proceeds into the body of the while loop, where the variable 'n' is incremented as specified in the initial statement.

The 'n' value gets displayed, and then the program goes back to the while loop condition where 'n' is updated to 1. This satisfies the condition again, and the loop's instructions are carried out once more. This process repeats until the condition evaluates to false, signaling the end of the loop.

The 'while' loop, similar to the 'for' loop, has the capability to set the control variable at the start of the loop, specifically during the condition evaluation.

Example

//for example
while((ch = getchar( ) ) != 'A')
{
System.out.println(" The input alphabet " +ch);
}

At the beginning of the loop, the control variable 'ch' is set, and the loop's condition is checked.

Note: If there is only one statement in the body of the loop, whether it is a for loop or a while loop, the curly braces are not required.

In C, what is the difference between a for loop and a while?

Parameters For Loop While Loop
Declaration for(initialization ; condition ; iteration ) {//body of 'for' loop} initializationwhile ( condition ) {statements;//body of loop}
Format. At the top of the loop, initialization, condition checking, and iteration statements are written. At the top of the loop, only initialization and condition checking are performed.
Use. The 'for' loop was only used when the number of iterations was already known. When the number of iterations is unknown, the 'while' loop is used.
Condition. If the condition is not included in the 'for' loop, the loop iterates indefinitely. If the condition is not included in the 'while' loop, a compilation error occurs.
Initialization The initialization is never repeated in a 'for' loop. If initialization is performed during condition checking in a while loop, initialization is performed each time the loop iterates.
Iteration assertion Because the iteration statement in the 'for' loop is written at the top, it executes only after all statements in the loop have been executed. The iteration statement in a 'while' loop can be written anywhere in the loop.

The Key Differences Between for and while loop

  • Initialization, condition checking, and increment or decrement of iteration variables are all done explicitly in the loop syntax only. In contrast, in the while loop, we can only initialise and check the condition in the loop syntax.
  • When we know the number of iterations that must occur in a loop execution, we use the for loop. On the other hand, if we do not know how many iterations must occur in a loop, we use a while loop.
  • If you do not include a condition statement in the for loop, the loop will loop indefinitely. In contrast, failing to include a condition statement in the while loop will result in a compilation error.
  • The initialization statement in the for loop syntax is only executed once at the beginning of the loop. If the while loop's syntax includes an initialization statement, the initialization statement will be executed each time the loop iterates.
  • The iteration statement in the for loop will run after the body of the for loop. On the contrary, because the iteration statement can be written anywhere in the body of the while loop, there may be some statements that execute after the iteration statement in the body of the while loop is executed.
  • Conclusion

Loops represent a sequence of instructions that need to be executed in a particular sequence. An incorrect loop structure will lead to the display of a syntax error in the program. Loops are executed to achieve an outcome or meet a specific condition or multiple conditions. They form the basis of all coding languages.

During the execution phase, the loop's logic poses a query and continues to run until a satisfactory response is obtained. This repetitive inquiry persists until a new condition is met. The iteration cycle persists endlessly until the program encounters a stopping point. Failure to reach this breakpoint will result in a program failure.

The for and while loops function as conditional statements in programming. A for loop executes a set of commands iteratively within a single line. In contrast, while loops can either be concise with a single line or encompass several commands based on a specific condition.

Both the for loop and the while loop hold significance in programming languages for achieving desired outcomes. The condition is satisfied when the syntax of the command is accurate.

Both the for loop and the while loop are types of iteration statements, each with unique attributes. The for loop encompasses the declaration of initialization, condition, and iteration within the loop body's outset. Conversely, the while loop places only the initialization and condition at the beginning of the loop body, allowing the iteration to be positioned at any point within the loop body.

Input Required

This code uses input(). Please provide values below: