Loops
Loops
What is a Loop?
A loop is like giving instructions to a robot. Instead of telling it to do the same thing over and over, you tell it to
repeat the action until you say stop.
1. Hello
2. Hello
3. Hello
4. Hello
5. Hello
You can simply tell someone, "Say 'Hello' 5 times." That’s a loop! You give the instruction once, and it repeats
the action for you.
In Programming:
Use it when you're not sure how many times to repeat, but you know when to stop.
Example: You keep printing numbers until you reach 5.
see here what you do is first initialize the value of i=1 (i is the loop varaible) then a keyword came
While (jabtak), so this means reapeat whatever code is inside { } these bracket until the value of I become
equal or less than 5.
Here if we see inside currly bracket there is a print condition which prints value of i, so in 1st iteration
the value 1 will be printed then it will encounter a increment operator so the value of i will become 2 for the
second loop iteration
Do-While Loop:
It’s like a "while loop" but guarantees that the code runs at least once.
Example: Print a number, then check if it’s less than or equal to 5.
In this it first do whatever is written is {} then afterwards it check the condition in while
For Loop:
Write a program to calculate the sum of the first 5 natural numbers (1 + 2 + 3 + 4 + 5).
Write a loop to find how many digits are there in a number (e.g., 4567 has 4 digits).
You’re tracking your steps for a week. Write a loop to enter your daily step count and calculate the total
steps for the week.
6.Distributing Flyers
Imagine you have 200 flyers to distribute in your neighborhood. Write a loop to calculate how many
houses you visit until all flyers are distributed, assuming each house takes 2 flyers.
Write a program that keeps asking for the price of items in a cart and adds them until all items are
entered (use 0 as the signal to stop).