1 Introduction To Programming in Java p3 v2 - 5
1 Introduction To Programming in Java p3 v2 - 5
3: Loops, Arrays
...
else {
int salary = 0;
...
return salary
} // end if’s
previous Assignment
Method to print pay based on base pay and hours worked
Assignment solution
public 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;
} // end of successive if’s
double pay = basePay * hours;
pay = pay + overtimeHours * basePay * 1.5;
System.out.println("Pay this employee $" + pay);
} // end of successive if’s
} // end of pay method
public static void main( String[] arguments ) {
pay(7.5, 35);
pay(8.2, 47);
pay(10.0, 73);
} // end main method
} // end of class WeeklyPay
• Operators
• If statement
Today’s Topics
• Good programming style
• Loops, cycles,
• Arrays
• Reduce the effort required to read and understand the source code.
• Improve the appearance of the source code, for example, by not allowing excessively long names or
unclear abbreviations.
String a1;
int a2;
double b;
A = b * h;
String firstName;
String lastName;
int temperature;
// BAD!!
double cel=fahr*42.0/(13.0-7.0);
// GOOD
double cel = fahr * 42.0 / ( 13.0 – 7.0 );
int x = 5;
x = x * x;
if (x > 20) {
System.out.println(x + “ is > 20.”);
}
double y = 3.4;
}
BAD
GOOD
https://www.thinkful.com/blog/coding-best-practices/
https://www.browserstack.com/guide/coding-standards-best-practices
• Use indentation.
In next program highlights the sections for data request, calculations or data processing, and display of results.
Reading data is done in the main method.
9 omitted lines
10
11 // get input data
12 solicitaDatos();
13 nom = readThis.readLine();
14 cal1 = Integer.parseInt(readThis.readLine());
15 cal2 = Integer.parseInt(readThis.readLine());
16
6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 5
OOP class notes Ene – Abr 2023 26/12/22
17 // Process information through operations
18 prom = procesaDatos(cal1, cal2);
19
20 // Display results
21 muestraResulta2(nom, prom);
22
23 }// fin del main
24
25 public static void solicitaDatos() {
26 System.out.println(" Introduce los datos en el orden mostrado");
27 System.out.println(" Sepáralos mediante un intro/enter");
28 System.out.println(" 1. dame tu nombre");
29 System.out.println(" 2. dame tu primer calificacion");
30 System.out.println(" 3. dame tu segunda calificacion");
31 }
32
33 public static double procesaDatos(int x1, int x2) {
34 double ret_prom;
35 ret_prom = (x1+x2)/2.0;
36 return ret_prom;
37 }
38
In the following program, the data request section is highlighted, since for each variable there is a method.
Reading data is done in child methods or functionality.
9 omitted lines
10
11 // get input data
12 nom = solicitaNombre();
13 cal1 = solicitaCal1();
14 cal2 = solicitaCal2();
Remember that, for the moment, methods can return only one value
if you need to do some calculus, and every calculus have assigned a variable, for every calculus you need one
method.
11 omitted lines
12
17 sum = toSum( num1, num2 );
18 subt = toSubtract( num1, num2 );
19 multip = toMultiply( num1, num2 );
20
21 omitted lines
continue below
5. Make a program to determine if three different values representing sides can form a triangle. Suppose we
have variables A, B, and C, and each representing one side. Which of the following datasets allows us to
form a triangle and why?
Conj. A B C
1 5 10 3
2 5 10 5
3 5 10 7
What is it about that set (which allows us to form a triangle) that the other two don't have?
6. Make a program that calculates and displays on screen the daily wage of a worker who receives $ 11.00
for each hour of work and $ 19.55 for each overtime. The normal working day consists of 8 hours, above
that it is considered as overtime. If the working day exceeds 13 hours of work, 10% will be withheld as
savings. Use printf to limit decimals.
Clues. Review next data sets. For 7 worked hours, the daily wage is $77.00
For 12 worked hours, the daily wage is $166.20
For 15 horked hours, the daily wage is $202.365
7. Make a program that allows students of a university to calculate the payment of their monthly payments
based on the following criteria: a) when advancing monthly payments, a 10% discount will be applied. b) In
late monthly payments, an extra charge of 10% will be applied. c) The payment of the monthly payment of
the current month does not carry a discount but there is no extra charge. The amount of the monthly
payment is $ 650.00. Use printf to limit decimals.
Clues. Payment of an advance monthly payment and that of the current month, the total is $1,235.00.
Payment of a late monthly payment and that of the current month, the total is $1,365.00.
Payment of two late monthly payments and one for the current month and one in advance, the
total is $2,665.00
8. En una empresa se usa el salario mínimo diario ($207.5) como base para calcular el pago a sus
empleados. Se considera que una jornada normal de trabajo consta de 8 hrs diarias de trabajo. Para
obtener la tarifa por hora se toma el salario mínimo diario y la jornada normal de trabajo. El pago por hora
trabajada es 4 veces la tarifa por hora. La cantidad de horas trabajadas para jornadas normales de trabajo
es de 40 horas a la semana, arriba de esa cantidad se consideran como tiempo extra. Las horas extras se
pagan a 1.35 veces el pago por hora trabajada. Los impuestos se calculan en base a lo siguiente:
Usar Métodos. Dos y tres métodos, 60 de calif. Cuatro y cinco métodos, 75 de calif. 6 y 7 métodos, 100 de calif
Pistas:
Con 20 horas de trabajo el salario bruto es de $2,075, los impuestos son de $0.0 y el salario neto es de $2,075.
Con 40 horas trabajadas el salario bruto es de $4,150, los impuestos son de $ 213.75 y el salario neto es de $3,936.25.
Con 52 horas trabajadas el salario bruto es de $5,830.75, los impuestos son de $ 636.59 y el salario neto es de $5,194.16.
Con 7 horas de trabajo el programa no puede continuar y todos los resultados están en cero.
Con 63 horas trabajadas el programa no puede continuar y todos los resultados están en cero.
Loops
When working with repetitive loops, we are often interested in knowing in which repetition we are in. To count
repetitions, we use a variable called counter.
2. Within the repetitive cycle, we increase the variable in one or other number that be convenient
Accumulator variable
It is similar to the counter. It is initialized to zero and is incremented in each repetition with different values.
The result is that the variable accumulates the sum of the values added in each repetition:
Count carefully.
Make sure that your loop has a chance to finish. Do not forget to increase the variable used in the condition,
otherwise the loop will never end!
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop
instead of the top. Therefore, the statements within the do block are always executed at least once.
Count carefully.
Make sure that your loop has a chance to finish. Do not forget to increase the variable used in the condition,
otherwise the loop will never end!
When you don't know exactly how many times you want to repeat a block of code, use the do-while loop this way
public class Do_WhileExample2 {
public static void main(String[] args) {
Scanner read = new Scanner( System.in );
int resp = 0; // response
do {
System.out.println(“Print this” );
System.out.println(“Do you want repeat? 1=yes / other number = not” );
resp = read.nextInt();
} while ( resp == 1 ); // end while
read.close();
} // end main method
} // end class Do_WhileExample2
When you know exactly how many times you want to loop through a block of code, use the for loop instead of a
while loop or do-while loop.
} // end for
initialization is executed (only one time) before the execution of the code block.
update is executed (every time) after the code block has been executed.
The sequence is: 1. initialization, 2. condition, 3. statements, 4. update; and repeat steps 2, 3 and 4 until
condition is false.
1. Develop the program that allows to calculate the sum of N different numbers and that shows the result of
the sum. Use loop while in one program and loop do-while in other program.
Clues: with numbers 65, 12, -15, 3, 25, -31, the sum of all is 59 and 6 numbers were added.
2. Develop the program that calculates the sum of the first N integer numbers and shows how many numbers
were added. The program must show the next number to add and the user will decide whether to add it or
not, if the user responds negatively, the program execution will end. Make a version with while loop and
another version with do-while loop.
Clues: with numbers 1, 2, 3, 4, 5, 6, 7, the sum of all them is 28 and 7 numbers were added.
3. Develop the program that allows you to enter N grades from a group of students and add them up to
calculate the average of the group. You should also determine and display on screen how many are
passed and how many are failed. The minimum pass is 70. Use loop for.
Clues: with grades 59, 78, 67, 91, 84, 77, the average is 76, and 4 passed and 2 failed.
4. Program for a grocery store. The program allows us to enter the prices of the items that a customer is
going to buy and shows the total to be paid and the number of items sold. At the end it must display the
total of all payments and the number of custumers of the day. Use loop while or do-while.
Clues: with prices 23.45, 35.80, 10.35, 59.10, the total to pay is 128.70
Branching Statements
break terminates a loop
System.out.println(“Num ” + i );
Branching Statements
continue skips the current iteration of a loop and proceeds directly to the next iteration
do { {
if( i == 5 ) { if( i == 5 ) {
continue; } continue; }
System.out.println(“Num ” + i ); System.out.println(“Num ” + i );
i++; i++;
System.out.println(“Num ” + i );
in the programs above change the condition from i == 5 to i % 5 == 0 and the limit from 10 to 100, what will the
programs do?
2. Make a program for a tire store that allows you to enter an existing value of tires (suppose 250) and that
simulates sales through a count that decreases the number of tires one by one, and that when it reaches a
threshold or defined value (suppose 35), sends a message that the number of tires in stock is very low.
Use break to end the cycle.
6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 15
OOP class notes Ene – Abr 2023 26/12/22
3. Make a program that will display a countdown by one from 50, and numbers that are multiples of 7 will not
show. Use Continue to skip these numbers
4. Program that prints only the prime numbers from 1 to 100. Use Continue to skip numbers
6. Make a program that generates a random number from 1 to 100 and displays on the screen whether or not
it is even; whether or not it is a multiple of 5; whether or not it is a multiple of 11; whether or not is prime.
See this and this and this.
7. Write a program that displays numbers from 2 to 50. Using random numbers, generate three random
divisors from 2 to 12, and determine how many numbers are divisible (the quotient equals zero) with each
of those three divisors.
8. Select any program, edit it and remove the word “public” from the class and change the name of the class
to let's say “VerQuePasa”. compile. Is there an error because the file name and the class name are
different? what is the name of the .class file?
9. Make a program that displays the multiplication table of any number; example in case it is the one of 2
2* 1 = 2
2* 2 = 4
.
.
2* 10 = 20
8. Make the necessary changes to the above algorithm so that it displays the divide table; example in case it
is the one of 2
2/2=1
4/2=2
6/2=3
.
.
20 / 2 = 10
9. Carry out the desktop test of the following algorithm in Pseint and draw a conclusion in such a way that it
allows you to elaborate the wording of the problem that is solved with this algorithm. Finally, make the
corresponding java program
10. Carry out the desktop test of the following algorithm in Pseint and draw a conclusion in such a way that it
allows you to elaborate the wording of the problem that is solved with this algorithm. Finally, make the
corresponding java program
11. Write a program that prints the multiplication tables from 1 to 9 in the order shown.
Arrays
An array is an indexed list of values. You can make an array of any type, may be int, double, String, etc.
0 1 2 3 ... n-1
...
Example: double [ ]
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
Arrays
An array is defined using TYPE [ ].
Arrays
To create an array of a given size, use the operator new :
int[ ] values = new int [5]; //values has 5 elements
or you may use a variable to specify the size:
int size = 12; int[ ] values = new int [size]; //values has 12 elements
Array Initialization
Curly braces can be used to initialize an array.
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 and the index number: values[index]
Example:
int[ ] values = { 12, 24, -23, 47 };
values[3] = 18; // it refers to element 3 which contains to 47 and will be changed by 18
int x = values[1] + 3; // refers to element 1, this is 24, and 3 will be added to it
// and x = 27 but values[1] still is 24
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]);
}
c) import java.util.Arrays; 1
1 import java.util.Scanner;
2
3 public class Ejemplo1Arreglos { //begin class
4 public static void main (String[]args) { //begin main
5 int i; // counter on each for loop
6
7 int [] valores1 = new int [5]; //array of size 5
8 valores1 [0] = 10;
9 valores1 [4] = 40;
10 valores1 [5] = 25; /*error! an array of length 5 its last element is 4,
11 so we can modify size to 6 (in line 7) or change the index to 1, 2, or 3 (in line 10) */
12
2. Program that inserts random values from 0 to 99 into an array of size N, to then display the numbers on
the screen. See https://www.w3schools.com/java/java_math.asp
3. Program that inserts random values from 20 to 70 into an array of size N, to then display the numbers on
the screen. See https://carloszr.com/como-generar-numero-aleatorio-en-rango-de-valores-en-java/
4. Create a program that allows you to input integer numeric values to a one-dimensional array and average
them (it will serve as the basis for the variance and standard deviation).
5. Write a program that inserts random values from 0 to 99 into an array of size N, sort them lower to higher,
finally display values sorted. Use bubble sort. See
https://www.wikiwand.com/es/Ordenamiento_de_burbuja
6. Use arrays. There are the final grades of a school group, one grade per student; make a program that
calculates the group average and says how many grades are higher than the average and how many are
lower than the average.
7. Program that uses two arrays, in the first N grades from 0 to 100 are introduced, in the second the points
that each grade represents are stored (pts = grade *.35). At the end, it shows each grade and the points
obtained.
8. Write a program that allows you to input random integer values from 0 to 99 to two one-dimensional arrays
and add the values that are in the same positions in both arrays and store the sum in a third array and
display the values of all three arrangements.
9. Develop a program that allows you to calculate the variance and the sample standard deviation of a
i=n
∑ (x i− ̄x )2
2 i =1
population of a set of numbers; the variance formula is s= where ̄x is the arithmetic
n−1
mean or average of the set of numbers. Review procedure here.
Here you have to divide the entire process into parts. 1st. The mean or average will be calculated. 2nd.
Each of the subtractions of each data will be made with the average, and they are saved. 3rd. The square
of each subtraction is calculated and the results are saved. In that same step you can perform the sum of
all squares. 4th. Finally, the variance is calculated and then the standard deviation.
10. Program that in an mxn matrix, where m=n and 2 <= m <= 5, inserts random values from 10 to 99, to then
display the numbers on the screen in matrix form. Validate that the value of m complies with the restriction
of 2 <= m <= 5.
Matrix 3x3 Matrix 4x4 Matrix 5x5
00 01 02 00 01 02 03 00 01 02 03 04
10 11 12 10 11 12 13 10 11 12 13 14
20 21 22 20 21 22 23 20 21 22 23 24
30 31 32 33 30 31 32 33 34
40 41 42 43 44
The value of m will represent the maximum number of rows and since m=n, the matrix will have n
columns, making the number of rows and columns equal, and therefore, it is square; on the other hand, we
do the traversal of each of the positions of a matrix with the index i for the rows and j for the columns.
we will use the variable lim_i to identify the maximum number of rows (m) and the variable lim_j to identify
the maximum number of columns (n).
11. Write the program that allows you to input random values from 100 to 399 to a matrix of mxn, where m=n
and 3 <= m <= 9. Identify which numbers occupy each corner of the matrix. Validate that the value of m
complies with the restriction of 3 <= m <= 9.
12. Write the program that allows you to input random values from 0 to 99 to a matrix of mxn, where where
m=n and 3 <= m <= 9. Calculate the sum of the numbers that lie on the periphery of the matrix. Validate
that the value of m complies with the restriction of 3 <= m <= 9.
13. Write the program that allows you to input random values from 0 to 99 to a matrix of mxn, where m=n and
3 <= m <= 9 and that adds the numbers that are a) on the main diagonal and then b ) those of the minor
diagonal and showing each result
6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 22
OOP class notes Ene – Abr 2023 26/12/22
Assignment 3
A group of friends participate in the Boston Marathon.
This teaching material is based on 6.092 Introduction to Programming in Java, January (IAP) 2010, which is available at MIT OpenCourseWare:
http://ocw.mit.edu, therefore has the Creative Commons license mentioned in https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode
For information about citing 6.092 Introduction to Programming in Java or yours Terms of Use, visit: http://ocw.mit.edu/terms.