0% found this document useful (0 votes)
45 views14 pages

DSA Lab 02 SPRING 2022 SE

This document provides information about selection and iterative controls in Java including if, if-else statements and for loops. It explains boolean expressions and data types and how they are used in conditional statements. Examples are given to demonstrate different types of conditional statements.

Uploaded by

Mehmood Sheikh
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)
45 views14 pages

DSA Lab 02 SPRING 2022 SE

This document provides information about selection and iterative controls in Java including if, if-else statements and for loops. It explains boolean expressions and data types and how they are used in conditional statements. Examples are given to demonstrate different types of conditional statements.

Uploaded by

Mehmood Sheikh
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/ 14

USMAN INSTITUTE OF TECHNOLOGY

CS211 DATA STRUCTURES & ALGORITHMS


LAB 02
SPRING 2022

Name : _________________________________________
Roll No. : _________________ Section : ________________
Date : _________________________________________
Remarks : _________________________________________
Signature : _________________________________________
April 6, 2022 LAB 02 – UNDERSTANDING SELECTION AND ITERATIVE CONTROLS IN JAVA

Student Name: ____________________________________ Roll No: ________________ Section: ______________

Experiment No. 02
Lab 02 – Understanding Selection and iterative controls in java using Eclipse IDE.

Selection Control:
If you enter a negative value for radius in Lab 01 Example 1.3, ComputeAreaWithConsoleInput.java, the program
prints an invalid result. If the radius is negative, you don’t want the program to compute the area. How can you deal
with this situation? Like all high-level programming languages, Java provides selection statements that let you choose
actions with two or more alternative courses. Selection statements use conditions. Conditions are Boolean expressions.
Let’s first introduces Boolean types, values, comparison operators, and expressions.

Boolean Data Type


How do you compare two values, such as whether a radius is greater than 0, equal to 0, or less than 0? Java provides
six comparison operators (also known as relational operators), shown in Table 2.1, which can be used to compare
two values (assume radius is 5 in the table).

TABLE 2.1 Comparison Operators

The result of the comparison is a Boolean value: true or false. For example, the following statement displays true:

double radius = 1;
System.out.println(radius > 0);

Output:

A variable that holds a Boolean value is known as a Boolean variable. The boolean data type is used to declare
Boolean variables. A boolean variable can hold one of the two values: true and false. For example, the following
statement assigns true to the variable lightsOn:

boolean lightsOn = true;

true and false are literals, just like a number such as 10. They are reserved words and cannot be used as identifiers in
your program.

Problem: A Simple Math Learning Tool


Suppose you want to develop a program to let a first-grader practice addition. The program randomly generates two
single-digit integers, number1 and number2, and displays to the student a question such as “What is ”, as shown in
the sample run. After the student types the answer, the program displays a message to indicate whether it is true or
Lab Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 1
Algorithms
April 6, 2022 LAB 02 – UNDERSTANDING SELECTION AND ITERATIVE CONTROLS IN JAVA

Student Name: ____________________________________ Roll No: ________________ Section: ______________


false. There are several ways to generate random numbers. For now, generate the first integer using
System.currentTimeMillis() % 10 and the second using System.currentTimeMillis() * 7 % 10. Example 2.1 gives
the program. Lines 5–6 generate two numbers, number1 and number2. Line 14 obtains an answer from the user. The
answer is graded in line 18 using a Boolean expression number1 + number2 == answer.

Example 2.1 AdditionProgram.java

Output:

if Statements
The preceding program displays a message such as “6 + 2 = 7 is false.” If you wish the message to be “6 + 2 = 7 is
incorrect,” you have to use a selection statement to carry out this minor change.
This section introduces selection statements. Java has several types of selection statements: one-way if statements,
two-way if statements, nested if statements, switch statements, and conditional expressions.

One-Way if Statements
A one-way if statement executes an action if and only if the condition is true. The syntax for a one-way if statement
is shown below:

if (boolean-expression) {
statement(s);
}

