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

Java - 07-u1 - Copy

The document provides an overview of Java loop statements, including for, while, and do-while loops, along with their syntax and use cases. It also discusses infinite loops, the use of the comma operator in for loops, and includes several exercises to reinforce understanding. Additionally, it highlights common pitfalls such as extra semicolons in loop statements and provides examples for various programming tasks.

Uploaded by

alitooq987
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java - 07-u1 - Copy

The document provides an overview of Java loop statements, including for, while, and do-while loops, along with their syntax and use cases. It also discusses infinite loops, the use of the comma operator in for loops, and includes several exercises to reinforce understanding. Additionally, it highlights common pitfalls such as extra semicolons in loop statements and provides examples for various programming tasks.

Uploaded by

alitooq987
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Java

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.

for (Initializing_Action; Boolean_Expression; Update_Action)


{ int a;
Statements for (a=1;a<=5;a++)
. . . {
System.out.println(a);
} }
System.out.println("After the loop a = "+a);

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.

double x=0; Enter a positive integer


boolean not_valid; -9
int i,s; Wrong value, try again.
56.3
System.out.println("Enter a positive integer");
Wrong value, try again.
not_valid=true; -5.2
while (not_valid) Wrong value, try again.
{ -8
x= k.nextDouble(); Wrong value, try again.
not_valid=(x<0)||(x!=(int)(x)); 5
if (not_valid) Sum = 4
System.out.println("Wrong valur, try again.");
}

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

The Maximum Grade is : 80


Exercise
Write a Java program that read int i, x, min;
the marks for 5 students and System.out.println("Enter the grades of 5 students:");
find the minimum grade min=101; // initialize with a vale that is grater 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 (min>x)
min=x;
Enter the grades of 5 students: }
enter Student 1 grade: 70 System.out.println("\nThe Minimum Grade is : " + min);
enter Student 2 grade: 90
enter Student 3 grade: 48
enter Student 4 grade: 57
enter Student 5 grade: 100

The Minimum Grade is : 48


Exercise
Write a Java program that int i, x, max=77, min=77; // max and min var. can be initialize with
read the balance of 5 // any value just to avoid compiler error
System.out.println("Enter 5 customers balance.");
customers and find both
for(i=1;i<=5;i++)
the maximum balance
{
and the minimum System.out.print("enter customer " + i + " balance: ");
balance, knowing that the x= k.nextInt();
balance might be if (i==1){ // we will assume that the first value represent the
positive or negative. max=x; // solution if that assumption is correct that means
Enter 10 customers balance: min= x; // we reached the solution from the first iteration
enter customer 1 balance: 100
} // if that assumption is wrong then we will reach
enter customer 2 balance: -50
enter customer 3 balance: 300 if (max<x) // the solution in one of the remaining iterations.
enter customer 4 balance: 20 max=x;
enter customer 5 balance: -80 if (min>x)
min=x;
The Maximum balance is : 300
}
The Minimum balance is : -80
System.out.println("\nThe Maximum balance is : " + max);
System.out.println("The Minimum balance is : " + min);
Exercise
Other Solution

int i, x, max=0, min=0;


System.out.println("Enter 5 customers balance.");
for(i=1;i<=5;i++)
{
System.out.print("enter customer " + i + " balance: ");
x= k.nextInt();
if ((max<x)||(i==1))
max=x;
if ((min>x)||(i==1))
min=x;
}
System.out.println("\nThe Maximum balance is : " + max);
System.out.println("The Minimum balance is : " + min);
Exercise
Write a program that asks
int i, n, c=0;
the user to enter the double min=-1.76254978668, s=0, d=0,t;
number of times that they double av;
have run around a System.out.print("How many laps did you run?");
racetrack, and then uses a n = k.nextInt();
loop to prompt them to for(i=1;i<=n;i++)
enter the lap time (in {
minutes) for each of their System.out.print("Enter the time for lap "
laps. When the loop finishes, + i + ": ");
the program should display t= k.nextDouble();
s+=t;
the
How timelaps
many of their
did fastest lap4
you run?
if ((min>t)||(i==1))
and the
Enter theirtime
average lap time.
for lap 1: 4.75
min=t;
Enter the time for lap 2: 5.25
Enter the time for lap 3: 4.5 }
Enter the time for lap 4: 6 av= s/n;
System.out.println("\nThe Average Time is: " + av +
The Average Time is: 5.125 "\nThe fastest Lap time is: " +
The fastest Lap time is: 4.5 min);
int i;

Exercise char g, ming=0;


