While Loop
The while loop is used to repeat a block of code as long as a given condition is true. It’s a fundamental tool for creating loops when the number of iterations isn’t predetermined. Here are some beginner-friendly exercises to practice the while loop.
Practice Problems
Problems Index
- Print numbers from 1 to 10 using a
whileloop. - Calculate the factorial of a given number.
- Input numbers continuously and stop when a negative number is entered. Then, print their sum.
- Print the first
neven numbers. - Reverse the digits of a given number.
- Count the number of digits in an integer.
- Print the Fibonacci series up to
nterms. - Find the greatest common divisor (GCD) of two numbers using repeated subtraction.
- Input marks until a valid score (0–100) is entered, then details it.
- Continuously take input using
while Trueand exit the loop only if “stop” is entered.
Try It Yourself
Now that you’ve reviewed the problems, practice them below using the code runner!
1. Print Numbers
PygroundTry It Out
Print numbers from 1 to 10 using a while loop.
Expected Output:
1 2 3 4 5 6 7 8 9 10
Output:
2. Calculate Factorial
PygroundTry It Out
Calculate the factorial of a given number.
Output:
3. Sum Until Negative
PygroundTry It Out
Input numbers continuously and stop when a negative number is entered. Then, print their sum.
Output:
4. First N Even Numbers
PygroundTry It Out
Print the first n even numbers.
Output:
5. Reverse Digits
PygroundTry It Out
Reverse the digits of a given number.
Output:
6. Count Digits
PygroundTry It Out
Count the number of digits in an integer.
Output:
7. Fibonacci Series
PygroundTry It Out
Print the Fibonacci series up to n terms.
Output:
8. GCD Using Subtraction
PygroundTry It Out
Find the greatest common divisor (GCD) of two numbers using repeated subtraction.
Output:
9. Valid Marks Input
PygroundTry It Out
Input marks until a valid score (0–100) is entered, then details it.
Output:
10. Input Until Stop
PygroundTry It Out
Continuously take input using while True and exit the loop only if 'stop' is entered.
Output:
Last updated on