Lecture 7 - Loops
Lecture 7 - Loops
Lecture 7 - Loops
Loops
Pre-Requisites
Basic syntax of Java
Variables
Operators
Conditionals
Here, once the loop begins, end will drive start and start will drive end until certain condition to break out of loop
is encountered.
Now that we have understood the simple meaning of loop, let us now move to the computer programming
terms.
In computer programming, a loop is a sequence of instructions continually repeated until a certain condition is
reached.
Yes, that’s where the concept of loops comes in. Loops help you perform a task repeatedly until a certain
condition is met. In our example, the task would be to print the value of the number, and the till it is less than
10000.
Syntax
while (condition)
statement;
Let us understand the working of while loop with the help of this simple example -
To accomplish this-
We declare a variable ‘i’ which denotes the current number. We initialize it with the value 1 (as you already
know, the first natural number).
In the while loop, we put a condition that makes the loop run till the value of the variable i doesn’t exceed 10.
Finally, we print the value of the variable ‘i’ and then increment it by 1.
Code
int i = 1;
while (i ≤ 10) {
System.out.print(i + “ “);
i = i + 1;
Output - 1 2 3 4 5 6 7 8 9 10
For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
The advantage of a for loop is we know exactly how many times the loop will execute even before the actual
loop starts executing.
Unlike while loop, in for loop we have 3 parts in the for header.
Syntax:
statement
Init-statement: This statement is used to initialize or assign a starting value to a variable which may be altered
over the course of the loop (we will see this while solving examples). It is used/referred only once at the start of
the loop.
Condition: This condition serves as a loop control statement. The loop block is executed until the condition
evaluates to true.
Final expression: It is evaluated after each iteration of the loop. It is generally to update the values of the loop
variables.
Now that we know the use of each of these, let's understand it with an actual loop.
System.out.print(index + “ “);
Output - 0 1 2 3 4
Here
Init-statement is executed only once at the start of the loop. In this example, index variable is defined and
initialized to 0.
Next, the condition is evaluated. If index is not equal to 5, the for body is executed. Otherwise, the loop
terminates. If the condition is false in the first iteration itself, 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 (the print
statement).
Finally, the final-expression is evaluated. In this example, index is incremented by 1.
In a ‘for’ loop, we can omit any (or all) of init-statement, condition and final-expression.
1. We can omit the init-statement when an initialization is unnecessary. This may be the case when the
Example-
int index = 0;
System.out.println(index);
Note that the semicolon is necessary to indicate the absence of init-statement—more precisely, the
2. Omitting the condition is equivalent to 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 or infinite loop which is a nightmare for
Example-
3. We can also omit final expression. In such loops, either the condition or the body must do something to
advance the iteration, otherwise the loop will not run any further owing to lack of information.
Example-
System.out.println(index);
index = index + 1;
Note
The above statements can all be omitted together too.
We can also have multiple statements inside the loop.
Here, you may see that we are handling two variables, conditions wrt both and final expression, all in one for
loop.
Code
System.out.println(i + “ “);
Output - 1 2 3 4 5 6 7 8 9 10
2. 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.
The simple answer to this is your own judgement and choice. 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( we will learn about arrays in the forth-
coming class).
Use a for loop when you know that loop needs to run ‘n’ number of times.
Whereas,
1. Use a while loop when the termination condition is taking too much time to be checked or the termination
2. Use a while loop when increment condition is non standard like i=i*2.
3. Use a while loop when you are unsure till when the loop will continue, like while finding the first number
Let us move to the next looping statement which is seldom used and is a variation of while loop.
Syntax
do
statement;
} while (condition);
do
System.out.print(idx + “ ”);
Output- 15
Explanation- In the above example, when we enter the loop, there will be no condition check. Therefore, we get
15 printed because of the system.out.println() statement inside the loop. However, in the next iteration, the
program goes through the condition check mentioned in the while part. This time it will fail and the loop
execution will end.
Let us now look at this example, can you guess the output?
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
Explanation- Did you notice the difference in output ?Without the break statement, the inner loop is executed 3
times for each iteration of i. However, after the break statement is added to the condition that ‘i’ equals ‘j’, the
inner loop is terminated whenever this condition is true.
Try these
Print the first multiple of 5 which is also a multiple of 7.
Tell if the number in the input is prime or not.
Code
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 skipping the printing statement of
printing 3.
Try these
Print all values between 1 and 100, except if it’s a multiple of 3.
Print all factors of the number in the input.
first:
if(i == 1 && j == 1)
continue first;
Output
0 0
0 1
0 2
1 0
2 0
2 1
2 2
Here, as soon as we reach the continue statement, unlike normal scenarios, the control moves to the next
iteration of the outer loop that is labeled as “first”.
second:
if(i == 1 && j == 1)
break second;
Output
0 0
0 1
0 2
1 0
Explanation
Here, as soon as we reach the break statement, unlike normal scenarios, the control breaks out of the outer
loop that we labeled as “second”.