double w, m=0, f=0, mc=0, minw=0;
System.out.println("Enter student weight and gender for 5 students:");
Write a Java program for(i=1;i<=5;i++)
{
that asks the user to
System.out.print("Student " + i + ": ");
input weight and the
w= k.nextDouble();
gender (M for male, g= k.next().toLowerCase().charAt(0);
F for female) of 5 if (g=='m') {
students and find: m += w; Enter student weight and gender for 5
mc++; students:
 The average wight
} Student 1: 40 f
for boys. else Student 2: 60 m
 The average f += w; Student 3: 55 m
if((minw>w)||(i==1)){ Student 4: 65 m
weight for girls. Student 5: 58 f
minw = w;
 The gender of the ming = g; Av. Weight for boys = 60.0
} Av. Weight for girls = 49.0
student who have
} Minimum Weight is 40.0 that registered by f
the lightest
m = m/mc;
weight.
f = f/(5-mc);
System.out.println("Av. Weight for boys = " + m);
System.out.println("Av. Weight for girls = " + f);
System.out.println("Minimum Weight is " + m + " that registered by "+ ming );
Exercises
To compute the geometric Scanner kbd = new Scanner(System.in);
mean of k values, multiply int n, product=1;
them all together and then double mean;
compute the kth root of the System.out.println("Please enter the number of vales to
find their geometric mean");
value.
n= kbd.nextInt();
For example, the geometric for (int i=1; i<=n; i++){
mean of 2, 5, and 7 is . System.out.println("Please enter number " + i + ":");
Product *=kbd.nextInt();
Hint: Math.pow(x, 1.0/k) will }
compute the kth root of x. mean = (Math.pow(product,1.0/n));
System.out.println("The geometric mean is:" + mean);
Exercise
The admission office of the university is requested to
write a program that reads records for multiple
Please enter the student's first name, GPA, gender,
students. Each record consists of first name (string) to stop write 'stop'
followed by his/her GPA (double) followed by a letter Ahmed 3.1 m
code, either F or M (char). The letter code F is used for Hasan 2.2 m
female students and M for male students. Assume the Hessa 3.3 f
Ahmed 4.0 m
number of records is unknown and the program stops
Fatima 3.9 f
reading when the word ‘stop’ is entered as the student stop
name. Write a program that reads the first name, the The number of students named [Ahmed] is: 2
GPA and the letter code for every student and displays The number of students with GPA > 3.0 is: 4
The name that has maximum GPA is: Ahmad
on screen the following:
The average GPA of female students is: 3.599
(a) The number of students named AHMED. The average GPA of male students is: 3.1

(b) The number of students whom GPAs are above 3.0.


(c) The name that has the maximum GPA.
(d) The average GPA for female and male students
separately.
Exercise
Scanner kbd = new Scanner(System.in);
String FN, maxName="";
double GPA, femaleAVG=0, maleAVG=0, maxGPA=-1;
char gender;
int countAhmed=0, countGPA=0, femaleCount=0, maleCount=0;
System.out.println("Please enter the student's first name, GPA, gender, to stop
write 'stop' ");
do {
FN = kbd.next();
if (!FN.equals("stop")) {
GPA = kbd.nextDouble();
gender = kbd.next().charAt(0);
if (FN.equals("Ahmed"))
countAhmed++;
if (GPA > 3.0)
countGPA++;
if (maxGPA < GPA) {
maxGPA = GPA;
maxName = FN;
}
Exercise
if (gender == 'f') {
femaleCount++;
femaleAVG += GPA;
} else if (gender == 'm') {
maleCount++;
maleAVG += GPA;
}
}while(!FN.equals("stop"));
femaleAVG/=femaleCount;
maleAVG/=maleCount;

System.out.println("The number of students named [Ahmed] is: " + countAhmed);


System.out.println("The number of students with GPA > 3.0 is: " + countGPA);
System.out.println("The name that has maximum GPA is: " + maxName);
System.out.println("The average GPA of female students is: " + femaleAVG);
System.out.println("The average GPA of male students is: " + maleAVG);
Exercise
After graduation from high school, students with percentages above or equal to 90% are getting scholarships and students
with percentages below 70% but not below 60% must register for the ENGLISH class. Write a Java program to do the
following:
 Prompt the user to enter the number of students. If the user entered a negative or zero number of students, then print
an invalid message and ask the user to try again (see the sample input/output).
 Ask the user to enter percentages (double) for all students.

 Display how many students have scholarships and how many students registered for the ENGLISH class.

How many students? -3


Invalid input. Try again? 6
Enter percentages for 6 students:
85.0
68.0
92.5
61.0
95.5
64.0
2 have scholarship and 3 registered ENGLISH
Exercise
Scanner kbd = new Scanner(System.in);
int number, scholarship=0, english=0;
double percentage;
System.out.print("How many students? ");
number = kbd.nextInt();
do {
number = kbd.nextInt();
if (number <0)
System.out.print("Invalid input. Try again? ");
} while(number<=0);
System.out.println("Enter percentages for " + number + " students:");
for (int i=1; i<=number; i++){
percentage = kbd.nextDouble();
if (percentage>=90)
scholarship++;
if ((percentage>=60) && (percentage<70))
english++;
}
System.out.println(scholarship + " have scholarship and " + english +
"registered ENGLISH");
Exercise
Write a Java program to generate a user’s daily average number of walking steps for a given month of the
year. To do so, write the appropriate code for each of the following steps:
a) First the program should prompt the user to enter the month’s number (from 1 to 12) as an integer type.
Assume all input is valid.
b) Use switch case to determine the number of days in the given month (Suppose that month 2 has 28 days,
months 1,3,5,7,8, 10,12 have 31 days and the other months have 30 days).
c) Use a counter-based loop (for-loop or while-loop) to ask the user to enter the number of steps walked in
each of the days of the entered month.
d) Calculate and display the daily average number of walked steps as follows:

