While and For Loops | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

While and For Loops

"while" and "for" loops look pretty the same for me, doing the same function. Please correct me if they are different

22nd Dec 2016, 1:01 AM
Goshgar Mikayilov
Goshgar Mikayilov - avatar
3 Answers
+ 8
1. while loops - are used when you are unsure of how many times an action should occur (i.e. validaing user input). 2. for loops - are used when you know exactly how many times an action will be repeated (i.e. getting the sum of an int array). Also: 3. do-while loops: are used when you need the action to occur atleast once (similar to while loop). Hope this helps! Gud Luk! -bErN
22nd Dec 2016, 1:07 AM
bernscode
bernscode - avatar
+ 1
They are very similar, but the main difference is that while loops run for an unknown duration whereas for loops the duration is known ahead of time. There is a fundamental difference between, "process the next 10 bytes of data" and "process data until you see a '0'."
22nd Dec 2016, 1:08 AM
Thomas Stone
Thomas Stone - avatar
+ 1
Both while and for loop do the same thing, the difference is their syntaxes and the ways of using them, if you want the loop to execute for a number of times say x you can use for loop. if you want to execute loop till a condition matches use while loop. for example to run loop x times for(int i=0;i<x;i++) { //loop body } you can do the same with while loop but it will add more lines to your code int i =0; while(i<x) { //loop body i++; } Now if you don't know how many times loops will execute or if you want to execute loop till a condition is met you can use while loop as follows: while(true) //forever loop { if(condtion==true) break; //stop the loop if condition is true } now using for loop: for(;;;) { if(condition==true) break; } in this case, both code do the same thing but while loop look clear :)
22nd Dec 2016, 1:20 AM
Ravi Kumar
Ravi Kumar - avatar