+ 1
For vs while?
So are for loops basically the same thing as while loops? My understanding is For(int, when itâs this, do this) While(when itâs this){ Do this } Thatâs almost exactly the same thing? So whatâs the point of while loops when for loops exist and vice versa?
2 Answers
+ 1
For loops are incredibly useful to eventually track an index when you want to loop through an entire array:
for (int i=0; i < array.size (); i++)
{
array [i] = 10;
// or any operation you need
}
While loops on the other hand do not track any index, and will just repeat over until the condition of your loop returns false.
0
For loops are really useful if you want to iterate through something and you know exactly how often it'll have to run.
For any other conditions or permanent loops you can use while.
I hope that this was helpful.