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

Control Flow in Java

The document provides an overview of control flow in Java, focusing on loops such as while, do-while, and enhanced for loops. It includes examples demonstrating their syntax and usage, along with explanations of jumping statements like break, continue, and return. The content is aimed at helping readers understand how to control the flow of execution in Java programs.

Uploaded by

jelintaric
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 views23 pages

Control Flow in Java

The document provides an overview of control flow in Java, focusing on loops such as while, do-while, and enhanced for loops. It includes examples demonstrating their syntax and usage, along with explanations of jumping statements like break, continue, and return. The content is aimed at helping readers understand how to control the flow of execution in Java programs.

Uploaded by

jelintaric
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

Control Flow in Java

Jelin Taric G
Asst. Professor
Department of Computer Science and Engineering
While Loop

• Used when the number of repetitions is not fixed, but depends on a


condition.

Syntax:
• while(condition) {
• // code to repeat
• }
While Loop Example

Example:
• public class WhileExample {
• public static void main(String[] args) {
• int i = 1;
• while(i <= 5) {
• [Link]("Number: " + i);
• i++;
• }
• }
• }
While Loop Example

Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
While Loop Example
import [Link];

public class WhileExample {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int num;

[Link]("Enter numbers (0 to stop): ");


num = [Link]();
While Loop Example

while(num != 0) {
[Link]("You entered: " + num);
num = [Link](); // ask again
}

[Link]("Loop ended!");
[Link]();
}
}
While Loop Example

Output:

Enter numbers (0 to stop):


45
You entered: 45
23
You entered: 23
0
Loop ended!
Do While

• Similar to while, but executes at least once (condition checked after the
loop).
• In ATM initially it will display the menu options. Then based on the
conditions user give the program decides.
• A system must ask for username and password at least once, and keep
repeating until correct.
Syntax:
• do {
• // code
• } while(condition);
DoWhileExample

Example:
• public class DoWhileExample {
• public static void main(String[] args) {
• int i = 1;
• do {
• [Link]("Value: " + i);
• i++;
• } while(i <= 5);
• }
• }
DoWhileExample

Output:
Value: 1
Value: 2
Value: 3
Value: 4
Value: 5
Example: (User Login)
write a do-while loop program in Java to check if a username and password entered by the user are correct,
with a maximum of 3 attempts.

import [Link];

public class LoginExample {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Correct credentials
String correctUsername = "admin";
String correctPassword = "1234";

int attempts = 0;
boolean success = false;
Example: (User Login)

do {
[Link]("Enter username: ");
String username = [Link]();

[Link]("Enter password: ");


String password = [Link]();

if ([Link](correctUsername) && [Link](correctPassword)) {


success = true;
break; // Exit the loop if login is successful
} else {
[Link]("Invalid username or password!");
}
Example: (User Login)

attempts++;
} while (attempts < 3);

if (success) {
[Link]("Login successful");
} else {
[Link]("Maximum attempts reached. Access denied");
}

}
}
Enhanced For Loop:

Used to iterate over arrays or collections


Simpler and cleaner than the traditional for loop when you don’t need
the index.
Only increment. Does not decrement. Also only increment by 1.
Enhanced For Loop:

Syntax

for (datatype variable : array name) {


// code using variable
}

•datatype → type of elements in the array/collection


•variable → each element of the array/collection (one at a time)
•arrayOrCollection → the array or collection you want to loop through
Normal for loop vs
enhanced
• public class NormalForExample {
public class ForEachExample {
• public static void main(String[] args) {
public static void main(String[] args)
• int[ ] numbers = {10, 20, 30, 40, {
50};
int[] numbers = {10, 20, 30, 40, 50};

• for (int i = 0; i < [Link]; for (int num : numbers) {


i++) {
[Link](num);
• [Link](numbers[ i ]);
}
• } }
• } }
• }
Enhanced For Loop:

Output:
10
20
30
40
50
Example 2: Array of Strings

public class StringArrayExample {


public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Mango"};

for (String fruit : fruits) {


[Link]("I like " +fruit);
}
}
}
Enhanced For Loop:

Output:

I like Apple
I like Banana
I like Mango
Jumping Statement
In Java, jumping statements are used to change the normal flow of control in a program.

break

• Used to exit from a loop or switch statement immediately.


• Control jumps out of the loop or switch.
break
• while( i < 5) {
• [Link]("Enter i value :
");
• import [Link];
• i = [Link]();
• public class BreakExample {
• if (i == 0) {
• public static void main(String[]
args) { • break; // exits the loop when i = 0

• Scanner sc = new • }
Scanner([Link]);
• [Link]("i = " + i);
• int i = 1;
• }

• }
• public class ContinueExample {
Continue
• public static void main(String[] args) {

• for (int i = 1; i <= 5; i++) {


• Only skips the current iteration of • if (i % 2 != 0) {
the loop and moves to the next
iteration. The loop itself is not • continue; // skips odd numbers
terminated.
• }

• [Link]("i = " + i);

• }

• }

• }
• public class ReturnExample {
return • public static void main(String[] args) {

• public int addNumbers(int a, int b) {


• Used to exit from a method. • return a + b; // returns the sum

• Can also return a value to the • }


calling method (if the method is
not void).
• [Link]("Sum = " +
addNumbers(5, 10));

• }

• }

You might also like