Lecture 6 Loops in Java
Lecture 6 Loops in Java
IN2203
Fundamentals of
Programming (Java)
Instructor
Dr. Muhammad Waqar
[email protected]
• System.out.println("Welcome to Java!");
• System.out.println("Welcome to Java!");
• ...
• System.out.println("Welcome to Java!");
1
7/18/2020
while (loop-continuation-condition) {
// Loop body
}
• The part of the loop that contains the statements to be repeated is called the
loop body.
• A one-time execution of a loop body is referred to as an iteration (or
repetition) of the loop.
• If its evaluation is true, the loop body is executed; if its evaluation is false, the
entire loop terminates and the program control turns to the statement that
follows the while loop.
• The curly braces are unnecessary if only a single statement is being repeated.
2
7/18/2020
This while loop sums ups numbers from 1 to 10 and prints result.
3
7/18/2020
A common mistake
• A common mistake using loops is to use a boolean condition which is always
true and the loops runs forever. For example the following code runs forever
Tests
int sum = 0, i = 1;
while (i < 10) {
sum = sum + i;
}
4
7/18/2020
Simple Problem
Write a while loop which keeps on printing “Hello” as long as user enters ‘y’ or
“Y” and exits program printing “bye” if user enters anything else
Tests
10
Code
public static void main(String args[]) {
Tests
Scanner input = new Scanner(System.in);
String s1 = "y";
while (s1.equals("y")){
System.out.println("Hello");
System.out.println("Do you want to print hello again?.");
s1 = input.nextLine();
s1 =s1.toLowerCase();
}
}
10
5
7/18/2020
11
Practice Problem
• Please write a program which prints number from 0 to 4 using while loop.
The output should be
• Count = 1
• Count = 2
• Count = 3
• Count = 4
• Count = 5
11
12
Practice problem
• Please write a program using while which prints even numbers from 0 to
20
• 0
• 2
• 4
• 6
• 8
• .
• .
• .
• 20
12
6
7/18/2020
13
Practice Problem
Write a program which calculates sum of the numbers entered by user.
Specifications:
Tests
1- Please ask user to enter a number to get sum and enter 0 to end the
program.
2- Keep asking user to enter more numbers and keep calculating sum until user
enters 0.
3- When user enters 0, print the sum and exit the program.
13
14
Code
public static void main(String args[]) {
System.out.println("This program sum the numbers entered by user.");
Scanner input = new Scanner(System.in);
int count = 0; Tests
int check = 0;
int sum =0;
while (check == 0){
System.out.println("Please enter a number to sum or enter 0 to exit.");
int number = input.nextInt();
if (number!=0){
sum += number;
count++;}
else
check =1;}
System.out.println("The sum of " + count + " numbers is " + sum);
}
14
7
7/18/2020
15
do while Loop
• A do-while loop is the same as a while loop except that it executes the loop
body first and then checks the loop continuation condition.
• The do-while loop is a variation of the while loop. Its syntax is:
Tests
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
15
16
do while Loop
• If the conditional expression controlling a while loop is initially false, then the
body of the loop will not be executed at all.
• Sometimes it is desirable to execute the Tests
body of a loop at least once, even if
the conditional expression is false to begin with.
• In other words, there are times when you would like to test the termination
expression at the end of the loop rather than at the beginning. A loop that
does just that is the do-while.
• The do-while loop always executes its body at least once, because its
conditional expression is at the bottom of the loop.
• You can write a loop using either the while loop or the do-while loop.
Sometimes one is a more convenient choice than the other.
16
8
7/18/2020
17
Example of do while
This programs calculates sum of numbers entered by user and exits if 0 is
entered by user.
Tests
int data;
int sum = 0;
Scanner input = new Scanner(System.in);
do {
System.out.print("Enter an integer (the input ends if it is 0): ");
data = input.nextInt();
sum += data;
} while (data != 0);
System.out.println("The sum is " + sum);
17
18
• If the answer is wrong, it should tell the user that your answer is wrong.
Please try again.
• If the user does not answer right in 5 attempts then it should exit the
program and should tell the user that you have lost and should display the
random number.
18
9
7/18/2020
19
Code
System.out.println("This is guess the number problem. \n Computer will generate a number between 1 and 10 and you
will have to guess ");
Scanner input = new Scanner(System.in);
int number = 1 + (int)(Math.random() * 10); Tests
int count = 1;
while (count < 6) {
System.out.print("Please guess a number between 1 and 10: ");
int guess = input.nextInt();
if (guess == number ){
System.out.println("You have guessed right in "+ count + " attempts.");
break;}
else{
System.out.println("You have guessed wrong. You have "+ (5-count) + " attempts left.");
count++;}
}
System.out.println("The random number was: " + number);
19
20
20
10
7/18/2020
21
Tests
for (int i = 0; i < 100; i++) {
System.out.println("Welcome to Java!");
}
21
22
• The conditional expression does not always need to involve declared variable
boolean done = false;
for(int i=1; !done; i++) {
// ...
if(interrupted()) done = true;
}
22
11
7/18/2020
23
Another Example
long sum = 0;
for (int i = 0; i <= 1000; i++)
sum = sum + i;
System.out.println(“Sum is: “ + sum);
If there are no {} after for loop then only one statement after for is executed.
23
24
24
12
7/18/2020
25
Practice Problem
• Write a program which prints number and square of those number from 1 to
10 using for and while loop. A sample output is shown below
Tests
25
26
Practice Problem
Write a program using for loop to print the numbers between 1 and 10, along with an
indication of whether the number is even or odd, like this:
1 is odd
2 is even
3 is odd
(Hint: use an if statement to decide if the remainder that results by dividing the
number by 2 is 0. There is a modulus operator %, which can be used to achieve this,
where x%y is equal to the remainder of the first operand (x) divided by the second (y)
).
26
13
7/18/2020
27
Nested loops
• Nested loops consist of an outer loop and one or more inner loops. Each time the
outer loop is repeated, the inner loops are reentered, and started anew.
class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
} } }
27
28
Practice problem
• Write a program which gives the following output. Use nested for loop for your
program
*
**
***
****
*****
28
14
7/18/2020
29
29
30
Practice problem
• Write a program which gives the following output. Use nested for loop for your
program
*
**
***
****
*****
30
15
7/18/2020
31
*
***
*****
***
*
31
32
Practice Problem
Write a program which prints even numbers from 0 to 20 (using for loop) and then
asks user do you want to print again? (using while loop) if user enter ‘y’ or ‘Y’ then
the program must print even numbers from 0 to 20 again and should ask the user
his/her choice again.
32
16
7/18/2020
33
• Java supports three jump statements: break, continue, and return. These
statements transfer control to another part of your program.
• break is used to terminate a statement sequence in a switch statement. It can also
be used to exit a loop.
• By using break, you can force immediate termination of a loop, bypassing the
conditional expression and any remaining code in the body of the loop.
• When a break statement is encountered inside a loop, the loop is terminated and
program control resumes at the next statement following the loop.
33
34
34
17
7/18/2020
35
35
36
continue statement
• Sometimes it is useful to force an early iteration of a loop. That is, you might want
to continue running the loop but stop processing the remainder of the code in its
body for this particular iteration. The continue statement performs such an action.
• In while and do-while loops, a continue statement causes control to be transferred
directly to the conditional expression that controls the loop.
• In a for loop, control goes first to the iteration portion of the for statement and
then to the conditional expression. For all three loops, any intermediate code is
bypassed.
36
18
7/18/2020
37
37
38
38
19
7/18/2020
39
39
40
40
20
7/18/2020
41
41
42
Practice Problem
• An integer greater than 1 is prime if its only positive divisor is 1 or itself. For
example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not.
• The problem is to ask the user to enter a number and print out at output whether
this number is a prime number.
42
21
7/18/2020
43
43
Thank You
44
22