2. What is a Loop?
A loop is a way to repeat a set of instructions multiple times in a
program. In simple terms, repeating the same code unless stopped.
It helps avoid writing the same code over and over again.
This is also a kind of loop ^
>> kinds of loops
3. Kinds of Loops :
- For
- While
- Do… while (do-while)
>> what is a for loop?
4. What is a for Loop?
- A for loop is used when you know
how many times you want to
repeat a block of code.
- It's a compact way to repeat
code a specific number of times.
>> syntax and use of for loop
5. for Loop Syntax :
for(initialization; condition; increment/decrement) {
// Code to repeat
}
for Loop Example :
for Loop Output :
>> what is a while loop?
6. What is a while Loop?
- A while loop repeats a block of code as long
as a given condition is true.
- It's useful when you don't know how many
times you need to repeat the code.
>> syntax and use of while loop
7. while Loop Syntax :
while(condition) {
// Code to repeat
}
while Loop Example :
while Loop Output :
>> what is a do-while loop?
8. What is a do-while Loop?
- A do-while loop is similar to a while loop but guarantees
that the code inside the loop runs at least once.
- The condition is checked after the loop has run, not
before.
>> syntax and use of do-while loop
9. do-while Loop Syntax :
do {
// Code to repeat
} while(condition);
do-while Loop Example :
do-while Loop Output :
>> summary
10. If Output* is the same then what is the difference?
Allow me to explain this.
for Loop : Use it when you know exactly how many times the code
needs to run to get the output you want.
while Loop : Use it when you don't know in advance how many times
the code will need to run. This loop keeps going as long as the condition
is true.
do-while Loop : It’s like the while loop but with one key difference — it
always runs at least once because it checks the condition after each
run.
>> that's all!