[go: up one dir, main page]

0% found this document useful (0 votes)
14 views21 pages

Looping

Uploaded by

lenverparis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views21 pages

Looping

Uploaded by

lenverparis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Looping

Looping
In this chapter you will
• Learn about the Loop Structure
• Create While Loops
• Use Shortcut arithmetic operators
• Create for Loops
• Create do….while Loops
• Nest Loops
• Improve Loops performance
Learning About the Loop
Structure
If making decisions is what makes programs seem smart, looping is
what makes programs seem powerful. A loop is a structure that allows
repeated execution of a block of statements. Within a looping
structure, a Boolean expression is evaluated. If it is true, a block of
statements called the loop body executes and the Boolean expression
is evaluated again. The loop body can be a single statement or a block
of statements between curly braces. As long as the expression is true,
the statements in the loop body continue to execute. When the
Boolean evaluation is false, the loop ends. One execution of any loop is
called an iteration.
Learning About
the Loop
Structure
In Java, you can use • A while loop, in which the loop
several mechanisms to controlling Boolean expression
create loops. In this is the first statement in the loop
chapter, you learn to
use three types of
• A for loop, which is usually used
loops: as a concise format in which to
execute loops
• A do…while loop, in which the
loop controlling Boolean
expression is the last statement
in the loop
Creating while Loops
• You can use a while loop to • You can use a while loop when you
execute a body of statements need to perform a task either a
continually as long as the predetermined or unpredictable
Boolean expression that controls number of times. A loop that
executes a specific number of times
entry into the loop continues to
is a definite loop, or a counted loop.
be true. In Java, a while loop On the other hand, the number of
consists of the keyword while times the loop executes might not
followed by a Boolean be determined until the program is
expression within parentheses, running. Such a loop is an indefinite
followed by the body of the loop because you don’t know how
loop. many times it will eventually loop.
Writing a Definite while Loop
• To write a definite loop, you • In the body of the loop, you
initialize a loop control variable, must include a statement that
a variable whose value alters the loop control variable.
determines whether loop
execution continues. While the
Boolean value that results from
comparing the loop control
variable and another value is
true, the body of the while loop
continues to execute.
Infinite loop
When you write applications containing loops, it is easy to make
mistakes. For example, executing the code shown the message “Hello”
to be displayed forever (theoretically) because there is no code to end
the loop. A loop that never ends is called an infinite loop.
Altering a Definite Loop’s
Control Variable
• A definite loop is a counter- • However, not all loops are
controlled loop because the loop controlled by adding 1. The loop
control variable is changed by shown displays “Hello” twice,
counting. It is very common to but its loop is controlled by
alter the value of a loop control subtracting 1 from a loop control
variable by adding 1 to it, or variable, or decrementing it.
incrementing the variable.
Using Shortcut Arithmetic
Operators
• Programmers commonly need to • Incrementing a variable in a loop
increase the value of a variable to keep track of the number of
in a program. As you saw in the occurrences of some event is also
previous section, many loops are known as counting. the process of
controlled by continually adding repeatedly increasing a value by
1 to some variable, as in count some amount is known as
= count + 1; accumulating
Using Shortcut The += is the add and assign
Arithmetic operator; it adds and assigns in one
Operators operation. Besides using the
Because increasing a
shortcut operator +=, you can use
variable is so common, Java the subtract and assign operator ( -
provides you with several = ), the multiply and assign
shortcuts for incrementing operator ( *= ), the divide and
and accumulating. The
statement count += 1; is assign operator ( /= ), and the
identical in meaning to remainder and assign operator
count = count + 1. ( %= ). Each of these operators is
used to perform the operation and
assign the result in one step.
Using Increment Operators (++)
in while Loops
• The ++ operator is a shortcut for Example 4: Printing Numbers Using ++
increasing a value by 1. You can
use it inside while loops for int count = 1;
counting tasks.
How It Works: while (count <= 5) {
• The count++ increments the
value of count by 1 after each System.out.println("Count:
iteration. " + count);
• The loop ends when count count++; // Shortcut
becomes greater than 5. for count = count + 1
}
Creating a for Loop
Introduction to the for Loop
• A for loop is ideal for situations where the number of iterations is
known beforehand.
• It is a shorthand notation for counter-controlled loops, allowing all
necessary components of the loop to be written in a single line.
Structure of a for Loop
The for loop syntax includes three main parts within parentheses, separated by
semicolons:
for (initialization; condition; • Initialization: Sets up the loop
update) {
control variable (e.g., int i = 0;).
// Loop body
Executed once at the start of the
} loop.
• Condition: Boolean expression
tested before each iteration. If true,
the loop runs; if false, the loop exits.
• Update: Alters the loop control
variable after each iteration (e.g., +
+i;).
Example: Printing numbers from 1 to 10
using a for loop:
for (int val = 1; val <= 10; ++val) {
System.out.println(val);
}
Comparison with while Loop
• A for loop is functionally similar to Using for:
a while loop but more concise for
counter-controlled tasks.
Using while: for (int val = 1; val
<= 10; ++val) {
int val = 1;
while (val <= 10) {
System.out.println(val)
;
System.out.println(val);
}
++val;
Both produce the same output, but the for loop integrates
} initialization, condition, and update into one statement for
clarity.
For loop

Best Practices Summary


• Always use meaningful loop control • The for loop simplifies counter-
variable names. controlled loops by combining
• Avoid modifying the loop control initialization, condition, and update.
variable inside the loop body to • It is ideal for definite loops where
prevent bugs. the number of iterations is
• Use curly braces {} even for single-line predetermined.
loop bodies for better readability. • Understanding how to use its
• Ensure that the loop condition will features will make your programs
eventually be false to avoid infinite more efficient and readable.
loops.
The do-while Loop
• The do-while loop in Java is a do {
control flow statement that // Statements to execute
allows a block of code to be } while (condition);
executed at least once before
checking a condition. Unlike Key Points:
other loops (e.g., while or for),
the do-while loop ensures that • The block inside do is executed once
unconditionally.
the code block executes before
the condition is tested. • The while condition is checked after the
block's execution.
• If the condition evaluates to true, the
loop continues; otherwise, it stops.
Example: Printing Numbers
public class Sample { Explanation:
public static void main(String[] args) {
• Prints numbers from 1 to 5.
int number = 1;
do {
• The loop executes at least once,
System.out.println("Number: " +
even if the condition (number <=
number); 5) is false initially.
number++;
} while (number <= 5);
}
}
Example : Repeating a Task
public class RepeatTask {
Explanation:
public static void main(String[] args) {
int counter = 0;
• Executes the task three times
do { (counter < 3).
System.out.println("Task executed: " + counter); • Useful when you want to ensure
counter++; the task executes at least once.
} while (counter < 3);
}
}
Example : Simple Menu
Explanation:
public class SimpleMenu {
public static void main(String[] args) { • Simulates a menu system.
int choice;
• The menu is displayed at
do {
System.out.println("Menu:"); least once before the exit.
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. Exit");
choice = 3; // Simulate choosing exit
} while (choice != 3);
System.out.println("Exit menu.");
}
}
Exercises: Grading System using
both for and while loops.
How It Works Grading Criteria:
1. For Loop:
•Used to process a fixed number of • A: 90–100
students (numberOfStudents). • B: 80–89
2. While Loop: • C: 70–79
•Allows entering grades for
multiple subjects until the user • D: 60–69
enters -1 to stop. • F: Below 60
3. If-Else Statements:
•Used to determine the letter
grade based on the average grade.

You might also like