Java - 07-u1 - Copy
Java - 07-u1 - Copy
Loop Statements
Prepared By Dr. Muhammad Mazin
--------------------------------------------------------
-------------------------------
References:
1. Java an Introduction to Problem Solving and Programming, Walter Savitch, 7 th ed.
The for Loop
The for loop is controlled by a counter.
For loop keep iterate if the boolean expression is true.
1
2
3
4
5
After the loop a = 6
The while Loop
A while statement repeats its action as long as a controlling boolean expression is
true.
When the expression is false, the repetition ends.
A while loop can perform zero iterations.
int a=1;
while (a<=5)
while (Boolean_Expression) {
System.out.println(a);
{
a++;
Statements }
. . . System.out.println("After the loop a = "+a);
}
1
2
3
4
5
After the loop a = 6
The do-while Loop
A do-while loop repeats its body while a boolean expression is true.
The loop body executes at least one time (before checking the boolean expression).
A while statement repeats its action as long as a controlling boolean expression is
true.
If the boolean expression is false, theint a=1;
loop ends.
do
{
do System.out.println(a);
a++;
{ } while (a<=5);
Statements System.out.println("After the loop a = "+a);
. . .
1
} while (Boolean_Expression); 2
3
4
5
After the loop a = 6
Choosing the suitable loop statement
Use for loop If you know the starting point, the step, the ending point (for example
adding the even numbers from 1 to 10).
Use while loop or do-while loop if you know the starting point and the ending point
but you don’t know how many steps it will take you to reach the end.
The while will be more suitable if you need to apply the creature before entering
the loop (for example keep elevator door open in the sensor detect a person).
The do wile will be more suitable if you need to execute the statement at least for
one time (for example if want to find the summation of numbers that you get from
user and the sequence ends by the number 0).
Infinite Loop
A loop that iterates its body repeatedly without ending is called an infinite loop.
This is caused usually by some a statement in the body of the loop that will prevent the
loop from exiting.
Some infinite loops will not really run forever if left alone, others will end your program
when some system resource is exhausted.
On many systems —but not all— you can stop program execution by typing control-C,
which you do by holding down the control (Ctrl) key while pressing the C key.
For with Comma Operator
There will be times when we will want to include more than one statement in the
initialization and iteration sections of the For loop. For example:
int i,j; 1 20
for(i=1,j=20;j>=10;i++,j-=2) 2 18
{ 3 16
System.out.println(i+" "+j); 4 14
} 5 12
6 10
Exercise
Get the value of the positive integer x from the user and find the summation of the odd numbers
between 0 and x, x should not be included.
int x,i,s; int x,i,s;
System.out.println("Enter a pos. int."); System.out.println("Enter a pos. int.");
x= k.nextInt(); x= k.nextInt();
s=0; s=0;
for (i=1;i<x;i+=2) i=1;
s+=i; do
System.out.println("Sum = " + s); {
s+=i;
int x,i,s; i+=2;
System.out.println("Enter a pos. int."); }while (i<x);
x= k.nextInt(); System.out.println("Sum = " + s);
s=0;
i=1;
while (i<x)
{
s+=i; Enter a pos. int.
i+=2; 15
} Sum = 49
System.out.println("Sum = " + s);
Exercise
Change the previous example and make sure that the user enter a positive integer, show the
message "Wrong value, try again." if the user entered non integer or a negative value.
double x; Enter a positive integer
boolean not_valid; -9
int i,s; Wrong value, try again.
56.3
System.out.println("Enter a positive integer");
do { Wrong value, try again.
x= k.nextDouble(); -5.2
not_valid=(x<0)||(x!=(int)(x)); Wrong value, try again.
if (not_valid) -8
System.out.println("Wrong Value, Try again."); Wrong value, try again.
}while (not_valid); 5
Sum = 4
s=0;
for (i=1;i<x;i+=2)
s+=i;
System.out.println("Sum = " + s);
Exercise
Change the previous example and make sure that the user enter a positive integer, show the message "Wrong value, try
again." if the user entered non integer or a negative value.
s=0;
for (i=1;i<x;i+=2)
s+=i;
System.out.println("Sum = " + s);
Extra Semicolon in a Loop Statement
The following code looks quite ordinary, it will compile and run with no error messages.
int product = 1, number;
for (number = 1; number <= 10; number++);
{
product = product * number;
}
The output for this code will be 11.
The problem is that the for statement has an extra semicolon at the end of the first line.
This for statement with the extra semicolon is equivalent to:
for (number = 1; number <= 10; number++)
{
//Do nothing.
}
{
product = product * number;
}
Extra Semicolon in a Loop Statement
Code snippet Output
int n;
for (n = 1; n <= 4; n++) 1 2 3 4
System.out.print(n + " ");
for (int n = 1; n <= 4; n++)
1 2 3 4
System.out.println(n + " ");
for (double test = 1; test < 3; test = test + 0.5)
1.0 1.5 2.0 2.5
System.out.println(test + " ");
for (int n = 10; n >= 6; n--)
10 9 8 7 6
System.out.print(n + " ");
for (int n = 1; n <70; n*=2)
1 2 4 8 16 32 64
System.out.print(n + " ");
int i=1;
while(i<5);
{
Infinite loop
System.out.print(i + " ");
i--;
}
Extra Semicolon in a Loop Statement
Code snippet Output
int n;
for (n = 1; n <= 4; n++){
System.out.print(n + " "); Infinite loop
n-=2;
}
for (int n = 1, n <= 4, n++)
System.out.print(n + " "); Compiler error
System.out.println(n);
int i=1;
while(int i<5){
Compiler error
System.out.print(i + " ");
}
double i=0.5
while(i!=5);
{
Infinite loop
System.out.print(i + " ");
i++;
}
Extra Semicolon in a Loop Statement
Code snippet Output
int i=1,j;
while(i<5) {
int j=10;
10 20 30 40
System.out.print((i*j) + " ");
i++;
}
Exercise
Blood sugar rate is considered to be: int s, c=0 ;
double h=0,l=0,n=0;
normal if it is less than 140 and greater System.out.println(" Enter Blood Sugar, to stop enter -1");
than 70. do {
high if it is greater than or equal to 140. s=k.nextInt();
if ((s>0)==(s<=70))
low if it is less than or equal to 70. l++;
Write a Java program that asks the user to else if (s>=140)
input the rate of blood sugar of each patient h++;
in a hospital (-1 to indicate the end of the else if (s>0)
n++;
data.) The program should calculate and
c++;
print the percentage of patients with normal
}while(s!=-1);
blood sugar, percentage of patients with high c--;
blood sugar, percentage of patients with low n=n/c*100;
blood sugar, and the total number of h=h/c*100;
patients entered by the user. l=l/c*100;
Enter Blood Sugar, to stop enter -1 System.out.println("High: "+ h +"%\nNormal: "+ n +"%\nLow: "
70 110 120 240 -1
High: 25.0% + l + "%\nNumber of Patents: " + c);
Normal: 50.0%
Low: 25.0%
Number of Patents: 4
Exercise
Write a Java program that asks the user to input a line of characters from the keyboard. Your
program should count the number of alphabets (a–z, A–Z) and the number of non-alphabets
(i.e digits, special characters, spaces, tabs, etc.) in the given input.
char c;
int i,a=0, n=0;
System.out.println("Enter a line of text:");
s= k.nextLine();
for (i=0;i<s.length();i++) {
c = s.charAt(i);
if (((c >= 'a') && (c <= 'z'))||((c >= 'A') && (c <= 'Z')))
a++;
else
n++;
}
System.out.println("Alphabets count: "+ a +"\n Non-alphabets count:" +
n);
Enter a line of text:
CSC 113!..
Alphabets count: 3
Non-alphabets count:7
Exercise
Write a Java program using a int d,f,i;
LOOP to print the date of all System.out.print("Enter number of days in the month:");
Sundays in a month, if the d= k.nextInt();
date of the first Sunday is System.out.print("Enter the date of first Sunday:");
given. First prompt the user f= k.nextInt();
to input the number of days System.out.print("The Sunday will be on: ");
in the month, then prompt for (i=f;i<d;i+=7)
the user to input the date of System.out.print(i + ", ");
the first Sunday in that
month. After that find all
Sundays in the given month
and output. Assume all
inputs are valid. Your
program must follow the
given
EnterSample
numberInput/Output.
of days in the month: 29
Enter the date of first Sunday: 2
The Sunday will be on: 2, 9, 16, 23,
Exercise
Write a program that reads a Scanner k = new Scanner(System.in);
positive integer number of int i, x, s, c, d=0;
any digit size and do the double av;
System.out.println("Enter a number:");
following:
x = k.nextInt();
(a) Print the sum of its digits. if (x<0)
x=-x;
(b) Print the average of its
s = 0;
digits. c = 0;
(c) Print the leftmost digit. while (x > 0) {
d = x % 10;
If the input number is x /= 10;
negative, convert it to
Enter a number: s += d;
8261
positive. c++;
Sum of digits: 17
}
Average of digits: 4.25
Left Most Digit: 8 av= s/(double)c;
System.out.println("Sum of digits: " + s + "\nAverage of digits: "
+ av + "\nLeft Most Digit: " + d);
Exercise
Write a Java program that read int i, x, max;
the marks for 5 students and System.out.println("Enter the grades of 5 students:");
find the maximum grade max=-1; // initialize with a vale that is less than
knowing that the grades // any possible value
ranges between 0 and 100. for(i=1;i<=5;i++)
{
System.out.print("enter Student " + i + " grade: ");
x= k.nextInt();
if (max<x)
max=x;
}
Enter the grades of 5 students: System.out.println("\nThe Maximum Grade is : " + max);
enter Student 1 grade: 40
enter Student 2 grade: 80
enter Student 3 grade: 70
enter Student 4 grade: 80
enter Student 5 grade: 60
Display how many students have scholarships and how many students registered for the ENGLISH class.
1*1=1
int i,j; 1*2=2
for (i=1;i<4;i++) 1*3=3
{ 2*1=2
for (j = 1; j < 4; j++) 2*2=4
{ 2*3=6
System.out.println(i+"*"+j+"="+i*j); 3*1=3
} 3*2=6
} 3*3=9
The break and continue Statement in Loops
So far, the loops (while, do-while, and for) always exit when their controlling
boolean expression becomes false.
The break statement can force the loop to exit “if required”.
A break statement ends the enclosing loop and the remainder of the loop
body does not execute.
The break statement ends only the innermost loop or switch statement that
contains the break statement.
A continue statement within the body of a loop ends its current iteration and
begins the next one.
The continue and break statements can and should be avoided in a loop.
Examples
1
int i; int i, j;
1 2
for (i=1;i<=10;i++) for (i = 1; i <= 8; i++) {
1 2 3
{ for (j = 1; j <= i; j++) {
1 2 3 4
System.out.print(i+", "); System.out.print(j + " ");
1 2 3 4 5
} }
1 2 3 4 5 6
System.out.print("\n i="+i); System.out.print("\n");
1 2 3 4 5 6 7
}
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1 2 3 4 5 6 7 8
i=11
int i; for (i = 1; i <= 8; i++) { 1
for (i=1;i<=10;i++) for (j = 1; j <= i; j++) { 1 2
{ System.out.print(j + " "); 1 2 3
System.out.print(i+", "); if (j>=4) 1 2 3 4
if (i==5) break; 1 2 3 4
break; } 1 2 3 4
} System.out.print("\n"); 1 2 3 4
System.out.print("\n i="+i); } 1 2 3 4
1, 2, 3, 4, 5,
i=5
Examples
int i, j; 1
for (i = 1; i <= 8; i++) { 1 2
for (j = 1; j <= i; j++) { 1 2 3
System.out.print(j + " "); 1
if (i>=4) 1
break; 1
} 1
System.out.print("\n"); 1
}
int i, j;
for (i = 1; i <= 8; i++) {
for (j = 1; j <= i; j++) {
System.out.print(j + " "); 1
} 1 2
System.out.print("\n"); 1 2 3
if (i>=4) 1 2 3 4
break;
}
Examples
1
int i, j;
2 4
for (i = 1; i <= 8; i++) {
3 6 9
for (j = 1; j <= i; j++) {
4 8 12 16
System.out.print(i*j + " ");
5 10 15 20 25
}
6 12 18 24 30 36
System.out.print("\n");
7 14 21 28 35 42 49
}
8 16 24 32 40 48 56 64
int i, j;
1
for (i = 1; i <= 8; i++) {
2 4
for (j = 1; j <= i; j++) {
3 6 9
System.out.print(i*j + " ");
4 8 12 16
if (i*j>=20)
5 10 15 20
break;
6 12 18 24
}
7 14 21
System.out.print("\n");
8 16 24
}
Exercise
Blood sugar rate is considered to be: Scanner k = new Scanner(System.in);
normal if it is less than 140 and greater than 70. int s, c = 0;
high if it is greater than or equal to 140. double h = 0, l = 0, n = 0;
System.out.println("Enter Blood Sugar for 10
low if it is less than or equal to 70.
patents, to stop before 10
Write a Java program that asks the user to input the rate enter a negative value");
of blood sugar of each patient in a hospital. The program do {
should: s = k.nextInt();
Calculate and print the percentage of patients with if (s<0)
normal, High and Low blood sugar break;
Display the total number of patients entered by the if ((s > 0) == (s <= 70))
l++;
user. else if (s >= 140)
The program will stop when the user enter 10 different h++;
Enter
valuesBlood Sugar
or when for
the 10 enters
user patents, to stop value.
a negative before 10 else if (s > 0)
enter
Use
a negative value
break system in your solution. n++;
140
c++;
160
} while (c < 10);
120
80
n = n / c * 100;
-12 h = h / c * 100;
High: 50.0% l = l / c * 100;
Normal: 50.0% System.out.println("High: "+ h +"%\nNormal: " +
Low: 0.0% n +"%\nLow: "+ l +
Number of Patents: 4 "%\nNumber of Patents: " + c);
Examples
int i;
for (i=1;i<=8;i++){
System.out.print(i+", ");
}
System.out.print("\nAfter exitting the loop i = " + i);
1, 2, 3, 4, 5, 6, 7, 8,
After exiting the loop i = 9
int i;
for (i=1;i<=8;i++){
if (i>4)
continue;
System.out.print(i+", ");
}
System.out.print("\nAfter exitting the loop i = " + i);
1, 2, 3, 4,
After exiting the loop i = 9
Examples
int i, s=0;
for (i=1;i<=8;i++)
{
System.out.print(i+", ");
if (i>4)
continue;
s+=i;
}
System.out.print("\nAfter exiting the loop i = " + i);
System.out.print("\ns = " + s);
1, 2, 3, 4, 5, 6, 7, 8,
After exiting the loop i = 9
s = 10
Exercise
Blood sugar rate is considered to be:
normal if it is less than 140 and greater than 70. Scanner k = new Scanner(System.in);
high if it is greater than or equal to 140. int s, c = 0;
low if it is less than or equal to 70. double h = 0, l = 0, n = 0;
Write a Java program that asks the user to input the rate of blood System.out.println("Enter a valid Blood Sugar
sugar of each patient in a hospital. The program should: for 5 patents");
Calculate and print the percentage of patients with normal, High do {
and Low blood sugar s = k.nextInt();
The program will stop when the user enter 10 different. if ((s<20)||(s>200))
The program should ignore any value that is greater than 200 or continue;
less than 20. if ((s > 0) == (s <= 70))
Use continue system in your solution. l++;
else if (s >= 140)
Enter a valid Blood Sugar for 5 patents h++;
140 else if (s > 0)
-90 n++;
300 c++;
10 } while (c < 10);
80 n = n / c * 100;
110 h = h / c * 100;
90
l = l / c * 100;
120
System.out.println("High: " + h + "%\nNormal: "
High: 20.0%
Normal: 80.0% + n + "%\nLow: " + l );
Low: 0.0%
Exercises
Develop an algorithm for a simple
game of guessing at a secret four-digit Enter your guess for attempt 1: 4342
code. When the user enters a guess The number of correct digits guessed is 2
at the code, the program returns two and the sum of the digits is 8
values: Enter your guess for attempt 2: 4145
the number of digits in the guess The number of correct digits guessed is 3
and the sum of the digits is 9
that are in the correct position
the sum of those digits. For Enter your guess for attempt 3: 4147
The number of correct digits guessed is 3
example
and the sum of the digits is 9
Allow the user to guess a five times
only. Enter your guess for attempt 4: 4146