Exam Announcements Techniques of Programming CSCI 131 Exam #2 REVIEW 2D Arrays, FuncCons, and Recursions Exam noCces: -‐ closed book, closed notes, no electronics. -‐ cell phones in backpacks. -‐ backpacks at front of room or end of row. -‐ bring pencils and erasers. 1 1 1) A funcCon, someFunc, has two formal parameters named alpha and beta, both of type int. The funcCon returns a boolean value. Write an appropriate signature for the funcCon. public static boolean someFunc(int alpha, int beta)
3 3 3) Given the funcCon definiCon: public staCc int mystery( double someVal ) { if (someVal > 2.0) { return 3 * (int)someVal; } else { return 0; } } What is the value of the expression mystery (4.2) ? Value is 12 (converts to int first, then multiply by 3)
5 5 2 2 2) Consider the funcCon definiCon: public staCc int demo (int intVal, double floatVal) { intVal = intVal *2; floatVal = (double)intVal + 3.5; return intVal; } Suppose the caller has variables myInt and myFloat whose values are 20 and 4.8 respecCvely. What are the values of myInt and myFloat a]er return from the following funcCon call? myInt = demo(myInt, myFloat); myInt will be 40 (return value is myInt doubled) myFloat will be 4.8 (value parameter, so func>on is irrelevant) 4) a) Write a funcCon that returns 10.0 raised to the integer power specified by parameter n. (Recall that 10.0 raised to power 0 is 1.0, 10.0 raised to power 1 is 10.0, 10.0 raised to power 2 is 100.0, and so on.) The funcCon should match the following signature. You may not use any Math library funcCons – you should instead compute the answer using a loop. public sta>c double tenToThePower(int n) { sta>c double enToThePower(int n) public double result = 1t.0; { if (n < 0) d
ouble for result (int i = 01; .0; i > n; i-‐-‐) // count down to neg. num f or (int i = 0; riesult result / 10; < n; i=++) else result = result * 10; for (int i = 0; i < n; i++) // count up to pos. number r eturn result; result = result * 10; } return result; } 4 4 6 6 5) Given the following array and variable declaraCons: int[] ssn = new int[100]; int numPaCents; Write a loop that reads from the keyboard the social security number for each of the paCents and stores the values in the appropriate posiCon in the appropriate array. Stop reading numbers once the user enters 0 or a negaCve number. You can assume the user will enter at least one valid social security number and no more than 100 of them. StdOut.println("Please enter SSNs (use 0 to stop): ");
b) Write a single JAVA statement that invokes the above funcCon to compute 10.0 to the power 8 and store the answer in the variable b. double b = tenToThePower(8); (or, if we assume variable b is already declared…) b = tenToThePower(8); int count = 0;
int num = StdIn.readInt(); // priming read
while (num > 0) {
ssn[count] = num;
count++;
num = StdIn.readInt(); // read next number
}
7 7 8 8 6) Given the declaraCon int[][] checkers = new int[8][8]; a) Write a statement that will store the number five in the 2nd row, 3rd column of the array. checkers[1][2] = 5; // 0 is first row, 1 is second row, etc.
b) Write JAVA code to store the numbers 1-‐8 in the first row, 9-‐16 in the second row, 17-‐24 in the third row, and so on. for (int row = 0; row < 8; row++) {
int num = 1; // holds number to put in next cell
7) Write a funcCon called arrayRev that reverses an array of integers. The funcCon should take two parameters, source and desCnaCon, both of which have an appropriate type for an array of integers. The funcCon does not return anything. The funcCon should put the last integer of source into the first posiCon in desCnaCon, the next-‐to-‐last integer of source into the second posiCon in desCnaCon, and so on. You can assume both arrays are the same size. public sta>c void arrayRev(int[] source, int[] des>na>on) { for (int i = 0; i < source.length; i++) { des>na>on[i] = source[source.length-‐1-‐i]; // des>na>on[i] is the i^th item of des>na>on // source[n] is one past the last item of source // source[n-‐1] is the last item of source // source[n-‐1-‐i] is the i^th item from the last of src } } for (int col = 0; col < 8; col++) {
for (int row = 0; row < 8; row++) // each row counts for 8, each col counts for 1, plus
for (int col = 0; col < 8; col++) {
// one extra so it starts at 1 instead of 0
checkers[row][col] = num;
checkers[row][col] = row*8 + col + 1;
num++;
} }
} 9 9 8) Suppose the string variable login contains a student's login name in typical Holy Cross format (e.g. "jqsmit17"). Write a snippet of code that assigns the appropriate values to the first, middle, and last variables. For example, if login is "jqsmit17", then the code should assign first to be the leoer 'j', it should assign middle to be the leoer 'q', and it should assign last to be the word "smit". You can assume the login has exactly the format shown in this example (2 iniCals, 4 leoers, then 2 digits). String login;
char first, middle;
String last;
login = StdIn.readString();
// assigns login to be something like "jqsmit17" // your code here
first = login.charAt(0); // letter 0 is first initial
middle = login.charAt(1); // letter 1 is second initial
last = login.substring(2, 6); // start at 2, go up to not including 6
11 11 10 10 9) Write a funcCon that checks if a given two arrays of integers have idenCcal contents. The funcCon should have the following signature: public staCc boolean idenCcalLists(int[] one, int[] two) The funcCon should return true only if the two lists have the same contents. public static boolean identicalLists (int[] one, int[] two) {
if (one.length != two.length)
return false; // different len, must not be identical
for (int i = 0; i < one.length; i++)
if (one[i] != two[i])
return false; // mismatch, not identical
return true; // if loop finishes, must be identical
}
12 12 10) Below are snippets of code that are trying to replace each of the leading 1 numbers in an integer array with a 3. For each loop, say whether it is correct and explain why. int[] name = {1,1,1,1,2,2,2}; int[] name = {1,1,1,1,2,2,2}; int ct = 0; int ct = 0; while (name[ct] == 1) { while (name[ct] == 1) { ct++; name[ct] = 3; name[ct] = 3; ct++; } } The Left loop is correct (starts by checking name[0], then replaces name[0], then moves to count=1). Right loop is broken because after checking that name[0] is a 1, it then replaces name[1], which might be anything), but it never changes name[0].
13 13 public staCc void fix (double rad) { StdOut.println("The perimeter of the circle " + "with radius " + rad + " is " + (2 * Math.PI * rad)); } b) Rewrite lines 6-‐12 of the main() funcCon using two disCnct calls to your funcCon, fix() to replace lines 6-‐8, and 10-‐12. public static void main(String[] args) {
double radius = 52.0;
fix (radius);
fix ( 31.0);
} 15 15 11) Consider the following program: public class Circle { // line 1
// line 2
public static void main (String[] args) { // line 3
double radius = 52.0; // line 4
// line 5
StdOut.println ("The perimeter of the circle " + // line 6
"with radius " + radius + " is " + // line 7
2 * Math.PI * radius); // line 8
// line 9
StdOut.println ("The perimeter of the circle " + // line 10
"with radius " + 31.0 + " is " + // line 11
2 * Math.PI * 31.0); // line 12
} // line 13
} // line 14
a) NoCce that the lines 6-‐8, and 10-‐12 have a similar paoern of code. Write a funcCon, fix() that captures this similarity, so that each of these sets of 3 lines can be replaced with a single call to fix(). Your funcCon should have only one parameter and should not return a value. 14 14 12) Write a program that inputs a series of month names and temperatures from a file, and outputs a bar chart (using stars) of the temperatures. The month name should be printed to the le] of the corresponding bar. You can assume all of the month names have 3 characters and all of the temperatures are in the range 0 to 120. Because it is hard to display 120+ characters wide on the screen, you should have each star (the character '*') represent 3 degrees. That way, the bars will be at most 40 characters wide plus the labels. An example is shown below. Note how the temperatures are rounded to the nearest appropriate number of stars. The input file is named "temps.dat". Use a loop to process the input file. Write a funcCon to help you if you like. For example, if the input file contained: Jan 5 Mar 20 May 105 Dec 35 Then the output of the program should look like this: Temperatures (each star represents 3 degrees) Jan ** Mar ******* May ********************** Dec ************ 16 16 13) Assume two arrays of the same length have already been declared an iniCalized. The first array, names, contains student names. The second array, ages,contains the corresponding age of each of those students. (a) Write code to print out the name and age of every student, one per line, using the following format: Alice is 5 years old. Bob is 3 years old. Carol is 7 years old. Grace is 5 years old. public class Rev2 { // This function prints a month name, then a space, // then a series of n stars, then a newline. public static void printBar(String month, int n) { StdOut.print (month + " "); for (int i = 0; i < n; i++) StdOut.print("*"); StdOut.println(); } // PrintBar public static void main(String[] args) { String month; int temp; In inFile = new In ("temps.dat"); StdOut.println("Temperatures (each star represents 3 degrees)"); while (inFile.hasNextLine()) { // or... ! inFile.isEmpty() month = inFile.readString(); temp = inFile.readInt(); int numStars = (temp+1)/3; // we use n+1 to get it to round up in some cases instead of always down printBar(month, numStars); } // while not eof for (int i = 0; i < names.length; i++) {
StdOut.printf("%s is %d years old.\n", names[i], ages[i]);
}
} } 17 17 18 18 (b) Write code to instead print out only the names of the students younger than 6 years old, using the following format: Young students include: Alice Bob Grace. (c) Write a funcCon to count the number of students who are at least x years old and younger than y years old. Your funcCon should be named countAgeRange and it should have appropriate parameters and return type. public static int countAgeRange(int[] ages, int x, int y) { int count = 0; for (int i = 0; i < names.length; i++) { if (ages[i] >= x && ages[i] < y) { count++; } } return count; } StdOut.print("Young students include:");
for (int i = 0; i < names.length; i++) {
if (ages[i] < 6) {
StdOut.print(" " + names[i]);
}
}
StdOut.println(".");
19 19 (d) Write a funcCon named ageOfStudent that will find the age of a parCcular student, given a name. It should take three parameters: an array of names, an array of ages, and the name of the student being sought. For example, if invoked like this: int x = ageofStudent(names, ages, "Alice"); then the funcCon should return Alice's age based on the informaCon in the names and ages arrays. If the name "Alice" does not appear in the array, the funcCon should return -‐1 instead to indicate that the name could not be found. public static int ageOfStudent(String[] names, int[] ages, String target) { for (int i = 0; i < names.length; i++) { if (names[i].equals(target)) { return ages[i]; } } return -‐1; } 21 21 20 20
© Copyright 2026 Paperzz