COSC 111 MIDTERM 2 QUANTITATIVE SCIENCES COURSE UNION qscu.org Introductions Name, Major, Role in QSCU WHAT IS QSCU? How do I get involved? Weekly Meetings: Tuesday, 9:00-9:30am PST Discord - voice channel OPEN TO EVERYONE! (Snacks are sometimes provided) How do I stay in the loop? https://discord.gg/xH48R8K Facebook.com/ubcoqscu QSCU.org LET’S GET STARTED http://qscu.org/events/reviewmaterial/ 1. LOOPS (for, while nested fors, etc.) What is the output of the following code fragment? int num = 1, max = 20; while (num < max) { if (num%2 == 0) System.out.print(num + “ “); num++; } Answer: 2 4 6 8 10 12 14 16 18 Write a loop to print all the odd numbers from 1 to 99 (inclusive) Challenge: Answer this question without a % operator for(int i =1; i < 100; i++){ if(i %2 == 0){ System.out.println(i); } } Challenge: for(int i =1; i <= 99; i+=2){ System.out.println(i); } Transform the following while loop into an equivalent for loop. (Make sure it produces the same output) int num = 1; while (num < 20) { num++; System.out.println(num); } for(int i = 2; i <21; i ++){ System.out.print(i + “ “); } Increments then checks, because increment happens before the print we will print 20 Pretty cool answer from the class: for(int i = 1; i<20;) System.out.println(++i); Write a program that mimics a simple slot machine in which three numbers between 0 and 9 are randomly selected and printed side by side. Report to the user if all three of the numbers are the same, or if any two of the numbers are the same. Continue playing until the user chooses to stop. Assume the user gives valid input. Scanner scan = new Scanner(System.in); boolean play = true; while(play){ int r1 = (int) (Math.Random()*10); int r2 = (int) (Math.Random()*10); int r3 = (int) (Math.Random()*10); if( r1 == r2 && r2 == r3){ System.out.println(“all are the same”); } else if( (r1 == r2 && r2 != r3) || ( r1 == r3 && r2 != r3) || ( r2 == r3 && r1 != r3)){ //handles case where first 2 same //handles case where second 2 are same // handles case where first and last // helpful to draw out chart that i have //The else if condition could also be !(r1 != r2 && r2!=r3 && r1 != r3) System.out.println(“2 are the same”); } System.out.println(“would you like to play again? Enter any number for yes and -1 for no”); int check = scan.nextInt(); if(check == -1) play = false; } Convert the following for loop to use a foreach loop. int[] x = {1, 2, 5, 7}; for (int i = 0; i < x.length; i++) { System.out.println(x[i]); } Solution: for (int i : x) { System.out.println(i); } Create a for-each loop to output the following numbers from an array: Output: 12 13 14 44 int arr[]={12,13,14,44}; for(int i:arr){ System.out.println(i); } Convert the following for loop into a do-while loop: int sum = 0; for(int i = 0; i < 10; i++){ sum += i; System.out.println(sum); int i = 0; do { sum += i; System.out.println(sum); i++; } while (i < 10); Write a do-while loop that prints every number that is divisible by 3 between 1 to 100 inclusive int i = 0; do { if ( i % 3 == 0 ) { System.out.println(i); } i++; } while ( i <= 100 ); Write a do-while loop to print every element in numList where int [] numList = {1,2,3,4,5,6,7,8,9,10}; Answer: int i = 0; int [] numList = {1,2,3,4,5,6,7,8,9,10}; do { System.out.println(numList[i]); i++; } while (i < list.length); 2. METHODS Scope, primitive vs objects etc. What is a static method (“class method”)? What does the static keyword do to a method or variable? Static methods can only modify static variables. Any static variables or methods are shared by all instances of a class. So you can call a static method on two different objects of the same class, but you will be calling the same method. The important thing to note is that when you modify a static variable using a static method, that variable is changed for ALL instances of the class. 1) 2) 3) 4) Write the header to a method that takes input of an int, two doubles and returns a decimal number. Write the header to a method that takes a String as input and returns a String. Write the header to a method that takes no input and returns nothing. Write the header to a method that takes two integers and any number of doubles (but can accept more) and returns an array of decimal 1) public (double or float) foo (int a, double b, double c) 2) public String foo (String s) 3) public void foo () 4) (int a, int b, double c, double…d) technically double…d can take zero Method Overloading For each foo method what would be the output be? public public public Syntax void foo(double a, int b){System.out.print("A");} void foo(int a, double b, int c){System.out.print("B");} void foo(int a, int b, double... c){System.out.print("C");} error Answers: foo(1, 1); -> A or C depending foo(1, 2.0); -> error foo(1.0, 2); -> A foo(1, 2, 3); -> B foo(1, 2.0, 3); -> B foo(1, 2, 3.0); -> C foo(1, 2, 3, 4, 5); -> C Variable Scope Identify the error and suggest how to fix the following: public static void main(String[] args) { int n; n = 3; result = square(n); System.out.println(n + " squared is: " + result); n = 4; result = square(n); System.out.println(n + " squared is: " + result); } static int square(int i) { int result = i * i; return result; }} Ans. result is not defined in the main method, and is only defined locally in the square method Variable Scope Identify the error and suggest how you fix the following: public static void main(String[] args) { for(int i = 0; i < 10; i++) { System.out.println(i * i); } double sqrt = Math.sqrt(i); System.out.println(sqrt); } Ans. A variable, i, cannot be called outside of a loop, as it is only defined locally within a loop. The line double sqrt = Math.sqrt(i); calls on a variable, i, that is not resolved Write a method called powersOfTwo that prints the first 10 powers of 2. Starting with 2. (22 , 23, 24… 210) The method takes no parameters and has no return value. public static void powersOfTwo(){ for(int i =2; i <= 10; i ++) print(Math.Pow(2,i); } Write a method called multiConcat that takes a String and an integer as parameters. Return a String that consists of the string parameter concatenated with itself count times, where count is the integer parameter. For example, if the parameter values are “hi” and 4, the return value is “hihihihi” . Return the original string if the integer parameter is less than 2. public static String multiConCat(String s, int count){ String r ; if(count < 2){ Return s; } for(int i = 0 i < count; i ++){ R += s; } Return r; } Write a method called randomInRange that accepts two integer parameters representing a range. The method should return a random integer in the specified range (inclusive). Return zero if the first parameter is greater than the second. public static int randomInRange(int max, int min){ if( max > min ){ return 0; } Random rand = new Random(); Return random.nextInt((max-min) +1) + min; //or Int x = (int) ( ( (Math.random() * ( (max - min ) + 1)) ) + min) ; return x; // between 5 and 14, 14-5 is 9 so random from 0 to 9 and + 5 to make up to 14 // add one because exclusivity of random generator Write a method called average that accepts two integer parameters and returns their average as a floating point value. Public static double average(int a , int b){ Double x = (a+b)/2; Return x; } Overload the average method such that if three integers are provided as parameters, the method returns the average of all three Overload the average method to accept four integer parameters and return their average. Public static double average(int a , int b){ Double x = (a+b)/2; Return x; } Public static double average(int a , int b, int c, int d){ Double x = (a+b + c + d)/4; Return x; } Public static double average(int a , int b, int c){ Double x = (a+b +c)/3; Return x; } 3. Arrays Reference Data What does the following code snippet print out? What if the array was of type boolean? int [] array = new int[10]; for(int i = 0; i < array.length; i++) System.out.println(‘array at” + i + “ is “ + array[i]); Array at 0 is 0 (if boolean false) …… Array at 9 is 0 What is the output for the following code? public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4}; x = new int[2]; for (int i = 0; i < x.length; i++) A) B) C) D) 1 1 0 1 System.out.print(x[i] + " "); } } C Initialize all array elements with 0 2 2 3 4 0 1 Create an array of words (I called mine “words”), and write a method for each of the following 1. 2. 3. Find the word in the array with the most vowels (remember to count upper and lower case!) Replace the first letter of every word with “B” (BONUS!) Sort the array alphabetically (don’t use the Arrays.sort method) The following code aims to print the elements of the array nums as well as the value of the counter i which causes the loop to terminate. The code includes 3 errors. Find these errors and rewrite the code after fixing them. double nums[] = {1.5, 2.3, 3.6}; for (int i = 0; i <= nums.length; i++) { System.out.println(nums); } System.out.println(i); Errors: 1. index not specified on nums -> should be nums[i] 2. The call to print out is outside the scope of i 3. Nums.length needs to be -1 or < as it creates an index out of bounds exception once print To fix, specify index of nums (nums[i]) and declare i outside of loop. ( int i; ) Create a multiplication table. Use multidimensional arrays. int[][] mult = new int[9][9]; for(int i = 0; i < mult.length; i++){ for(int j = 0; j<mult[i].length; j++){ mult[i][j] = (i+1)*(j+1); } } for(int k = 0; k < mult.length; k++){ for(int l = 0; l < mult.length; l++){ System.out.printf("%3d", mult[k][l]); } System.out.println(); } Given a 2D array A, transform it into array B by moving each row. Remember a 2D array is an array of 1D arrays. A 1 5 9 13 2 6 10 14 3 7 11 15 B 4 8 12 16 16 12 8 4 15 11 7 3 14 10 6 2 13 9 5 1 public static int [][] transform ( int [][] array ) { int row = array.length; int col = array[0].length; int [][] result = new int [row][col]; for ( int i = 0; i < row; i++ ) { for ( int j = 0; j < col; j++ ) { result[i][j] = array[(row-1)-i][(col-1) -j]; } } return result; } GOOD LUCK!