Loops can execute a block of code as long as a specified condition is reached. Loops are handy because they save time, reduce errors, and they make code more readable.
TYPES OF LOOPS
1.WHILE LOOP :Repeats a statement or group of statements until a given condition is true. It testes the condition before executing the loop body.
3 Steps to write while loop:
1)Initialization, 2)Condition check, 3)Increment/Decrement
Syntax :
while (condition)
{
statements
}
2.FOR LOOP :Execute a sequence of statements multiple times and reduce the code that manages the loop variable.
3 Steps to write for loop:
1)Initialization, 2)Condition check, 3)Increment/Decrement
Syntax :
for(initialization; condition check; increment/decrement )
{
statements
}
Flowchart
Example
Question : Print 1 to 10 numbers
3.NESTED FOR LOOP :You can use one or more loops inside the main loop.
Syntax :
for(init; condition check; inc/dec)
{
for(init; condition check; inc/dec)
{
for(init; condition check; inc/dec)
}
}
Example
No comments:
Post a Comment