0% found this document useful (0 votes)
5 views

Lecture 6 Loops in Java

Loops in Java

Uploaded by

mwaslam2303
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lecture 6 Loops in Java

Loops in Java

Uploaded by

mwaslam2303
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

7/18/2020

IN2203

Fundamentals of
Programming (Java)

Instructor
Dr. Muhammad Waqar
[email protected]

Iteration Statements (Loops)


• A loop repeatedly executes the same set of instructions until a termination
condition is met. Tests
• Suppose that you need to display a string (e.g., Welcome to Java!) a hundred
times. It would be tedious to have to write the following statement a
hundred times:

• System.out.println("Welcome to Java!");
• System.out.println("Welcome to Java!");
• ...
• System.out.println("Welcome to Java!");

1
7/18/2020

The While Loop


• A while loop executes statements repeatedly while the condition is true.
• The syntax for the while loop is:
Tests

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.

The While Loop


• Each loop contains a loop-continuation-condition, a Boolean expression that
controls the execution of the body.
Tests
• The condition can be any Boolean expression.

• This condition is evaluated each time to determine if the loop body is


executed.

• 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

The While Loop Example


int count = 0; // variable initialization
while (count < 100) { // checking condition
Tests
System.out.printIn("Welcome to Java!"); // loop body
count++; // incrementing count
}

This Loops will print “Welcome to Java!” 100 times.

Another While Loop Example


int sum = 0, i = 1;
while (i < 10) { Tests
sum = sum + i;
i++;
}
System.out.println("sum is " + sum);

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;
}

• Make sure that the loop-continuation-condition eventually becomes false so


that the loop will terminate. If your program takes an unusually long time to
run and does not stop, it may have an infinite loop. If you are running the
program from the command window, press CTRL+C to stop it. If you are using
NetBeans use a stop sign on left side of output window.

Loop Design Strategy


Writing a correct loop is not an easy task for novice programmers. Consider three steps
when writing a loop.

Step 1: Identify the statements that need to be repeated.


Tests
Step 2: Wrap these statements in a loop like this:
while (true) {
Statements;
}

Step 3: Code the loop-continuation-condition and add appropriate statements for


controlling the loop.
while (loop-continuation-condition) {
Statements;
Additional statements for controlling the loop;
}

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

Guess a number problem


• Write a program which generates a random number between 1 and 10. It
asks the user to guess this number. If the answer is right, It should display
that you have guessed in these many attempts.
Tests

• 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.

• Use while loop to iteratively run the program.

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

The for loop


• The for loop statement starts with the keyword for, followed by a pair of
parentheses enclosing the control structure of the loop.
• This structure consists of initial-action,Tests
loop-continuation-condition, and
action-after-each-iteration.
• The control structure is followed by the loop body enclosed inside braces.
• The initial-action, loop continuation- condition, and action-after-each-
iteration are separated by semicolons.

for (initial-action; loop-continuation-condition; action-after-each-iteration) {


// Loop body;
}

20

10
7/18/2020

21

The for loop example


• The following loop prints “Welcome to Java!” 100 times.

Tests
for (int i = 0; i < 100; i++) {
System.out.println("Welcome to Java!");
}

• initial-action: int i=0;


• loop-continuation-condition: i<100
• action-after-each-iteration: i++

21

22

More on for loop


• The initial-action in a for loop can be a list of zero or more comma-separated
variable declaration statements or assignment expressions. For example:
Tests
for (int i = 0, j = 0; i + j < 10; i++, j++) {
// Do something
}

• 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

The following for loop sums up numbers from 0 to 1000.


Tests

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

Which loop to use?


• You can use a for loop, a while loop, or a do-while loop, whichever is
convenient.
• The while loop and for loop are called pretest loops because the
continuation condition is checked before Tests
the loop body is executed.
• The do-while loop is called a posttest loop because the condition is checked
after the loop body is executed.
• The three forms of loop statements—while, do-while, and for—are
expressively equivalent and you can write a loop in any of these three forms.
• Use the loop statement that is most intuitive and comfortable for you.
• In general, a for loop may be used if the number of repetitions is known in
advance, as, for example, when you need to display a message a hundred
times.
• A while loop may be used if the number of repetitions is not fixed, as in the
case of reading the numbers until the input is 0.

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

Practice problem code


class Nested {
public static void main(String args[]) {
int i, j;
for(i=1; i<=5; i++) {
for(j=1; j<=i; j++)
System.out.print(“*");
System.out.println();
} } }

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

Home Work problem


• Write a program which gives the following output

*
***
*****
***
*

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

Jump Statements (break and continue)

• 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

Example of break statement


// Using break to exit a loop.
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}

34

17
7/18/2020

35

break inside nested loops


• When used inside a set of nested loops, the break statement will only break out of
the innermost loop
class BreakLoop3 {
public static void main(String args[]) {
for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");
for(int j=0; j<100; j++) {
if(j == 10) break; // terminate loop if j is 10
System.out.print(j + " ");
}
System.out.println();
}
System.out.println("Loops complete.");
}}

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

Example of continue statement


class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}
}

37

38

continue to a specific label


Continue may specify a label to describe which enclosing loop to continue. Here is an
example program that uses continue to print a triangular multiplication table for 0
through 9.
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i) {
System.out.println();
continue outer; }
System.out.print(" " + (i * j));
}
}
System.out.println();
}}

38

19
7/18/2020

39

Practice problem: Checking Palindrome


• A string is a palindrome if it reads the same forward and backward.
• The words “mom,” “dad,” and “noon,” for instance, are all palindromes.
• The problem is to write a program that prompts the user to enter a string and
reports whether the string is a palindrome.

39

40

Practice problem code (Part I)


import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = input.nextLine();
int low = 0; // The index of the first character in the string
int high = s.length() - 1; // The index of the last character in
// the string
boolean isPalindrome = true;

40

20
7/18/2020

41

Practice problem code (Part II)


while (low < high) {
if (s.charAt(low) != s.charAt(high)) {
isPalindrome = false;
break;}
low++;
high--;
}
if (isPalindrome)
System.out.println(s + " is a palindrome");
else
System.out.println(s + " is not a palindrome");
}}

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

Home Work Problems


1) Ask the user to enter a number and count the number of positive numbers, negative
numbers and zeros entered by the user. The program should ask user after every number
do you want to enter another number? And should continue if user enters ‘y’ or ‘Y’.
(while and for loop)
2) Print multiplication tables from 1 to 10 using nested for loops. (for and for loop)
3) Convert a table of pound to Kgs from 1 to user defined value and ask user do you want to
print another table? ( while and for loop)
4) Ask student name and students marks to user defined number of students and display
the student name with highest marks. (You can use arrays) (for loop)
5) Ask user a number and calculate its factorial and ask user do you want to calculate
factorial of another number? (while and for loop)
6) Find factors of a user defined number, display its factors and ask user do you want to
calculate factors of another number? (while and for loop)

43

Thank You

44

22

You might also like