Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
17 views10 pages

NCP2210 LabAct3

Uploaded by

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

NCP2210 LabAct3

Uploaded by

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

NCP 2210 (Computer Fundamentals and Programming)

LABORATORY ACTIVITY #3
LOOPS
NAME: CRUZ, JOSH CLARENCE F. DR. JOAN P. LAZARO
SECTION: BSME 2 DATE: 3/27/22 GRADE:

The Increment and Decrement Operators


++ and − − are operators that add and subtract one from their operands. Java provides a
set of simple unary operators designed just for incrementing and decrementing variables. The
increment operator is ++ and the decrement operator is −−.

Example Program #1
package example;
/**
* @author Joan Lazaro
*/
public class Example
{
public static void main(String[] args)
{
int number = 4;
System.out.println("number is " + number);
System.out.println("I will increment number.");
number++;
System.out.println("Now, number is " + number);
System.out.println("I will decrement number.");
number--;
System.out.println("Now, number is " + number);
}
}

Result:

Observation:
My observation on this example program is that it shows the significant use of ++ and --.
It displays a addition or deduction of 1 to be exact.

1|Page
NCP 2210 (Computer Fundamentals and Programming)

Example Program #2
package example;
/**
* @author Joan Lazaro
*/
public class Example
{
public static void main(String[] args)
{
int number = 4;
System.out.println("number is " + number);
System.out.println("I will increment number.");
++number;
System.out.println("Now, number is " + number);
System.out.println("I will decrement number.");
--number;
System.out.println("Now, number is " + number);
}
}

Result:

Observation:
Example program number 2 is the same as example program number 1.

The Difference between Postfix and Prefix Modes


In Example Program #1 and Example Program #2, the statements number++ and +
+number increment the variable number, while the statements number−− and −−number
decrement the variable number. In these simple statements, it doesn’t matter whether the
operator is used in postfix or prefix mode. The difference is important, however, when these
operators are used in statements that do more than just increment or decrement.
For example, look at the following code:
number = 4;
System.out.println(number++);
The statement that calls the println method does two things: (1) calls println to display the
value of number, and (2) increments number. But which happens first? The println method will
display a different value if number is incremented first than if number is incremented last.

2|Page
NCP 2210 (Computer Fundamentals and Programming)

The answer depends upon the mode of the increment operator. Postfix mode causes the
increment to happen after the value of the variable is used in the expression. In the previously
shown statement, the println method will display 4 and then number will be incremented to 5.
Prefix mode, however, causes the increment to happen first.
number = 4;
System.out.println(++number);
In these statements, number is incremented to 5, then println will display the value in
number (which is 5). For another example, look at the following code:
int x = 1, y;
y = x++; // Postfix increment
The first statement declares the variable x (initialized with the value 1) and the variable y. The
second statement does the following:
 It assigns the value of x to the variable y.
 The variable x is incremented.
The value that will be stored in y depends on when the increment takes place. Because the ++
operator is used in postfix mode, it acts after the assignment takes place. So, this code will store
1 in y. After the code has executed, x will contain 2. Let’s look at the same code, but with the ++
operator used in prefix mode as follows:
int x = 1, y;
y = ++x; // Prefix increment
The first statement declares the variable x (initialized with the value 1) and the variable y.
In the second statement, the ++ operator is used in prefix mode, so it acts on the variable before
the assignment takes place. So, this code will store 2 in y. After the code has executed, x will
also contain 2.

The while loop


A loop is part of a program that repeats. In Experiment #2, you were introduced to the
concept of control structures, which direct the flow of a program. A loop is a control structure
that causes a statement or group of statements to repeat. Java has three looping control structures:
the while loop, the do-while loop, and the for loop. The difference among each of these is how
they control the repetition.
The while loop has two important parts: (1) a boolean expression that is tested for a true
or false value, and (2) a statement or block of statements that is repeated as long as the
expression is true. The figure below shows the logic of a while loop.

Here is the general format of the while loop:


while (BooleanExpression)
{

3|Page
NCP 2210 (Computer Fundamentals and Programming)

Statement;
Statement;
// Place as many statements here
// as necessary.
}

Example Program #3
package example;
/**
* @author Joan Lazaro
*/
public class Example
{
public static void main(String[] args)
{
int number = 1;
while (number <= 5)
{
System.out.println("Hello");
number++;
}
System.out.println("That's all!");
}
}

Result:

Observation:
The example program will display the number that is inputted and display it on text and
the value will be the number of word or sentence will be done repeatedly.

Example Program #4

4|Page
NCP 2210 (Computer Fundamentals and Programming)

