I m confused with the concept of for loop and while loop . | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

I m confused with the concept of for loop and while loop .

what is the major difference between them? (because I think both can perform same functionality; we can also use for loop on the basis of user input (likewise while) and we can also perform the mathematical functions with while . so what is major difference I m confused 😣😧)

9th Jun 2016, 5:23 AM
sorath Peetamber
sorath Peetamber - avatar
6 Answers
+ 5
These are both looping structures and both can be used to perform loops. The for loop is more convenient when you know how many iterations you will have, and provide that information right in the for components, like: for(i=0;i<10;i++) - here you define all the conditions for your loop, how many times it will run and the increment operation. In a while loop you have to define the increment operation within the body, for example: i=0; while(i<10) { //some code i++; } So, basically, both can be used to achieve the same results. You have to use whichever makes the logic of your program more understandable on a case-by-case basis. Hope this helps!
9th Jun 2016, 9:49 AM
James Flanders
+ 2
James Flanders is right. might I also add to wath he said that not only you can control how many iterations you will do with a for loop more straight forward but you can also control by what amout at each time. Now, you can also do that using a while loop but is more lines of code; less straight forward.
10th Jun 2016, 11:18 AM
Israel
Israel - avatar
+ 1
However you can also use a While loop to keep checking for a condition to be true or false. for example, for a page expecting user input you could say "while" there is no input keep checking, then when there is input the program will exit the while loop. So while can have other uses than just replacing a for loop. it's useful for when you DON'T know when the "condition" will become true or false (whichever you are looking for), for example.
20th Jun 2016, 3:08 AM
DevCoder (John Sullivan)
DevCoder (John Sullivan) - avatar
0
I m also
9th Jun 2016, 7:47 AM
tushar khorwal
tushar khorwal - avatar
0
To be more clear, in for loop the iterations will be known. Whereas in while we cannot judge.
14th Jun 2016, 6:41 PM
Naveen
- 1
difference between them is just a syntax.
9th Jun 2016, 8:08 PM
Arsalan MuhammadHussain
Arsalan MuhammadHussain - avatar