0% found this document useful (0 votes)
2 views13 pages

Lab2 Java Controlflow

This document provides an overview of control flow statements in Java, including decision-making, loops, and branching. It details the syntax and usage of if-else statements, switch statements, and various types of loops (while, do-while, for). Additionally, it includes examples, comparisons, and exercises for practical application of these concepts.

Uploaded by

PRO-TECH TIPS
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)
2 views13 pages

Lab2 Java Controlflow

This document provides an overview of control flow statements in Java, including decision-making, loops, and branching. It details the syntax and usage of if-else statements, switch statements, and various types of loops (while, do-while, for). Additionally, it includes examples, comparisons, and exercises for practical application of these concepts.

Uploaded by

PRO-TECH TIPS
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

Lab – 2: Control Flow Statements

Programming in Java

Overview
By default, Java executes statements from top to bottom in the order they
appear. Control flow statements alter this sequential execution by allowing
programs to make decisions, repeat actions, and jump to different parts of code.
Java provides four categories of control flow statements:

Category Keywords
Decision-Making if, if-else, switch
Loops while, do-while, for
Branching break, continue, return, label
Exception Handling try, catch, finally, throw

Exception handling will be covered in a later lab. This lab focuses


on decision-making, loops, and branching.

Decision-Making: The if-else Statement


The if statement executes a block only when a boolean expression evaluates to
true.
if (boolean expression) {
statement(s)
}
With an else clause, the second block executes when the condition is false:
if (boolean expression) {
statement(s)
} else {
statement(s)
}
For multiple conditions, chain using else if:
if (condition1) {
statement(s)
} else if (condition2) {
statement(s)
} else if (condition3) {

1
statement(s)
} else {
statement(s) // executes if none of the above are true
}
Important: Only the first matching branch executes. Once a match is found,
the rest are skipped.

Example – Grade Calculator


import [Link];

public class CompoundIfElseDemo {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);
double percent;
char grade;

[Link]("Enter Percentage: ");


percent = [Link]();

if (percent < 0.0 || percent > 100.0) {


[Link]("Incorrect Percentage!");
return; // exits the method immediately
} else if (percent >= 90.0) { grade = 'A';
} else if (percent >= 80.0) { grade = 'B';
} else if (percent >= 70.0) { grade = 'C';
} else if (percent >= 60.0) { grade = 'D';
} else if (percent >= 50.0) { grade = 'E';
} else { grade = 'F'; }

[Link]("Grade: %c%n", grade);


}
}
Note: The return statement inside the if block exits the method early when
the input is invalid. This is a common pattern for input validation called a
guard clause.

The Conditional (Ternary) Operator


The conditional operator ? : is a compact alternative to a simple if-else. It
evaluates to one of two values based on a condition.

2
Operator Symbol Form Operation
Conditional ?: c ? x : y If c is true,
evaluate x;
otherwise
evaluate y

// Find the maximum of two numbers


int x = 15, y = 22;
int max = (x > y) ? x : y;
[Link]("Max: %d%n", max); // Output: Max: 22
Use the ternary operator for simple, single-value decisions. For more com-
plex logic, use a full if-else.

Decision-Making: The switch Statement


The switch statement selects one of many execution paths based on the value
of an expression.
switch (expression) {
case label1:
statement(s)
break;
case label2:
statement(s)
break;
...
default:
statement(s)
break;
}
Key rules: - switch works with byte, short, char, int, String, and enu-
merated types. - Each case must end with break to prevent fall-through —
where execution continues into the next case. - default handles any value not
matched by a case. It is optional but recommended. - Multiple case labels can
share the same body (intentional fall-through).

Example 1 – Integer Switch


import [Link];

public class SwitchIntDemo {


static final Scanner input = new Scanner([Link]);

3
public static void main(String[] args) {
int choice;
String selection;

[Link]("1. Black\n2. White\n3. Red\n4. Green\n5. Blue");


[Link]("Select a Color: ");
choice = [Link]();

switch (choice) {
case 1: selection = "Black"; break;
case 2: selection = "White"; break;
case 3: selection = "Red"; break;
case 4: selection = "Green"; break;
case 5: selection = "Blue"; break;
default: selection = "Invalid";
}

[Link]("Your selection is %s.%n", selection);


}
}

Example 2 – Char Switch (Multiple Labels per Case)