import javax.swing.JOptionPane;
package example;
/**
* @author Joan Lazaro
*/
public class Example
{
public static void main(String[] args)
{
final int MIN_PLAYERS = 9; // Minimum players per team
final int MAX_PLAYERS = 15; // Maximum players per team
int players; // Number of available players
int teamSize; // Number of players per team
int teams; // Number of teams
int leftOver; // Number of leftover players
String input; // To hold the user input
input = JOptionPane.showInputDialog("Enter the number of players per
team.");
teamSize = Integer.parseInt(input);
while (teamSize < MIN_PLAYERS || teamSize > MAX_PLAYERS)
{
input = JOptionPane.showInputDialog("The number must be at least "
+ MIN_PLAYERS + " and no more than " + MAX_PLAYERS + ".\n Enter the number of
players.");
teamSize = Integer.parseInt(input);
}
input = JOptionPane.showInputDialog("Enter the available number of
players.");
players = Integer.parseInt(input);
while (players < 0)
{
input = JOptionPane.showInputDialog("Enter 0 or greater.");
players = Integer.parseInt(input);
}
teams = players / teamSize;
leftOver = players % teamSize;
JOptionPane.showMessageDialog(null, "There will be " + teams + " teams
with " + leftOver + " players left over.");
System.exit(0);
}
}
Result:

Observation:

5|Page
NCP 2210 (Computer Fundamentals and Programming)

In example program #4, the JOptionPane package is used to have a pop up to answer the
following needed data.

The do-while loop


The do-while loop is a posttest loop, which means its boolean expression is tested after
each iteration. The do-while loop looks something like an inverted while loop. The figure below
shows the logic of a do-while loop.

Here is the format of the do-while loop when the body of the loop contains multiple
statements:
do
{
Statement;
Statement;
// Place as many statements here as necessary.
} while (BooleanExpression);

Example Program #5
import java.util.Scanner;
package example;
/**
* @author Joan Lazaro
*/
public class Example
{
public static void main(String[] args)
{
int score1, score2, score3; // Three test scores
double average; // Average test score
char repeat; // To hold 'y' or 'n'
String input; // To hold input
System.out.println("This program calculates the average of three test
scores.");
Scanner keyboard = new Scanner(System.in);
do
{
System.out.print("Enter score #1: ");
score1 = keyboard.nextInt();

6|Page
NCP 2210 (Computer Fundamentals and Programming)

System.out.print("Enter score #2: ");


score2 = keyboard.nextInt();
System.out.print("Enter score #3: ");
score3 = keyboard.nextInt();
keyboard.nextLine();
average = (score1 + score2 + score3) / 3.0;
System.out.println("The average is " + average);
System.out.println();
System.out.println("Would you like to average another set of test
scores?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
} while (repeat == 'Y' || repeat == 'y');
}
}

Result:

Observation:
The program asks for data needed for the system to compute the following required. And
it will display a question if you want to be asked and compute the following next data. And if not
the system will not ask anymore.
The for loop
The for loop is ideal for performing a known number of iterations. In general, there are
two categories of loops: conditional loops and count-controlled loops. A conditional loop
executes as long as a particular condition exists. For example, an input validation loop executes
as long as the input value is invalid. When you write a conditional loop, you have no way of
knowing the number of times it will iterate. Sometimes you do know the exact number of
iterations that a loop must perform.
A loop that repeats a specific number of times is known as a count-controlled loop. For
example, if a loop asks the user to enter the sales amounts for each month in the year, it will
iterate 12 times. In essence, the loop counts to 12 and asks the user to enter a sales amount each
time it makes a count.
A count-controlled loop must possess three elements:
1. It must initialize a control variable to a starting value.
2. It must test the control variable by comparing it to a maximum value. When the
control variable reaches its maximum value, the loop terminates.
3. It must update the control variable during each iteration. This is usually done by
incrementing the variable.

7|Page
NCP 2210 (Computer Fundamentals and Programming)

In Java, the for loop is ideal for writing count-controlled loops. It is specifically designed
to initialize, test, and update a loop control variable. The figure below shows the logic of a for
loop.

Here is the format of the for loop when used to repeat a single statement:
for (Initialization; Test; Update)
{
Statement;
Statement;
// Place as many statements here as necessary.
}

Example Program #6
package example;
/**
* @author Joan Lazaro
*/
public class Example
{
public static void main(String[] args)
{
int number; // Loop control variable
System.out.println("Number Number Squared");
System.out.println("------------------------");
for (number = 1; number <= 10; number++)
{
System.out.println(number + "\t\t" + number * number);
}
}
}

Result:

Observation:

8|Page
NCP 2210 (Computer Fundamentals and Programming)

The following example problem displays a square of a number, and then the number that
you will input will set the limit and displays 1 to 10 because the limit is 10.

Example Program #7
import java.util.Scanner;
package example;
/**
* @author Joan Lazaro
*/
public class Example
{
public static void main(String[] args)
{
int number; // Loop control variable
int maxValue; // Maximum value to display
System.out.println("I will display a table of numbers and their
squares.");
Scanner keyboard = new Scanner(System.in);
System.out.print("How high should I go? ");
maxValue = keyboard.nextInt();
System.out.println("Number Number Squared");
System.out.println("-----------------------");
for (number = 1; number <= maxValue; number++)
{
System.out.println(number + "\t\t" + number * number);
}
}
}

Result:

Observation:
The following example problem displays a square of a number, and then the number that
you will input will set the limit and displays 1 to the number that you inputted and it will display
the square of each number from 1 to the limit.

Nested Loops

9|Page
NCP 2210 (Computer Fundamentals and Programming)

A loop that is inside another loop is called a nested loop. Nested loops are necessary
when a task performs a repetitive operation and that task itself must be repeated.

Example Program #8
package example;
/**
* @author Joan Lazaro
*/
public class Example
{
public static void main(String[] args)
{
for (int hours = 1; hours <= 12; hours++)
{
for (int minutes = 0; minutes <= 59; minutes++)
{
for (int seconds = 0; seconds <= 59; seconds++)
{
System.out.printf("%02d:%02d:%02d\n", hours, minutes,
seconds);
}
}
}
}
}

Result:

Observation:
The example program displays a nested loop, because there is a ++ sign at input code, that is why
12:59:59 is displayed.

10 | P a g e

You might also like