Input the month: 2


Input the number of steps for each of the 28
days of month 2:
227 1232 119 12002 1222 . . . 222
Daily Average of Walked Steps = 4732.28322
int monthNum, numOfDays;
double dailyAVG=0;
System.out.print("Input the month: ");
monthNum = kbd.nextInt();
switch (monthNum){
case 2:
numOfDays = 28;
break;
case 1:
case 3:
case 5:
Case 7:
case 8:
case 10:
case 12:
numOfDays = 31;
break;
default:
numOfDays = 30;
}
System.out.println("Input the number of steps for each of the " + numOfDays + " days of month " +
monthNum);
for (int i=1; i<=numOfDays; i++){
dailyAVG+= kbd.nextDouble();
}
dailyAVG/=numOfDays;
System.out.println("Daily Average of Walked Steps = " + dailyAVG);
Exercise
A triathlon is a multiple stage sports competition, where athletes compete for fastest overall course
completion time. Write a Java program that asks the user to enter the name and time for 5 athletes, then prints
the name and time of the winner. All times are measured in minutes (int). The winner has the lowest time.
Assume all inputs are valid.

Enter the name and time for 5 athletes:


Mike 274
John 207
Bob 301
Alistair 206
Comac 244
The winner is Alistair with completion time of 206 minutes
Exercise
Scanner kbd = new Scanner(System.in);
int time, winnerTime = -1.7;
String name, winnerName;
System.out.println("Enter the name and time for 5 athletes:");
for (int i = 1; i<=5; i++){
name=kbd.next();
time = kbd.nextInt();
if ((winnerTime>time) || (i==1)) {
winnerTime = time;
winnerName = name;
}
}
System.out.println("The winner is " + winnerName + " with completion time of " +
winnerTime + " minutes");
Exercise
Write a JAVA program that asks the user to input the jackets quality in any letter case (HQ for High Quality,
LQ for Low Quality) and their prices in a factory, until the user enters a QUIT in any letter case to stop. Your
program should count the number of HQ and LQ jackets, as well as, the highest HQ price of a jacket, then
print the results on the screen. Your program should ignore any unknown jacket quality.

Enter jackets quality followed by their prices (quit to stop):


LQ 100.5
HQ 382.99
Lq 411.05
hq 277.78
sd 120.5
HQ 299.5
Quit
Number of HQ jackets = 3
Number of LQ jackets = 2
Highest HQ Price BD = 382.99
Scanner kbd = new Scanner(System.in);
String quality;
int LQcount = 0, HQcount = 0;
double price, highestHQ = 0;
System.out.println("Enter jackets quality followed by their prices (quit to
stop):");
do {
quality = kbd.next();
if (!quality.equalsIgnoreCase("Quit")) {
price = kbd.nextDouble();
if (quality.equalsIgnoreCase("HQ")) {
HQcount++;
if (highestHQ < price)
highestHQ = price;
}
if (quality.equalsIgnoreCase("LQ")) {
LQcount++;
}
}
}while(!(quality.equals("Quit")));
System.out.println("Number of HQ jackets = " + HQcount);
System.out.println("Number of LQ jackets = " + LQcount);
System.out.println("Highest HQ Price BD = "+ highestHQ);
}
Nested Loop
 The body of a loop can contain any sort of statements, including loop statement.

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

Hint: you can use the function Congratulations!


Math.rand() that generate random You have guessed all 4 digits correctly
number between 0 and 1
int i, secret , guess, sum=0, correct=0, s, sd, g, gd, attempts = 0;
boolean flag = false;
secret = (int)(Math.random()*10000);
System.out.print(secret);
do {
attempts++;
System.out.print("Enter your guess for attempt " + attempts + ": ");
g = kbd.nextInt();
sum=0; correct= 0; s=secret;
for (i = 1 ; i <= 4; i++) {
sd = s%10; gd = g%10;
s /= 10; g /= 10;
if (sd==gd) {
sum += gd;
correct++;
}
}
if (correct<4)
System.out.println("The number of correct digits guessed is " + correct + " and the
sum of the digits is " + sum + "\n");
} while ((correct<4) && (attempts <5 ));
if (correct == 4)
System.out.println("Congratulations! \nYou have guessed all 4 digits correctly");
else
System.out.println("Sorry you couldn't guess the secret number.");

You might also like