The execution flow chart is shown in Figure 2.1(a).

Lab Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 2
Algorithms
April 6, 2022 LAB 02 – UNDERSTANDING SELECTION AND ITERATIVE CONTROLS IN JAVA

Student Name: ____________________________________ Roll No: ________________ Section: ______________

FIGURE 2.1 An if statement executes statements if the boolean-expression evaluates to true.

If the boolean-expression evaluates to true, the statements in the block are executed.
As an example, see the following code:

if (radius >= 0) {
area = radius * radius * PI;
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}

The flow chart of the preceding statement is shown in Figure 3.1(b). If the value of radius is greater than or equal to
0, then the area is computed and the result is displayed; otherwise, the two statements in the block will not be executed.

Two-Way if Statements
A one-way if statement takes an action if the specified condition is true. If the condition is false, nothing is done. But
what if you want to take alternative actions when the condition is false? You can use a two-way if statement. The
actions that a two-way if statement specifies differ based on whether the condition is true or false.

Here is the syntax for a two-way if statement:

if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}

The flow chart of the statement is shown in Figure 2.2.

Lab Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 3
Algorithms
April 6, 2022 LAB 02 – UNDERSTANDING SELECTION AND ITERATIVE CONTROLS IN JAVA

Student Name: ____________________________________ Roll No: ________________ Section: ______________


FIGURE 2.2 An if ... else statement executes statements for the true case if the boolean-expression evaluates to true;
otherwise, statements for the false case are executed. If the boolean-expression evaluates to true, the statement(s) for
the true case are executed; otherwise, the statement(s) for the false case are executed. For example, consider the
following code:

if (radius >= 0) {
area = radius * radius * PI;
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
else {
System.out.println("Negative input");
}

If radius >= 0 is true, area is computed and displayed; if it is false, the message "Negative input" is printed.

Nested if Statements
The statement in an if or if ... else statement can be any legal Java statement, including another if or if ... else statement.
The inner if statement is said to be nested inside the outer if statement. The inner if statement can contain another if
statement; in fact, there is no limit to the depth of the nesting. For example, the following is a nested if statement:

if (i > k) {
if (j > k)
System.out.println("i and j are greater than k");
}
else
System.out.println("i is less than or equal to k");

The if (j > k) statement is nested inside the if (i > k) statement. The nested if statement can be used to implement
multiple alternatives. The statement given in Figure 2.3(a), for instance, assigns a letter grade to the variable grade
according to the score, with multiple alternatives.

FIGURE 2.3 A preferred format for multiple alternative if statements is shown in (b).

Switch Statements
It makes selections based on a single true or false condition. There are four cases for computing taxes, which depend
on the value of status. To fully account for all the cases, nested if statements were used. Overuse of nested if statements
makes a program difficult to read. Java provides a switch statement to handle multiple conditions efficiently.

Lab Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 4
Algorithms
April 6, 2022 LAB 02 – UNDERSTANDING SELECTION AND ITERATIVE CONTROLS IN JAVA

Student Name: ____________________________________ Roll No: ________________ Section: ______________

The flow chart of the preceding switch statement is shown in Figure 2.4.

FIGURE 2.4 The switch statement checks all cases and executes the statements in the matched case.

This statement checks to see whether the status matches the value 0, 1, 2, or 3, in that order. If matched, the
corresponding tax is computed; if not matched, a message is displayed. Here is the full syntax for the switch statement:

switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}

Iterative Control:
Suppose that you need to print a string (e.g., "Welcome to Java!") a hundred times. It would be tedious to have to
write the following statement a hundred times:

Lab Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 5
Algorithms
April 6, 2022 LAB 02 – UNDERSTANDING SELECTION AND ITERATIVE CONTROLS IN JAVA

Student Name: ____________________________________ Roll No: ________________ Section: ______________


So, how do you solve this problem?
Java provides a powerful construct called a loop that controls how many times an operation or a sequence of operations
is performed in succession. Using a loop statement, you simply tell the computer to print a string a hundred times
without having to code the print statement a hundred times, as follows:

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

