Computer Science, asked by dikshajadhav51, 4 months ago

write one difference and one similarity between for loop and while loop in java
Icse Computer Class 10th
I will follow if you give the correct answer and i will mark it brainliest also

Answers

Answered by rishabh9543
1

Answer:

Both for loop and while loop are used to excute one or more lines of code certain number of times. The main differences are as follows.

Syntax:

While loop:

while(condtion) {

//statements to excute.

}

For loop:

for(intialization; condition; Increment or decrement){

// statements to be excuted.

}

There are few variations we can do with for loop.

Such as all three parts of for loop are optional. That means you can also have a loop like this.

for(;;) which is nothing but an infinite loop.

For initialization there can be multiple statements.

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

Similarly for the third component there can be any expression and not necessarily increment or decrement.

for(i =0;i<10;i = i * 2)

Working:

In while loop first of all the condition expression is evaluated and if it is true then the body of the loop is excuted. Then control again evaluate the condition expression. This goes on untill condition becomes false.

In for loop the initialization step is excuted if it is there. It is never excuted again. After this condition expression is evaluated and if it is found true then body of loop is excuted after this control goes to third part i.e. increment or decrement if it is defined. Then again control goes to check the condition again and if found true then body gets excuted and this goes on untill condition becomes false.

Use:

While loop is used in situations where we do not know how many times loop needs to be excuted beforehand.

For loop is used where we already know about the number of times loop needs to be excuted. Typically for a index used in iteration.

Similar questions