Question:

What is loop? Briefly describe the difference in working of while and for loop.

Show Hint

Use a for loop when the number of iterations is known, and use a while loop when the loop depends on a condition.
Updated On: Mar 14, 2026
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Step 1: Define loop.
A loop is a programming structure used to execute a block of code repeatedly until a specified condition is satisfied.
Loops help reduce code repetition and automate repetitive tasks.
Step 2: Explain while loop.
A while loop executes a block of code repeatedly as long as the specified condition remains true.
Example:
\[ \texttt{while x < 5:} \] \[ \texttt{\ \ print(x)} \] \[ \texttt{\ \ x += 1} \] The loop continues until the condition becomes false.
Step 3: Explain for loop.
A for loop is used when the number of iterations is known beforehand.
It iterates over a sequence such as a list, range, or string.
Example:
\[ \texttt{for i in range(5):} \] \[ \texttt{\ \ print(i)} \] Step 4: Difference between while and for loop.
• While loop runs based on a condition.
• For loop runs for a fixed sequence or number of iterations.
• While loop is suitable when the number of iterations is unknown.
• For loop is suitable when the number of iterations is known.
Step 5: Conclusion.
Thus loops help automate repetitive tasks, and while and for loops differ in the way their iterations are controlled.
Was this answer helpful?
0
0