A for loop has three parts: a start, a condition checked before every pass, and a step: for (int i = 1; i <= n; i++) runs with i from 1 to n. A while (condition) loop repeats as long as the condition holds, which suits "until" problems where you do not know the count in advance.
Two mistakes cause most loop bugs. An off-by-one error runs one pass too many or too few: compare < with <= on the last value. And a loop that adds up many values can outgrow int, so pick the type of the running total for the largest answer, not the first one.
A condition that never becomes false loops forever; here the test stops it after its time limit.
A for loop over a known range, and a while loop that runs until a target is reached.