import [Link];
import [Link];

public class SwitchCharDemo {


static final PrintStream out = [Link];
static final Scanner in = new Scanner([Link]);

public static void main(String[] args) {


[Link]("Which is the capital city of Pakistan?");
[Link]("A. Islamabad\nB. Karachi\nC. Lahore\nD. Peshawar\nE. Quetta");
[Link]("Your choice: ");

char choice = [Link]().charAt(0);

switch (choice) {
case 'A': case 'a':
[Link]("Correct Answer!"); break;
case 'B': case 'C': case 'D': case 'E':
case 'b': case 'c': case 'd': case 'e':
[Link]("Incorrect Answer!"); break;

4
default:
[Link]("Invalid Answer!");
}
}
}
Note: [Link]().charAt(0) reads the first character of the user’s input.
This is the standard way to read a single character in Java since there is no
nextChar() method in Scanner.

if-else vs switch — When to Use Which

Situation Prefer
Checking ranges (e.g., >= 90) if-else
Checking equality against fixed values switch
Boolean conditions if-else
Many exact-match cases (e.g., menu options) switch

Loops
The while Loop
Repeats a block as long as the condition is true. The condition is checked
before each iteration.
while (boolean expression) {
statement(s)
}
If the condition is false from the start, the body never executes.
// Print 1 to 10
int count = 1;
while (count <= 10) {
[Link]("%d ", count++);
}

The do-while Loop


Similar to while, but the condition is checked after each iteration. The body
always executes at least once.

5
do {
statement(s)
} while (expression);
// Keep asking until valid input (1-5)
int answer;
do {
[Link]("Enter a number (1–5): ");
answer = [Link]();
} while (answer < 1 || answer > 5);
do-while is ideal for input validation — you always want to ask at least once.

The for Loop


Best used when the number of iterations is known in advance.
for (initialization; termination; increment) {
statement(s)
}
• Initialization: runs once at the start.
• Termination: checked before each iteration; loop stops when false.
• Increment: runs after each iteration.
// Compute factorial
long factorial = 1;
int number = 7;
for (int i = 2; i <= number; i++) {
factorial *= i;
}
[Link]("%d! = %,d%n", number, factorial);

The Enhanced for Loop (for-each)


A simplified form of for designed for iterating over arrays and collections.
for (type variable : array) {
statement(s)
}
int[] values = { 2, 4, 6, 8, 10 };
for (int item : values) {
[Link]("%d ", item);
}

6
The enhanced for cannot be used to modify elements or to loop a specific
number of times — use a regular for in those cases.

Loop Comparison

Feature while do-while for


Condition Before After Before
checked
Guaranteed No Yes (at least No
execution once)
Best use case Unknown Input validation Known iterations
iterations

Nested Loops
Loops can be placed inside other loops. The inner loop completes all its itera-
tions for every single iteration of the outer loop.
// Print a triangle pattern
int outer = 1;
while (outer <= 5) {
int inner = 1;
while (inner <= outer) {
[Link]("%d ", inner++);
}
[Link](); // new line after each row
++outer;
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Branching: break and continue


break
Terminates the nearest enclosing loop or switch statement immediately.

7
// Stop when user enters 0
int sum = 0, count = 0;
do {
[Link]("Enter value (0 to exit): ");
int value = [Link]();
if (value == 0) { break; }
sum += value;
count++;
} while (true);
[Link]("Sum of %d values: %d%n", count, sum);
Labeled break — breaks out of a specified outer loop, identified by a label:
outer:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (someCondition) {
break outer; // exits BOTH loops entirely
}
}
}

continue
Skips the rest of the current iteration and jumps to the next one.
// Print only odd numbers from 0 to 99
for (int i = 0; i < 100; i++) {
if ((i % 2) == 0) { continue; } // skip even numbers
[Link]("%d ", i);
}
Labeled continue — skips to the next iteration of a specified outer loop:
skip:
for (int i = 0; i < 100; i++) {
for (int j = 3; j < [Link](i) + 1; j += 2) {
if ((i % j) == 0) {
continue skip; // skip to next value of i
}
}
[Link]("%d ", i); // only prints if no factor was found
}