The variable count is initially 0. The loop checks whether (count < 100) is true. If so, it executes the loop body to
print the message "Welcome to Java!" and increments count by 1. It repeatedly executes the loop body until (count
< 100) becomes false. When (count < 100) is false (i.e., when count reaches 100), the loop terminates and the next
statement after the loop statement is executed.

Loops are constructs that control repeated executions of a block of statements. The concept of looping is fundamental
to programming. Java provides three types of loop statements: while loops, do-while loops, and for loops.

The while Loop


The syntax for the while loop is as follows:

while (loop-continuation-condition) {
// Loop body
Statement(s);
}

Figure 2.5(a) shows the while-loop flow chart. 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 of the loop. Each loop contains a
loop-continuation-condition, a Boolean expression that controls the execution of the body. It 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 loop for printing Welcome to Java! a hundred times introduced in the preceding section is an example of a while
loop. Its flow chart is shown in Figure 2.5(b). The loop-continuation-condition is (count < 100) and loop body
contains two statements
as shown below:

Lab Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 6
Algorithms
April 6, 2022 LAB 02 – UNDERSTANDING SELECTION AND ITERATIVE CONTROLS IN JAVA

Student Name: ____________________________________ Roll No: ________________ Section: ______________

FIGURE 2.5 The while loop repeatedly executes the statements in the loop body when the loop-continuation-
condition evaluates to true. In this example, you know exactly how many times the loop body needs to be executed.
So a control variable count is used to count the number of executions. This type of loop is known as a counter-
controlled loop.

Here is another example to help understand how a loop works.

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

Output:

Example 2.2 GuessNumber.java


1 import java.util.Scanner;
2
3 public class GuessNumber {
4 public static void main(String[] args) {
5 // Generate a random number to be guessed
6 int number = (int)(Math.random() * 101);
7
8 Scanner input = new Scanner(System.in);
9 System.out.println("Guess a magic number between 0 and 100");
10
11 int guess = -1;
12 while (guess != number) {
13 // Prompt the user to guess the number
14 System.out.print("\nEnter your guess: ");
15 guess = input.nextInt();
16
Lab Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 7
Algorithms
April 6, 2022 LAB 02 – UNDERSTANDING SELECTION AND ITERATIVE CONTROLS IN JAVA

Student Name: ____________________________________ Roll No: ________________ Section: ______________


17 if (guess == number)
18 System.out.println("Yes, the number is " + number);
19 else if (guess > number)
20 System.out.println("Your guess is too high");
21 else
22 System.out.println("Your guess is too low");
23 // End of loop
24 }
25 }

Output:

The do-while Loop


The do-while loop is a variation of the while loop. Its syntax is given below:

do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);

Its execution flow chart is shown in Figure 2.6.

FIGURE 2.6 The do-while loop executes the loop body first, then checks the loop-continuation-condition to
determine whether to continue or terminate the loop.
The loop body is executed first. Then the loop-continuation-condition is evaluated. If the evaluation is true, the loop
body is executed again; if it is false, the do-while loop terminates. The difference between a while loop and a do-
while loop is the order in which the loop-continuation-condition is evaluated and the loop body executed. The while
loop and the do-while loop have equal expressive power. Sometimes one is a more convenient choice than the other.
For example, you can rewrite the while loop in Listing 4.4 using a do-while loop, as shown in Listing 4.5:

Example 2.3 TestDoWhile.java


1 import java.util.Scanner;
2
3 public class TestDoWhile {
4 /** Main method */
5 public static void main(String[] args) {
6 int data;
Lab Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 8
Algorithms
April 6, 2022 LAB 02 – UNDERSTANDING SELECTION AND ITERATIVE CONTROLS IN JAVA

Student Name: ____________________________________ Roll No: ________________ Section: ______________


7 int sum = 0;
8
9 // Create a Scanner
10 Scanner input = new Scanner(System.in);
11
12 // Keep reading data until the input is 0
13 do{
14 // Read the next data
15 System.out.print("Enter an int value (the program exits if the input is 0): ");
16
17 data = input.nextInt();
18
19 sum += data;
20 } while (data != 0);
21
22 System.out.println("The sum is " + sum);
23 }
24 }

