0

What is the difference between for loop and while loop?

while lopp

20th Dec 2016, 10:05 AM
Great Srrr
Great Srrr - avatar
4 Answers
+ 1
it's simple, we use for loop when we know before itself the no of repetitions . but while is used when we cannot get exact no of repetitions so we rely on some conditions to get the loop running till the condition holds good. do while is same as of while with just one exception that is, do while gurantee s that ur loop will be done at least once
20th Dec 2016, 12:10 PM
Morpheus
Morpheus - avatar
+ 1
We use for-loop,when we know the number of times the loop is gonna work int numOfTimes=10; for(int i=0;i<numOfTimes;i++) { } We use while loop when we want it to run till some condition has been achived. int x; while(x!=5) { //loop will execute anything till x is not equal to 5(we cant decide how many times it can be.) } do-while will run the code before checking the condition once do{ //this and that }while(x!=5);
20th Dec 2016, 1:58 PM
Doolitha Samaranayake
Doolitha Samaranayake - avatar
0
Firstly, while loop wont execute unless its expression is true. For loop allows you to define a variable and increment or decrement that particular variable but it also has a boolean expression which needs to validate to true for any code within the for loop to be executed. They're both used to repeated a certain task many times or iterate through a collections of items. Use for loop if you know how many times you want to loop, on the other hand use a while loop if you dont know how many times you want to loop for example you could say i want to loop as long as the user doesnt type "exit". Finally there are many cases where you can use both loops for same task but in certain cases its better to keep in mind what i just said above and use the most appropriate.
20th Dec 2016, 11:45 AM
Ousmane Diaw
- 2
I'm not an expert, but for me it seems that the for loop runs until there ITEMS defined in the statement beginning with 'for each' are all dealt with (e. g. for each files in a folder). The do while loop examines a criterion and repeats itself until it turns false.
20th Dec 2016, 10:29 AM
Mikesy MihĂĄly
Mikesy MihĂĄly - avatar