SlideShare a Scribd company logo
6.092: Intro to Java

3: Loops, Arrays
Assignment 2

Foo Corporation needs a program to calculate
how much to pay their employees.
1. Pay = hours worked x base pay
2. Hours over 40 get paid 1.5 the base pay
3. The base pay must be no less than $8.00
4. The number of hours must be no more than 60
Frequent Issues (I)

The signature of the main method cannot be
modified.
public static void main(String[] arguments) {
...
}
Frequent Issues (II)

Return values: if you declare that the method is not void,
then it has to return something!
public static int pay(double basePay, int hours) {
if (basePay < 8.0) return -1;
else if (hours > 60) return -1;
else {
int salary = 0;

...

return salary

}
}
Frequent Issues (III)

Don't create duplicate variables with the same
name
public static int pay(double basePay, int hours) {

int salary = 0; // OK
…
int salary = 0; // salary already defined!!
…
double salary = 0; //salary already defined!!
…
}
class WeeklyPay {
public static void pay(double basePay, int hours) {
if (basePay < 8.0) {
System.out.println("You must be paid at least $8.00/hour");
} else if (hours > 60) {
System.out.println("You can't work more than 60 hours a week");
} else {

int overtimeHours = 0;

if (hours > 40) {

overtimeHours = hours - 40;
hours = 40;
}
double pay = basePay * hours;
pay += overtimeHours * basePay * 1.5;
System.out.println("Pay this employee $" + pay);
}
}
public static void main(String[] arguments) {
pay(7.5, 35);
pay(8.2, 47);
pay(10.0, 73);
}
}
What we have learned so far

● Variables & types
● Operators
● Type conversions & casting

● Methods & parameters
● If statement
Today’s Topics
● Good programming style

● Loops
● Arrays
Good Programming Style
Good programming style

The goal of good style is to make your

code more readable.

By you and by others.
Rule #1: use good (meaningful) names

String a1;

int a2;

double b; // BAD!!

String firstName; // GOOD

String lastName; // GOOD

int temperature; // GOOD
Rule #2: Use indentation
public static void main (String[] arguments) {
int x = 5;
x = x * x;
if (x > 20) {
System.out.println(x + “ is greater than 20.”);
}
double y = 3.4;
}
Have a demo with no indentation
Ctrl-shift-F to auto-format the file
Rule #3: Use whitespaces
Put whitespaces in complex expressions:
// BAD!!
double cel=fahr*42.0/(13.0-7.0);
// GOOD
double cel = fahr * 42.0 / (13.0 - 7.0);
Rule #3: Use whitespaces
Put blank lines to improve readability:
public static void main (String[] arguments) {

int x = 5;

x = x * x;

if (x > 20) {
System.out.println(x + “ is > 20.”);
}
double y = 3.4;
}
Rule #4: Do not duplicate tests
if (basePay < 8.0) {
...
} else if (hours > 60) {
...
} else if (basePay >= 8.0 && hours <= 60) {
...
}
Rule #4: Do not duplicate tests
if (basePay < 8.0) {
...
} else if (hours > 60) {
...
} else if (basePay >= 8.0 && hours <= 60){
...
}
BAD
Rule #4: Do not duplicate tests

if (basePay < 8.0) {
...
} else if (hours > 60) {

...

} else {
...
}
Good programming style (summary)