Output:

The for Loop


Often you write a loop in the following common form:

i = initialValue; // Initialize loop control variable


while (i < endValue) {
// Loop body
...
i++; // Adjust loop control variable
}

A for loop can be used to simplify the proceding loop:

for (i = initialValue; i < endValue; i++) {


// Loop body
...
}

In general, the syntax of a for loop is as shown below:

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


// Loop body;
Statement(s);
}

Lab Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 9
Algorithms
April 6, 2022 LAB 02 – UNDERSTANDING SELECTION AND ITERATIVE CONTROLS IN JAVA

Student Name: ____________________________________ Roll No: ________________ Section: ______________


The flow chart of the for loop is shown in Figure 2.7(a).

FIGURE 2.7 A for loop performs an initial action once, then repeatedly executes the statements in the loop body, and
performs an action after an iteration when the loop-continuation-condition evaluates to true.
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, loop-continuation-condition, and action-after-each-iteration.
The control structure is followed by the loop body enclosed inside braces. The initial-action, loopcontinuation-
condition, and action-after-each-iteration are separated by semicolons.

A for loop generally uses a variable to control how many times the loop body is executed and when the loop terminates.
This variable is referred to as a control variable. The initialaction often initializes a control variable, the action-after-
each-iteration usually increments or decrements the control variable, and the loop-continuation-condition tests
whether the control variable has reached a termination value. For example, the following for loop prints Welcome to
Java! a hundred times:
int i;
for (i = 0; i < 100; i++) {
System.out.println("Welcome to Java!");
}

The flow chart of the statement is shown in Figure 2.7(b). The for loop initializes i to 0, then repeatedly executes the
println statement and evaluates i++ while i is less than 100.
The initial-action, i = 0, initializes the control variable, i. The loopcontinuation-condition, i < 100, is a Boolean
expression. The expression is evaluated right after the initialization and at the beginning of each iteration. If this
condition is true, the loop body is executed. If it is false, the loop terminates and the program control turns to the line
following the loop.

The action-after-each-iteration, i++, is a statement that adjusts the control variable. This statement is executed after
each iteration. It increments the control variable. Eventually, the value of the control variable should force the loop-
continuation-condition to become false. Otherwise the loop is infinite.

Lab Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 10
Algorithms
April 6, 2022 LAB 02 – UNDERSTANDING SELECTION AND ITERATIVE CONTROLS IN JAVA

Student Name: ____________________________________ Roll No: ________________ Section: ______________


Example 2.4 MultiplicationTable.java
1 public class MultiplicationTable {
2 /** Main method */
3 public static void main(String[] args) {
4 // Display the table heading
5 System.out.println(" Multiplication Table");
6
7 // Display the number title
8 System.out.print(" ");
9 for (int j = 1; j <= 9; j++)
10 System.out.print(" " + j);
11
12 System.out.println("\n—————————————————————————————");
13
14 // Print table body
15 for (int i = 1; i <= 9; i++) {
16 System.out.print(i + " | ");
17 for (int j = 1; j <= 9; j++) {
18 // Display the product and align properly
19 System.out.printf("%4d", i * j);
20 }
21 System.out.println()
22 }
23 }
24 }

Output:

Show the output of the following programs. (Tip: Draw a table and list the variables in the columns to trace these
programs.)

Output (a): Output (b):

Lab Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 11
Algorithms
April 6, 2022 LAB 02 – UNDERSTANDING SELECTION AND ITERATIVE CONTROLS IN JAVA

Student Name: ____________________________________ Roll No: ________________ Section: ______________


