Loop LP
Loop LP
Loops
List of Concepts Involved:
Introduction to Iterative statements/Loop
The while loo
The for loo
How to choose between while loop and for loop
The do-while loo
Break keywor
Continue keywor
Using labels with continue and break keyword
Syntax
while (condition)
statement;
Example -
Print the first 10 natural numbers.
Java + DSA
To do this-
We declare a variable ‘i’ which denotes the current number. We initialize it with the value 1 (the first natural
number)
In the while loop, we put the condition that runs the loop till the value of the variable i doesn’t exceed 10
Finally in the statement, first we print the value of the variable ‘i’ and then increment it by 1.
Code
int i = 1;
System.out.print(i + “ “);
i = i + 1;
Output -
1 2 3 4 5 6 7 8 9 10
Try this
Print the sum of the first ‘n’ natural numbers using a for loop, where n is the input
Write a short program that prints each number from 1 to 100 on a new line.
For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
Syntax
statement
Init-statement: In general, this statement is used to initialize or assign a starting value to a variable which may
be altered over the course of the loop. It is executed only once at the start.
Condition: Similar to the while condition, it serves as a loop control. The loop block is executed until the
condition evaluates to true.
Java + DSA
Final-expression: It is evaluated after each iteration of the loop. It is generally to update the values of the loop
variables.
Execution flow of for loop:
System.out.print(index + “ “);
Output - 0 1 2 3 4
Init-statement is executed once at the start of the loop. In this example, index is defined and initialized to
zero
Next, the condition is evaluated. If the index is not equal to 5, the for body is executed. Otherwise, the loop
terminates. If the condition is false on the first iteration, then the for body is not executed at all
If the condition is true, the for body executes. In this case, the for body prints the value of index.
Finally, the final-expression is evaluated. In this example, the index is incremented by 1.
These four steps represent the first iteration of the for loop. Step 1 is executed only once on entry to the loop.
Steps 2, 3, and 4 are repeated until the condition evaluates as false i.e. index becomes equal to 5.
Omitting parts of for loop
In a ‘for’ loop, we can omit any (or all) of init-statement, condition and final-expression.
We can omit the init-statement when an initialization is unnecessary. This may be the case when the
variable may have already been declared.
Example-
int index = 0;
System.out.println(index);
Note that the semicolon is necessary to indicate the absence of init-statement more precisely, the
—
Omitting the condition is equivalent to writing setting it as true. Because of this, the for loop must have an
exit statement inside the loop. Otherwise, it may lead to a never ending loop.
Example-
Java + DSA
We can also omit final-expression. In such loops, either the condition or the body must do something to
advance the iteration.
Example-
System.out.println(index);
index = index + 1;
Note -
The above statements can all be omitted together too
We can have multiple statements inside the loop.
Example-
Example-
Print the first 10 natural numbers.
To do this through a for loop-
We declare the int variable ‘i’ the same as before, but this time we do it as a part of for loop
Again we put the condition for i to be less than or equal to 10.
In the for statement we print the value of ‘i’
Finally in the final-expression, we increment the value of the variable ‘i’.
Code
System.out.println(i + “ “);
Output - 1 2 3 4 5 6 7 8 9 10
Try this
Print the sum of the first 10 natural numbers using a for loop
Write a short program that prints each number from 1 to 100 on a new line.
For each multiple of 3, print "Fizz" instead of the number.
For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
Java + DSA
Topic 4: How to choose between while loop and
for loop?
Deciding which loop to use is a judgemental call. Each person has different preferences. However, generally a
while loop is used whenever the total number of iterations to be made is unknown. For example,
Use a for loop when you are traversing a data structure like an array
Use a for loop when you know that loop needs to run ‘n’ number of times.
Whereas,
Use a while loop when increment type is nonstandard like i = i * 2
Use a while loop when you are unsure till when the loop will continue, like while finding the first number
divisible by both 5 and 7.
Syntax
do {
statement;
} while (condition);
Example -
Code
do {
System.out.print(idx + “ ”);
Output- 15
Explanation- In the above example, when we first enter the loop, there will be no condition check.
Consequently, we get 15 as an output. But for entering the loop the next time, we will go through the condition
check. This time it will fail and the loop execution will end.
Java + DSA
Code
do {
System.out.print(idx + “ ”);
idx = idx + 1;
Output- 15 16
Try this
Print the sum of the first 10 natural numbers using do while loop.
System.out.print(j + “ “);
Output- 1 2 3
1 2 3
1 2 3
System.out.print(j + “ “);
if(i == j) break;
Output- 1
1 2
1 2 3
Java + DSA
Explanation- Without the break statement, the inner loop is executed 3 times for each iteration of i. However,
after the break statement is added on the condition that ‘i’ equals ‘j’, the inner loop is terminated whenever the
condition is fulfilled.
Try this
Print the first multiple of 5 which is also a multiple of 7
Tell if the number in the input is prime or not.
if(i == 3) continue;
System.out.print(i + “ “);
Output- 1 2 4 5
Explanation- When the value of i becomes equal to 3, the continue statement makes the loop jump onto the
next iteration, skipping the remainder of the code, which in this case is printing ‘i’.
Try this
Print all values between 1 and 100, except if it’s a multiple of 3
Print all factors of the number in the input.
Java + DSA
first:
continue first;
Output-
0 0
0 1
0 2
1 0
2 0
2 1
2 2
Explanation- As soon as we reach the continue statement, unlike normal scenarios, we move on to the next
iteration of the outer loop that we labeled as “first”.
second:
break second;
Output-
0 0
0 1
0 2
1 0
Explanation- As soon as we reach the break statement, unlike normal scenarios, we break out of the outer loop
that we labeled as “first”.
Java + DSA