Use good names for variables and methods
Use indentation
Add whitespaces
Don't duplicate tests
oops
Loops
Loops
static void main (String[] arguments) {
System.out.println(“Rule #1”);
System.out.println(“Rule #2”);
System.out.println(“Rule #3”);
}
What if you want to do it for 200 Rules?
Loops
Loop operators allow to loop through a block
of code.
There are several loop operators in Java.
The while operator
while (condition) {

statements
}
The while operator
int i = 0;
while (i < 3) {
System.out.println(“Rule #“ + i);
i = i+1;
}
Count carefully
Make sure that your loop has a chance to finish.
The for operator

for (initialization;condition;update){
statements
}
The for operator
for (int i = 0; i < 3; i=i+1) {
System.out.println(“Rule #“ + i);
}
Note: i = i+1 may be replaced by i++
S
}
Branching Statements
break terminates a for or while loop
break;
ystem.out.println(“Rule #” + i);
for (int i=0; i<100; i++) {
if(i == 50)
r
Branching Statements

continue skips the current iteration of a loop
and proceeds directly to the next iteration
fo (int i=0; i<100; i++) {
if(i == 50)
continue;
System.out.println(“Rule #” + i);
}
Embedded loops
for (int i = 0; i < 3; i++) {
for (int j = 2; j < 4; j++) {
System.out.println (i + “ “ + j);
}
}
Scope of the variable defined in the initialization:
respective for block
Arrays
Arrays

An array is an indexed list of values.
You can make an array of any type
int, double, String, etc..
All elements of an array must have the same type.
Arrays

..

0 1 2 3 .. n-1
Arrays

Example: double [ ]

5.0 2.44 9.01 1.0 -9.9
..
0 1 2 3 .. n-1
Arrays
The index starts at zero and ends at length-1.
Example:
int[] values = new int[5];
values[0] = 12; // CORRECT
values[4] = 12; // CORRECT
values[5] = 12; // WRONG!! compiles but
// throws an Exception
// at run-time
Have a demo with runtime exception
Arrays
An array is defined using TYPE[].
Arrays are just another type.
int[] values; // array of int
int[][] values; // int[] is a type
Arrays

To create an array of a given size, use the operator new :
int[] values = new int[5];
or you may use a variable to specify the size:
int size = 12;
int[] values = new int[size];
Array Initialization

Curly braces can be used to initialize an array.
It can ONLY be used when you declare the
variable.
int[] values = { 12, 24, -23, 47 };
Quiz time!

Is there an error in this code?
int[] values = {1, 2.5, 3, 3.5, 4};
Accessing Arrays

To access the elements of an array, use the [] operator:
values[index]
Example:
int[] values = { 12, 24, -23, 47 };
values[3] = 18; // {12,24,-23,18}
int x = values[1] + 3; // {12,24,-23,18}
The length variable

Each array has a length variable built-in that
containsthe length of the array.
int[] values = new int[12];

int size = values.length; // 12

int[] values2 = {1,2,3,4,5}

int size2 = values2.length; // 5
String arrays

A side note

public static void main (String[] arguments){
System.out.println(arguments.length);
System.out.println(arguments[0]);
System.out.println(arguments[1]);
}
Combining Loops and Arrays
Looping through an array
Example 1:
int[] values = new int[5];
for (int i=0; i<values.length; i++) {
values[i] = i;
int y = values[i] * values[i];
System.out.println(y);
}
Looping through an array
Example 2:
int[] values = new int[5];

int i = 0;

while (i < values.length) {

values[i] = i;
int y = values[i] * values[i];
System.out.println(y);
i++;

}
Summary for today

1. Programming Style

2. Loops
3. Arrays
Assignment 3
A group of friends participate in the Boston 

Marathon.

Find the best performer.

Find the second-best performer.
MIT OpenCourseWare
http://ocw.mit.edu
6.092 Introduction to Programming in Java
January (IAP) 2010
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.

More Related Content

Similar to LECTURE 3 LOOPS, ARRAYS.pdf (20)

Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
Graham Royce
 
Java tut1
Java tut1Java tut1
Java tut1
Sumit Tambe
 
Java tut1
Java tut1Java tut1
Java tut1
Sumit Tambe
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
Akash Pandey
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
Java tutorial PPT
Java tutorial  PPTJava tutorial  PPT
Java tutorial PPT
Intelligo Technologies
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
Intelligo Technologies
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
Abdul Aziz
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
Vijay A Raj
 
Java tut1
Java tut1Java tut1
Java tut1
Ajmal Khan
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
guest5c8bd1
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
Bui Kiet
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH, SINDH, PAKISTAN
 
Ppt on java basics1
Ppt on java basics1Ppt on java basics1
Ppt on java basics1
Mavoori Soshmitha
 
javaloop understanding what is java.pptx
javaloop understanding what is java.pptxjavaloop understanding what is java.pptx
javaloop understanding what is java.pptx
RobertCarreonBula
 
JAVA LOOP.pptx
JAVA LOOP.pptxJAVA LOOP.pptx
JAVA LOOP.pptx
SofiaArquero2
 
JAVA programming language made easy.pptx
JAVA programming language made easy.pptxJAVA programming language made easy.pptx
JAVA programming language made easy.pptx
Sunila31
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
parveen837153
 
17-Arrays en java presentación documento
17-Arrays en java presentación documento17-Arrays en java presentación documento
17-Arrays en java presentación documento
DiegoGamboaSafla
 

More from SHASHIKANT346021 (8)

Civil Engineering Departmental PPT 1.pptx
Civil Engineering Departmental PPT 1.pptxCivil Engineering Departmental PPT 1.pptx
Civil Engineering Departmental PPT 1.pptx
SHASHIKANT346021
 
Electronics and Computer Engineering PPT.pptx
Electronics and Computer Engineering PPT.pptxElectronics and Computer Engineering PPT.pptx
Electronics and Computer Engineering PPT.pptx
SHASHIKANT346021
 
Introducing-the-Python-Interpreter. What is Python Interpreter
Introducing-the-Python-Interpreter. What is Python InterpreterIntroducing-the-Python-Interpreter. What is Python Interpreter
Introducing-the-Python-Interpreter. What is Python Interpreter
SHASHIKANT346021
 
Course Presentation: Electronic & Computer Engineering
Course Presentation: Electronic & Computer EngineeringCourse Presentation: Electronic & Computer Engineering
Course Presentation: Electronic & Computer Engineering
SHASHIKANT346021
 
Parallel Programming Models: Shared variable model, Message passing model, Da...
Parallel Programming Models: Shared variable model, Message passing model, Da...Parallel Programming Models: Shared variable model, Message passing model, Da...
Parallel Programming Models: Shared variable model, Message passing model, Da...
SHASHIKANT346021
 
Parallel Programming Models: Shared variable model
Parallel Programming Models: Shared variable modelParallel Programming Models: Shared variable model
Parallel Programming Models: Shared variable model
SHASHIKANT346021
 
LECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdf
LECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdfLECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdf
LECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdf
SHASHIKANT346021
 
Classes in Java great learning.pdf
Classes in Java great learning.pdfClasses in Java great learning.pdf
Classes in Java great learning.pdf
SHASHIKANT346021
 
Civil Engineering Departmental PPT 1.pptx
Civil Engineering Departmental PPT 1.pptxCivil Engineering Departmental PPT 1.pptx
Civil Engineering Departmental PPT 1.pptx
SHASHIKANT346021
 
Electronics and Computer Engineering PPT.pptx
Electronics and Computer Engineering PPT.pptxElectronics and Computer Engineering PPT.pptx
Electronics and Computer Engineering PPT.pptx
SHASHIKANT346021
 
Introducing-the-Python-Interpreter. What is Python Interpreter
Introducing-the-Python-Interpreter. What is Python InterpreterIntroducing-the-Python-Interpreter. What is Python Interpreter
Introducing-the-Python-Interpreter. What is Python Interpreter
SHASHIKANT346021
 
Course Presentation: Electronic & Computer Engineering
Course Presentation: Electronic & Computer EngineeringCourse Presentation: Electronic & Computer Engineering
Course Presentation: Electronic & Computer Engineering
SHASHIKANT346021
 
Parallel Programming Models: Shared variable model, Message passing model, Da...
Parallel Programming Models: Shared variable model, Message passing model, Da...Parallel Programming Models: Shared variable model, Message passing model, Da...
Parallel Programming Models: Shared variable model, Message passing model, Da...
SHASHIKANT346021
 
Parallel Programming Models: Shared variable model
Parallel Programming Models: Shared variable modelParallel Programming Models: Shared variable model
Parallel Programming Models: Shared variable model
SHASHIKANT346021
 
LECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdf
LECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdfLECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdf
LECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdf
SHASHIKANT346021
 
Classes in Java great learning.pdf
Classes in Java great learning.pdfClasses in Java great learning.pdf
Classes in Java great learning.pdf
SHASHIKANT346021
 

Recently uploaded (20)

Group-4-report-_20250409_180212_0000.pdf
Group-4-report-_20250409_180212_0000.pdfGroup-4-report-_20250409_180212_0000.pdf
Group-4-report-_20250409_180212_0000.pdf
joankatevallecervald
 
Consistency Leads to Success : Consistency Leads to Success
Consistency Leads to Success : Consistency Leads to SuccessConsistency Leads to Success : Consistency Leads to Success
Consistency Leads to Success : Consistency Leads to Success
CorporateSecretary6
 
linux_admin_course_full_for beginers.pptx
linux_admin_course_full_for beginers.pptxlinux_admin_course_full_for beginers.pptx
linux_admin_course_full_for beginers.pptx
tejas2429
 
1- Rules of Tajweed Qalqalah_Letters.pptx
1- Rules of Tajweed Qalqalah_Letters.pptx1- Rules of Tajweed Qalqalah_Letters.pptx
1- Rules of Tajweed Qalqalah_Letters.pptx
sammk2023
 
MERI-Cultivating-Global-Professionals.pdf
MERI-Cultivating-Global-Professionals.pdfMERI-Cultivating-Global-Professionals.pdf
MERI-Cultivating-Global-Professionals.pdf
anchal600585
 
Visionary of the Year Leading the Charge for Sustainability.pdf
Visionary of the Year  Leading the Charge for Sustainability.pdfVisionary of the Year  Leading the Charge for Sustainability.pdf
Visionary of the Year Leading the Charge for Sustainability.pdf
ciotimespublication
 
The Role of Philanthropy in Strengthening Communities.pdf
The Role of Philanthropy in Strengthening Communities.pdfThe Role of Philanthropy in Strengthening Communities.pdf
The Role of Philanthropy in Strengthening Communities.pdf
Steven Bauer, M.D.
 
Proposal Entrepreneurial Summit 2024 (1).pptx
Proposal Entrepreneurial Summit 2024 (1).pptxProposal Entrepreneurial Summit 2024 (1).pptx
Proposal Entrepreneurial Summit 2024 (1).pptx
eee Lastsss
 
2025 Job-ready Program in Digital Marketing.pdf
2025 Job-ready Program in Digital Marketing.pdf2025 Job-ready Program in Digital Marketing.pdf
2025 Job-ready Program in Digital Marketing.pdf
himanshu1223344
 
Grey Modern Professional Business Project Presentation.pptx.pptx
Grey Modern Professional Business Project Presentation.pptx.pptxGrey Modern Professional Business Project Presentation.pptx.pptx
Grey Modern Professional Business Project Presentation.pptx.pptx
NURSYUHADABINTISAIDY
 
Bài Tập Tiếng Anh 7-Tập 1 (Mai Lan Hương - Hà Thanh Uyên).pdf
Bài Tập Tiếng Anh 7-Tập 1 (Mai Lan Hương - Hà Thanh Uyên).pdfBài Tập Tiếng Anh 7-Tập 1 (Mai Lan Hương - Hà Thanh Uyên).pdf
Bài Tập Tiếng Anh 7-Tập 1 (Mai Lan Hương - Hà Thanh Uyên).pdf
minhvy680
 
medical coding courses in sao tome and principe.pdf
medical coding courses in sao tome and principe.pdfmedical coding courses in sao tome and principe.pdf
medical coding courses in sao tome and principe.pdf
stskills iim
 
The Ultimate Guide to Startup Jobs in Jaipur – High-Growth Roles in 2025..pdf
The Ultimate Guide to Startup Jobs in Jaipur – High-Growth Roles in 2025..pdfThe Ultimate Guide to Startup Jobs in Jaipur – High-Growth Roles in 2025..pdf
The Ultimate Guide to Startup Jobs in Jaipur – High-Growth Roles in 2025..pdf
vinay salarite
 
SCIENCE QUIZ CLASS III for 111111111.pptx
SCIENCE QUIZ CLASS III for 111111111.pptxSCIENCE QUIZ CLASS III for 111111111.pptx
SCIENCE QUIZ CLASS III for 111111111.pptx
VickyRathi2
 
Power of audit and its implementation and mane.pptx
Power of audit and its implementation and mane.pptxPower of audit and its implementation and mane.pptx
Power of audit and its implementation and mane.pptx
ShomoyEkhonAmader
 
Empowering-Little-Learners-Innovation-in-MIS-Nursery-Education.pdf
Empowering-Little-Learners-Innovation-in-MIS-Nursery-Education.pdfEmpowering-Little-Learners-Innovation-in-MIS-Nursery-Education.pdf
Empowering-Little-Learners-Innovation-in-MIS-Nursery-Education.pdf
sanikaaconsultancy
 
Birth certificate council Koblenz 2012-2020.pdf
Birth certificate council Koblenz 2012-2020.pdfBirth certificate council Koblenz 2012-2020.pdf
Birth certificate council Koblenz 2012-2020.pdf
Astrid Gerhard
 
Pieter Stalenhoef’s ProfPieter Stalenhoef’s Professional Highlights and Indus...
Pieter Stalenhoef’s ProfPieter Stalenhoef’s Professional Highlights and Indus...Pieter Stalenhoef’s ProfPieter Stalenhoef’s Professional Highlights and Indus...
Pieter Stalenhoef’s ProfPieter Stalenhoef’s Professional Highlights and Indus...
WilliamClack2
 
Preparing-Students-for-the-Future-The-Power-of-CBSE-in-Baner-Schools.pdf
Preparing-Students-for-the-Future-The-Power-of-CBSE-in-Baner-Schools.pdfPreparing-Students-for-the-Future-The-Power-of-CBSE-in-Baner-Schools.pdf
Preparing-Students-for-the-Future-The-Power-of-CBSE-in-Baner-Schools.pdf
sanikaaconsultancy
 
minna n4 sach bai tap - tiengnhadongian.pdf
minna n4 sach bai tap - tiengnhadongian.pdfminna n4 sach bai tap - tiengnhadongian.pdf
minna n4 sach bai tap - tiengnhadongian.pdf
Tiếng Nhật Đơn giản
 
Group-4-report-_20250409_180212_0000.pdf
Group-4-report-_20250409_180212_0000.pdfGroup-4-report-_20250409_180212_0000.pdf
Group-4-report-_20250409_180212_0000.pdf
joankatevallecervald
 
Consistency Leads to Success : Consistency Leads to Success
Consistency Leads to Success : Consistency Leads to SuccessConsistency Leads to Success : Consistency Leads to Success
Consistency Leads to Success : Consistency Leads to Success
CorporateSecretary6
 
linux_admin_course_full_for beginers.pptx
linux_admin_course_full_for beginers.pptxlinux_admin_course_full_for beginers.pptx
linux_admin_course_full_for beginers.pptx
tejas2429
 
1- Rules of Tajweed Qalqalah_Letters.pptx
1- Rules of Tajweed Qalqalah_Letters.pptx1- Rules of Tajweed Qalqalah_Letters.pptx
1- Rules of Tajweed Qalqalah_Letters.pptx
sammk2023
 
MERI-Cultivating-Global-Professionals.pdf
MERI-Cultivating-Global-Professionals.pdfMERI-Cultivating-Global-Professionals.pdf
MERI-Cultivating-Global-Professionals.pdf
anchal600585
 
Visionary of the Year Leading the Charge for Sustainability.pdf
Visionary of the Year  Leading the Charge for Sustainability.pdfVisionary of the Year  Leading the Charge for Sustainability.pdf
Visionary of the Year Leading the Charge for Sustainability.pdf
ciotimespublication
 
The Role of Philanthropy in Strengthening Communities.pdf
The Role of Philanthropy in Strengthening Communities.pdfThe Role of Philanthropy in Strengthening Communities.pdf
The Role of Philanthropy in Strengthening Communities.pdf
Steven Bauer, M.D.
 
Proposal Entrepreneurial Summit 2024 (1).pptx
Proposal Entrepreneurial Summit 2024 (1).pptxProposal Entrepreneurial Summit 2024 (1).pptx
Proposal Entrepreneurial Summit 2024 (1).pptx
eee Lastsss
 
2025 Job-ready Program in Digital Marketing.pdf
2025 Job-ready Program in Digital Marketing.pdf2025 Job-ready Program in Digital Marketing.pdf
2025 Job-ready Program in Digital Marketing.pdf
himanshu1223344
 
Grey Modern Professional Business Project Presentation.pptx.pptx
Grey Modern Professional Business Project Presentation.pptx.pptxGrey Modern Professional Business Project Presentation.pptx.pptx
Grey Modern Professional Business Project Presentation.pptx.pptx
NURSYUHADABINTISAIDY
 
Bài Tập Tiếng Anh 7-Tập 1 (Mai Lan Hương - Hà Thanh Uyên).pdf
Bài Tập Tiếng Anh 7-Tập 1 (Mai Lan Hương - Hà Thanh Uyên).pdfBài Tập Tiếng Anh 7-Tập 1 (Mai Lan Hương - Hà Thanh Uyên).pdf
Bài Tập Tiếng Anh 7-Tập 1 (Mai Lan Hương - Hà Thanh Uyên).pdf
minhvy680
 
medical coding courses in sao tome and principe.pdf
medical coding courses in sao tome and principe.pdfmedical coding courses in sao tome and principe.pdf
medical coding courses in sao tome and principe.pdf
stskills iim
 
The Ultimate Guide to Startup Jobs in Jaipur – High-Growth Roles in 2025..pdf
The Ultimate Guide to Startup Jobs in Jaipur – High-Growth Roles in 2025..pdfThe Ultimate Guide to Startup Jobs in Jaipur – High-Growth Roles in 2025..pdf
The Ultimate Guide to Startup Jobs in Jaipur – High-Growth Roles in 2025..pdf
vinay salarite
 
SCIENCE QUIZ CLASS III for 111111111.pptx
SCIENCE QUIZ CLASS III for 111111111.pptxSCIENCE QUIZ CLASS III for 111111111.pptx
SCIENCE QUIZ CLASS III for 111111111.pptx
VickyRathi2
 
Power of audit and its implementation and mane.pptx
Power of audit and its implementation and mane.pptxPower of audit and its implementation and mane.pptx
Power of audit and its implementation and mane.pptx
ShomoyEkhonAmader
 
Empowering-Little-Learners-Innovation-in-MIS-Nursery-Education.pdf
Empowering-Little-Learners-Innovation-in-MIS-Nursery-Education.pdfEmpowering-Little-Learners-Innovation-in-MIS-Nursery-Education.pdf
Empowering-Little-Learners-Innovation-in-MIS-Nursery-Education.pdf
sanikaaconsultancy
 
Birth certificate council Koblenz 2012-2020.pdf
Birth certificate council Koblenz 2012-2020.pdfBirth certificate council Koblenz 2012-2020.pdf
Birth certificate council Koblenz 2012-2020.pdf
Astrid Gerhard
 
Pieter Stalenhoef’s ProfPieter Stalenhoef’s Professional Highlights and Indus...
Pieter Stalenhoef’s ProfPieter Stalenhoef’s Professional Highlights and Indus...Pieter Stalenhoef’s ProfPieter Stalenhoef’s Professional Highlights and Indus...
Pieter Stalenhoef’s ProfPieter Stalenhoef’s Professional Highlights and Indus...
WilliamClack2
 
Preparing-Students-for-the-Future-The-Power-of-CBSE-in-Baner-Schools.pdf
Preparing-Students-for-the-Future-The-Power-of-CBSE-in-Baner-Schools.pdfPreparing-Students-for-the-Future-The-Power-of-CBSE-in-Baner-Schools.pdf
Preparing-Students-for-the-Future-The-Power-of-CBSE-in-Baner-Schools.pdf
sanikaaconsultancy
 

LECTURE 3 LOOPS, ARRAYS.pdf

  • 1. 6.092: Intro to Java 3: Loops, Arrays
  • 2. Assignment 2 Foo Corporation needs a program to calculate how much to pay their employees. 1. Pay = hours worked x base pay 2. Hours over 40 get paid 1.5 the base pay 3. The base pay must be no less than $8.00 4. The number of hours must be no more than 60
  • 3. Frequent Issues (I) The signature of the main method cannot be modified. public static void main(String[] arguments) { ... }
  • 4. Frequent Issues (II) Return values: if you declare that the method is not void, then it has to return something! public static int pay(double basePay, int hours) { if (basePay < 8.0) return -1; else if (hours > 60) return -1; else { int salary = 0; ... return salary } }
  • 5. Frequent Issues (III) Don't create duplicate variables with the same name public static int pay(double basePay, int hours) { int salary = 0; // OK … int salary = 0; // salary already defined!! … double salary = 0; //salary already defined!! … }
  • 6. class WeeklyPay { public static void pay(double basePay, int hours) { if (basePay < 8.0) { System.out.println("You must be paid at least $8.00/hour"); } else if (hours > 60) { System.out.println("You can't work more than 60 hours a week"); } else { int overtimeHours = 0; if (hours > 40) { overtimeHours = hours - 40; hours = 40; } double pay = basePay * hours; pay += overtimeHours * basePay * 1.5; System.out.println("Pay this employee $" + pay); } } public static void main(String[] arguments) { pay(7.5, 35); pay(8.2, 47); pay(10.0, 73); } }
  • 7. What we have learned so far ● Variables & types ● Operators ● Type conversions & casting ● Methods & parameters ● If statement
  • 8. Today’s Topics ● Good programming style ● Loops ● Arrays
  • 10. Good programming style The goal of good style is to make your code more readable. By you and by others.
  • 11. Rule #1: use good (meaningful) names String a1; int a2; double b; // BAD!! String firstName; // GOOD String lastName; // GOOD int temperature; // GOOD
  • 12. Rule #2: Use indentation public static void main (String[] arguments) { int x = 5; x = x * x; if (x > 20) { System.out.println(x + “ is greater than 20.”); } double y = 3.4; } Have a demo with no indentation Ctrl-shift-F to auto-format the file
  • 13. Rule #3: Use whitespaces Put whitespaces in complex expressions: // BAD!! double cel=fahr*42.0/(13.0-7.0); // GOOD double cel = fahr * 42.0 / (13.0 - 7.0);
  • 14. Rule #3: Use whitespaces Put blank lines to improve readability: public static void main (String[] arguments) { int x = 5; x = x * x; if (x > 20) { System.out.println(x + “ is > 20.”); } double y = 3.4; }
  • 15. Rule #4: Do not duplicate tests if (basePay < 8.0) { ... } else if (hours > 60) { ... } else if (basePay >= 8.0 && hours <= 60) { ... }
  • 16. Rule #4: Do not duplicate tests if (basePay < 8.0) { ... } else if (hours > 60) { ... } else if (basePay >= 8.0 && hours <= 60){ ... } BAD
  • 17. Rule #4: Do not duplicate tests if (basePay < 8.0) { ... } else if (hours > 60) { ... } else { ... }
  • 18. Good programming style (summary) Use good names for variables and methods Use indentation Add whitespaces Don't duplicate tests
  • 20. Loops static void main (String[] arguments) { System.out.println(“Rule #1”); System.out.println(“Rule #2”); System.out.println(“Rule #3”); } What if you want to do it for 200 Rules?
  • 21. Loops Loop operators allow to loop through a block of code. There are several loop operators in Java.
  • 22. The while operator while (condition) { statements }
  • 23. The while operator int i = 0; while (i < 3) { System.out.println(“Rule #“ + i); i = i+1; } Count carefully Make sure that your loop has a chance to finish.
  • 24. The for operator for (initialization;condition;update){ statements }
  • 25. The for operator for (int i = 0; i < 3; i=i+1) { System.out.println(“Rule #“ + i); } Note: i = i+1 may be replaced by i++
  • 26. S } Branching Statements break terminates a for or while loop break; ystem.out.println(“Rule #” + i); for (int i=0; i<100; i++) { if(i == 50)
  • 27. r Branching Statements continue skips the current iteration of a loop and proceeds directly to the next iteration fo (int i=0; i<100; i++) { if(i == 50) continue; System.out.println(“Rule #” + i); }
  • 28. Embedded loops for (int i = 0; i < 3; i++) { for (int j = 2; j < 4; j++) { System.out.println (i + “ “ + j); } } Scope of the variable defined in the initialization: respective for block
  • 30. Arrays An array is an indexed list of values. You can make an array of any type int, double, String, etc.. All elements of an array must have the same type.
  • 31. Arrays .. 0 1 2 3 .. n-1
  • 32. Arrays Example: double [ ] 5.0 2.44 9.01 1.0 -9.9 .. 0 1 2 3 .. n-1
  • 33. Arrays The index starts at zero and ends at length-1. Example: int[] values = new int[5]; values[0] = 12; // CORRECT values[4] = 12; // CORRECT values[5] = 12; // WRONG!! compiles but // throws an Exception // at run-time Have a demo with runtime exception
  • 34. Arrays An array is defined using TYPE[]. Arrays are just another type. int[] values; // array of int int[][] values; // int[] is a type
  • 35. Arrays To create an array of a given size, use the operator new : int[] values = new int[5]; or you may use a variable to specify the size: int size = 12; int[] values = new int[size];
  • 36. Array Initialization Curly braces can be used to initialize an array. It can ONLY be used when you declare the variable. int[] values = { 12, 24, -23, 47 };
  • 37. Quiz time! Is there an error in this code? int[] values = {1, 2.5, 3, 3.5, 4};
  • 38. Accessing Arrays To access the elements of an array, use the [] operator: values[index] Example: int[] values = { 12, 24, -23, 47 }; values[3] = 18; // {12,24,-23,18} int x = values[1] + 3; // {12,24,-23,18}
  • 39. The length variable Each array has a length variable built-in that containsthe length of the array. int[] values = new int[12]; int size = values.length; // 12 int[] values2 = {1,2,3,4,5} int size2 = values2.length; // 5
  • 40. String arrays A side note public static void main (String[] arguments){ System.out.println(arguments.length); System.out.println(arguments[0]); System.out.println(arguments[1]); }
  • 42. Looping through an array Example 1: int[] values = new int[5]; for (int i=0; i<values.length; i++) { values[i] = i; int y = values[i] * values[i]; System.out.println(y); }
  • 43. Looping through an array Example 2: int[] values = new int[5]; int i = 0; while (i < values.length) { values[i] = i; int y = values[i] * values[i]; System.out.println(y); i++; }
  • 44. Summary for today 1. Programming Style 2. Loops 3. Arrays
  • 45. Assignment 3 A group of friends participate in the Boston Marathon. Find the best performer. Find the second-best performer.
  • 46. MIT OpenCourseWare http://ocw.mit.edu 6.092 Introduction to Programming in Java January (IAP) 2010 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.