Answer the following questions:
1. Assuming that x is 1, show the result of the following Boolean expressions.
(true) && (3 > 4)
!(x > 0) && (x > 0)
(x > 0) || (x < 0)
(x != 0) || (x == 0)
(x >= 0) || (x < 0)
(x != 1) == ! (x == 1)

2. Write a Boolean expression that evaluates to true if a number stored in variable num is between 1 and 100.
3. Suppose, when you run the program, you enter input 2 3 6 from the console. What is the output?
public class Test {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
double x = input.nextDouble();
double y = input.nextDouble();
double z = input.nextDouble();
System.out.println("(x < y && y < z) is " + (x < y && y < z));
System.out.println("(x < y || y < z) is " + (x < y || y < z));
System.out.println("!(x < y) is " + !(x < y));
System.out.println("(x + y < z) is " + (x + y < z));
System.out.println("(x + y < z) is " + (x + y < z));
}
}
4. How do you obtain the current minute using the System.currentTimeMillis() method?
5. What are the benefits of using constants?
6. Show the following output.
float f = 12.5F;
int i = (int)f;
System.out.println("f is " + f);
System.out.println("i is " + i);
7. What is the keyword break for? What is the keyword continue for?
8. If a variable is declared in the for loop control, can it be used after the loop exits?
9. Can you convert a for loop to a while loop? List the advantages of using for loops.
10. Do the following two loops result in the same value in sum?

11. What does the following statement do?


for ( ; ; ) {
do something;}
12. Use a switch statement to rewrite the following if statement and draw the flow chart for the switch
statement:
if (a == 1)
x += 5;
else if (a == 2)
x += 10;
else if (a == 3)
x += 16;
else if (a == 4)
x += 34;
Lab Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 12
Algorithms
April 6, 2022 LAB 02 – UNDERSTANDING SELECTION AND ITERATIVE CONTROLS IN JAVA

Student Name: ____________________________________ Roll No: ________________ Section: ______________


13. What data types are required for a switch variable? If the keyword break is not used after a case is
processed, what is the next statement to be executed? Can you convert a switch statement to an equivalent
if statement, or vice versa? What are the advantages of using a switch statement?
14. Which of the following is a possible output from invoking Math.random()?
323.4, 0.5, 34, 1.0, 0.0, 0.234
15. List six comparison operators.

Programming Exercise
1. If today is Saturday, it will be Saturday again in 7 days. Suppose you and your friends are going to meet in
10 days. What day is in 10 days? Write a program to compute the day.
2. Write a program that find the birthday of your friend by asking few questions:
Hint: You can use these five table sets in your program to ask questions:

3. (Task 5 from Lab 01) Create a logic and write the program that show the time when hour pointer and
minute pointer makes overlap in a day. (E.g. at 12:00 both two pointers overlap each other).
4. (Game: scissor, rock, paper) Write a program that plays the popular scissor-rock-paper game. (A scissor
can cut a paper, a rock can knock a scissor, and a paper can wrap a rock.) The program randomly generates
a number 0, 1, or 2 representing scissor, rock, and paper. The program prompts the user to enter a number
0, 1, or 2 and displays a message indicating whether the user or the computer wins, loses, or draws. Here
are sample runs:
Output:(a)
scissor (0), rock (1), paper (2): 1
The computer is scissor. You are rock. You won

Output:(b)
scissor (0), rock (1), paper (2): 2
The computer is paper. You are paper too. It is a draw
5. Write a program to display the following pattern by using loop:
0
1 1
2 2 2
3 3 3 3
4 4 4 4 4
3 3 3 3
2 2 2
1 1
0
6. Write a program to calculate the value of Factorial?
7. In computing the following series, you will obtain more accurate results by computing from right to left
rather than from left to right:
1 1 1 1
1 + + + + ⋯+
2 3 4 𝑛
Write a program that compares the results of the summation of the preceding series, computing from left to
right and from right to left with n 50000.

Lab Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 13
Algorithms

You might also like