8
Lab Practice
Part A – Type and Run
Type and run the following programs. Predict the output before running, then
verify.
Program 1 – Fall-Through Demonstration
public class FallThroughDemo {
public static void main(String[] args) {
int x = 2;
switch (x) {
case 1: [Link]("One");
case 2: [Link]("Two");
case 3: [Link]("Three");
default: [Link]("Other");
}
}
}
Question: What is the output? Why? Now add break after each case and
observe the difference.
Program 2 – while vs do-while
public class LoopCompareDemo {
public static void main(String[] args) {
int x = 10;

// while loop
while (x < 5) {
[Link]("while: " + x);
x++;
}

// do-while loop
do {
[Link]("do-while: " + x);
x++;
} while (x < 5);
}
}
Question: Why does the while loop produce no output but do-while does?

9
Part B – Exercises
Write separate Java programs for each of the following:

# Task
1 Ask the user to enter a number. Print
whether it is positive, negative, or
zero.
2 Ask the user to enter two numbers
and a choice (+, -, *, /). Perform the
selected operation and print the
result. Handle division by zero.
3 Ask the user to enter marks for 5
subjects. Calculate the total,
percentage, and assign a grade
(A/B/C/D/E/F) based on the grade
calculator example.
4 Print the multiplication table of a
number entered by the user (from 1
to 12) using a for loop.
5 Print all even numbers from 1 to
50 using a while loop.
6 Write a program that keeps asking
the user to enter a password until
they enter the correct one
("java123"). Use a do-while loop.
7 Print the following star pattern
using nested loops: *, **, ***, ****,
***** (one row per line).
8 Write a program using a for loop
and continue that prints all numbers
from 1 to 100 that are divisible by 3
but not by 9.

Part C – Find the Errors


Find and fix all errors in the following programs:
Program 1:
public class ErrorOne {
public static void main(String[] args) {
int score = 75;
if score > 50 {

10
[Link]("Pass");
} else
[Link]("Fail")
}
}
Program 2:
public class ErrorTwo {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday");
case 4: [Link]("Thursday"); break;
}
}
}
Note: This compiles and runs — but is the output correct? What is wrong
logically?
Program 3:
public class ErrorThree {
public static void main(String[] args) {
for (int i = 0; i <= 10; i--) {
[Link](i);
}
}
}

Mastery Section – Tracing Code


For each snippet below, trace the execution by hand and write the expected
output before running the program. Then verify in your IDE.
Trace 1:
int i = 1, sum = 0;
while (i <= 5) {
sum += i;
i++;
}
[Link](sum);
Trace 2:

11
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 4; j++) {
if (j == 3) break;
[Link]("(%d,%d) ", i, j);
}
}
Trace 3:
int n = 36;
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
[Link]("%d ", i);
n /= i;
}
}

Lab Tasks
The following tasks are to be completed and submitted before the next lab
session.

# Task
1 Write a program that reads an integer
and prints whether it is odd or even
using the ternary operator.
2 Write a program that reads a year
from the user and determines whether
it is a leap year. A year is a leap
year if it is divisible by 4, except for
century years, which must be
divisible by 400.
3 Write a simple calculator using a
switch statement that supports +, -,
*, /, and % operations on two
numbers entered by the user.
4 Write a program that prints the
Fibonacci series up to n terms
using a for loop. (e.g., for n=8: 0 1 1
2 3 5 8 13)
5 Write a program that reads integers
from the user until -1 is entered
(sentinel value). Display the count,
sum, and average of the entered
numbers.

12
# Task
6 Write a program that prints a
right-angled triangle of numbers
using nested loops. For n=5, the
output should be: row 1 prints 1, row
2 prints 1 2, and so on.
7 Write a program that reads a number
and prints all its divisors using a
for loop, then determines if it is a
perfect number (a number equal to
the sum of its divisors, e.g., 6 = 1 + 2
+ 3).
8 Write a program that simulates a
number guessing game: the
program picks a fixed number (e.g.,
42), and the user keeps guessing using
a do-while loop. After each guess,
tell the user if their guess is too high,
too low, or correct.
9 Write a program that computes and
prints the sum of digits of a number
entered by the user. For example, for
1234, the answer is 10 (1+2+3+4).
Use a while loop.
10 Write a program that prints all
prime numbers between 1 and
100 using nested loops and continue.

References / Resources
1. Lecture Notes – CS212 Object Oriented Programming, Lecture 03
2. Introduction to Java Programming, by Y. Daniel Liang
3. [Link]
4. [Link]

13

You might also like