building java programs chapter 2
DESCRIPTION
Building Java Programs Chapter 2. Primitive Data and Definite Loops. Review. Primitive data types: boolean , char, double, int Expressions and literals A rithmetic operators: +, -, *, /, % Precedence and casting Variables String concatenation and mixing types - PowerPoint PPT PresentationTRANSCRIPT
Building Java ProgramsChapter 2PRIMITIVE DATA AND DEFINITE LOOPS
2
Review• Primitive data types: boolean, char, double, int
• Expressions and literals
• Arithmetic operators: +, -, *, /, %
• Precedence and casting
• Variables
• String concatenation and mixing types
• Increment/decrement operators
• For loops
3
Review What output by the following set of statements? int x = 12; double y = 24; System.out.println("x divided by y = " + x / y);
A. x divided by y = 0 B. x divided by y = 12 / 24 C. x divided by y = 0.5 D. x divided by y = + 12 / 24 E. Nothing – this does not compile.
4
for loop syntaxfor (initialization; test; update) { statement; statement; ... statement;}
Perform initialization once.
Repeat the following:◦ Check if the test is true. If not, stop.
◦ Execute the statements.
◦ Perform the update.
body
header
6
Repetition with for loops
We see redundancy when trying to perform a task more than once:
System.out.println(“Let’s go…");System.out.println(“Seahawks!");System.out.println(“Seahawks!");System.out.println(“Seahawks!");System.out.println(“Go home, Peyton!");
Java's for loop statement performs a task many times.
System.out.println(“Let’s go…");
// Repeat 3 timesfor (int i = 0; i <= 2; i++) {System.out.println(“Seahawks!");}
System.out.println(“Go home, Peyton!");
7
Volunteers
Initializer Condition tester Console UpdaterVariable
for (int candies = 0; candies < 5; candies++) { System.out.println("I ate " + candies + " candies");}
9
Practice-It Self-check: 2.12, 2.15, 2.16, 2.18, 2.20
10
Nested for loopsOne for loop can be nested inside another.
for (int outerLoop = 0; outerLoop < 2; outerLoop++) {
System.out.println("OuterLoop variable = " + outerLoop);
for (int innerLoop = 5; innerLoop > 0; innerLoop = innerLoop / 2) {
System.out.println("InnerLoop variable = " + innerLoop);
}
}
11
Nested for loopsfor (int outerLoop = 0; outerLoop < 2; outerLoop++) {
System.out.println("OuterLoop variable = " + outerLoop);
for (int innerLoop = 5; innerLoop > 0; innerLoop = innerLoop / 2) {
System.out.println("InnerLoop variable = " + innerLoop);
}
}
OuterLoop variable = 0◦ InnerLoop variable = 5◦ InnerLoop variable = 2◦ InnerLoop variable = 1
OuterLoop variable = 1◦ InnerLoop variable = 5◦ InnerLoop variable = 2◦ InnerLoop variable = 1
12
Homework Self-check: 2.12, 2.15, 2.16, 2.18, 2.20, 2.26, 2.27
Exercise: 2.2, 2.3
If you finish the homework before class is over:
• Review for your quiz on Wednesday.
• Read BJP 2.4.
• Do extra Practice-Its.