Mario Gets Laid Friday, January 6, 2012 My Final Java, C, & C++ Questions & Answers ARRAYS Declaration 1. Declare and instantiate an array named scores of twenty-five elements of type int. int[] scores = new int[25]; 2. Write a statement that declares an array named streetAddress that contains exactly eighty elements of type char. char[] streetAddress = new char[80]; Initialization-2 1. Declare an array named a of ten elements of type int and initialize the elements (starting with the first) to the values 10, 20, ..., 100 respectively. int[] a = {10,20,30,40,50,60,70,80,90,100}; 2. Declare an array named taxRates of five elements of type double and initialize the elements (starting with the first) to the values 0.10, 0.15, 0.21, 0.28, 0.31, respectively. double[] taxRates = { 0.10 , 0.15 , 0.21 , 0.28 , 0.31 } ; 3. Write a statement to declare and initialize an array named denominations that contains exactly six elements of type of int. Your declaration statement should initialize the elements of the array to the following values: 1, 5, 10, 25, 50, 100. (The value 1 goes into the first element, the value 100 to the last.) int[] denominations = { 1 , 5 , 10 , 25 , 50 , 100 } ; Access 1. Given an array a, write an expression that refers to the first element of the array. More... So, if the array a held the following values: 33,14,97,265, 84, then the value of your expression should be 33. a[0] 2. Given an array a , declared to contain 34 elements, write an expression that refers to the last element of the array. a[33] 3. Assume that the array arr has been declared. Write a statement that assigns the next to last element of the array to the variable x, which has already been declared. x = arr[arr.length-2] ; 4. Given that the array monthSales of integers has already been declared and that its elements contain sales data for the 12 months of the year in order (i.e., January, February, etc.), write a statement that writes to standard output the element corresponding to October. Do not write anything else out to standard output. More... So if the contents of the array monthSales were: 2000 1000 2400 2200 2800 3000 4400 3500 1500 1100 2200 1300 then your coulde would print out 1100 (the sales data for October). System.out.println(monthSales[9]) ; Assignment 1. Given that an array named a with elements of type int has been declared, assign 3 to its first element. More... Suppose the values of the array a BEFORE your code executed were: 15,7,22,4. Then, AFTER your code executed, the values of the array a would be: 3,7,22,4. Note that the value of the first element was changed to 3. a[0] = 3 ; 2. Assume that an array named salarySteps whose elements are of type int and that has exactly five elements has already been declared. Write a single statement to assign the value 30000 to the first element of this array. salarySteps[0] = 30000 ; 3. Assume that an array of integers named salarySteps that contains exactly five elements has been declared. Write a statement that assigns the value 160000 to the last element of the array salarySteps. salarySteps[4] = 160000 ; 4. Assume that an array named a containing exactly 5 integers has been declared and initialized. Write a single statement that adds 10 to the value stored in the first element of the array. a[0] = a[0]+10 ; 5. Given that an array of int s named a with 30 elements has been declared, assign 5 to its last element. a[29] = 5 ; 6. Assume that an array of int s named a has been declared with 12 elements. The integer variable k holds a value between 0 and 6. Assign 15 to the array element whose index is k. a[k] = 15 ; 7. Given that an array named a whose elements are of type int has been declared, assign the value -1 to the last element in a. a[a.length-1] = -1 ; 8. An array of int s named a has been declared with 12 elements. The integer variable k holds a value between 0 and 6. Assign 9 to the element just after a[k]. a[k+1] = 9 ; 9. An array of int s named a has been declared with 12 elements. The integer variable k holds a value between 2 and 8. Assign 22 to the element just before a[k]. a[k-1] = 22 ; 10. Assume that an array of int s named a that contains exactly five elements has been declared and initialized. In addition, an int variable j has also been declared and initialized to a value somewhere between 0 and 3. Write a single statement that assigns a new value to element of the array indexed by j. This new value should be equal to twice the value stored in the next element of the array (i.e. the element after the element indexed by j. a[j] = 2 * a[j+1] ; 11. Assume that an array of integers named a has been declared and initialized. Write a single statement that assigns a new value to the first element of the array. The new value should be equal to twice the value stored in the last element of the array. a[0] = 2 * a[a.length-1] ; Arrays-1 1. printArray is a method that accepts one argument, an array of int s. The method prints the contents of the array; it does not return a value. inventory is an array of int s that has been already declared and filled with values. Write a statement that prints the contents of the array inventory by calling the method printArray. printArray( inventory ) ; Arrays-3 1. Write the definition of a method printArray, which has one parameter, an array of int s. The method does not return a value. The method prints out each element of the array, on a line by itself, in the order the elements appear in the array, and does not print anything else. More... Consider this code fragment: int[] myArr = {10, 20, 30, 40, 50}; printArray(myArr); The above fragment of code should result in the following output 10 20 30 40 50 public void printArray( int[] s ) { for ( int i = 0 ; i < s.length ; i++ ) { System.out.println(s[i]) ; } } 2. Write the definition of a method named sumArray that has one parameter, an array of int s. The method returns the sum of the elements of the array as an int. public int sumArray ( int[] s ) { int sum = 0 ; for ( int i = 0 ; i < s.length ; i++ ) { sum = sum + s[i] ; } return sum ; } 3. Write the definition of a method, isReverse , whose two parameters are arrays of integers of equal size. The method returns true if and only if one array is the reverse of the other. ("Reverse" here means same elements but in reverse order.) More... So, suppose you had two int arrays, forward and backward, each with 4 elements. Now suppose that forward had these elements: 1, 2, 3, 4 and that backward had these: values 4, 3, 2, 1. Then if your isReverse method were invoked, passing it forward and backward, it would return true. public boolean isReverse ( int[] a , int[] b ) { if (a.length != b.length) { return false ; } for (int i = 0 ; i < a.length ; i++) { if (a[i] != b[b.length-1-i]) { return false ; } } return true ; } 4. Write the definition of a method reverse, whose parameter is an array of integers. The method reverses the elements of the array. The method does not return a value. More... If you pass an array of integers arr1 containing the values 2, 4, 6, 8, 10 to reverse, and print out the array after that, the output will be 10, 8, 6, 4, 2 public void reverse ( int[] a ) { for ( int i = 0 ; i < a.length/2 ; i++ ) { int temp = a[i] ; a[i] = a[a.length-i-1] ; a[a.length-i-1] = temp ; } } TECHNIQUES2 ArrayAverage 1. Given an array temps of double s, containing temperature data, compute the average temperature. Store the average in a variable called avgTemp. Besides temps and avgTemp, you may use only two other variables -- an int variable k and a double variable named total, which have been declared. More... Suppose the the temps array had just four elements: 5.4, 8.0, 2.0, and 4.6. Then the value of avgTemp that you would compute would be 5.0, because that is the average of the above four numbers. total = 0 ; for( k = 0 ; k<temps.length ; k++ ) { total = total + temps[k] ; } avgTemp = total/temps.length ; ArrayReversal 1. We informally define the term corresponding element as follows: The first element in an array and the last element of the array are corresponding elements. Similarly, the second element and the element just before the last element are corresponding elements. The third element and the element just before the element just before the last element are corresponding elements -- and so on. Given an array a, write an expression for the corresponding element of a[i]. More... Suppose there is an array a of size 5. Then a[0] corresponds to a[4], a[1] corresponds to a[3], and a[2] corresponds to itself. So if the value of i is 3, then your expression is equal to a[1]. a [ a . length - i - 1 ] 2. Reversing the elements of an array involves swapping the corresponding elements of the array: the first with the last, the second with the next to the last, and so on, all the way to the middle of the array. Given an array a and two other int variables, k and temp, write a loop that reverses the elements of the array. Do not use any other variables besides a, k, and temp. for( k=0 ; k<a.length/2 ; k++ ) { temp = a[k] ; a[k] = a[a.length - k - 1] ; a[a.length - k - 1] = temp ; } ArraySearching 1. Given: an int variable k, an int array currentMembers that has been declared and initialized, an int variable memberID that has been initialized, and an boolean variable isAMember, write code that assigns true to isAMember if the value of memberID can be found in currentMembers, and that assigns false to isAMember otherwise. Use only k, currentMembers, memberID, and isAMember. for ( k=0 ; k<currentMembers.length ; k++ ) { if (memberID==currentMembers[k]) { isAMember = true ; break ; } else { isAMember = false ; } } 2. You are given an int variable k, an int array zipcodeList that has been declared and initialized, and an boolean variable duplicates. Write some code that assigns true to duplicates if there are two adjacent elements in the array that have the same value, and that assigns false to duplicates otherwise. Use only k, zipcodeList, and duplicates. More... If zipcodeList contains four values: 11210, 11204, 11204, 10001, duplicates should become true. However, if zipcodeList contains the same four values, but in a different order: 11210, 11204, 10001, 11204, duplicates should become false duplicates = false ; for( k=0 ; k<zipcodeList.length-1 ; k++ ) { if (zipcodeList[k]==zipcodeList[k+1]) { duplicates=true; break ; } else { duplicates=false; } } 3. You are given two int variables j and k, an int array zipcodeList that has been declared and initialized, and an boolean variable duplicates. Write some code that assigns true to duplicates if any two elements in the array have the same value, and that assigns false to duplicates otherwise. Use only j , k, zipcodeList, and duplicates. More... This time the order doesn't matter, so in both cases, when zipcodeList contains 11210, 11204, 11204, 10001 and when zipcodeList contains 11210, 11204, 10001, 11204, duplicates should become true duplicates = false ; for( k=0 ; k<zipcodeList.length-1 ; k++ ) { for( j=k+1 ; j<zipcodeList.length ; j++ ) { if (zipcodeList[k]==zipcodeList[j]) { duplicates=true ; break ; } else { duplicates=false ; } } } CountingArrayElements 1. Given an int variable k, an int array incompletes that has been declared and initialized, an int variable studentID that has been initialized, and an int variable numberOfIncompletes, write code that counts the number of times the value of studentID appears in incompletes and assigns this value to numberOfIncompletes. You may use only k, incompletes, studentID, and numberOfIncompletes numberOfIncompletes=0; for(k=0;k<incompletes.length;k++) { if (studentID==incompletes[k]) { numberOfIncompletes++ ; } } MaxMin-1 1. Given the integer variables x and y, write a fragment of code that assigns the larger of x and y to another integer variable max. if (x>y) { max=x; } else { max=y; } 2. Write the definition of a method max that has three int parameters and returns the largest. public int max( int x , int y , int z ) { if (x>y&&x>z) { return x; } else if (y>x&&y>z) { return y; } else { return z; } } 3. An array of integers named parkingTickets has been declared and initialized to the number of parking tickets given out by the city police each day since the beginning of the current year. (Thus, the first element of the array contains the number of tickets given on January 1; the last element contains the number of tickets given today.) A variable named mostTickets has been declared, along with a variable k. Without using any additional variables, write some code that results in mostTickets containing the largest value found in parkingTickets. mostTickets=0; for(k=0;k<parkingTickets.length;k=k+1) { if (k==0) { mostTickets=parkingTickets[k]; } if (parkingTickets[k]>mostTickets) { mostTickets=parkingTickets[k]; } } C and C++ QUICKSTART in C Beginning 1. Write a statement that prints Hello World to the screen. printf( "Hello World" ) ; 2. Write a complete program that prints Hello World to the screen. void main() { printf( "Hello World" ) ; return 0 ; } 3. Suppose your name was Alan Turing. Write a statement that would print your last name, followed by a comma, followed by your first name. Do not print anything else (that includes blanks). printf( "Turing,Alan" ) ; 4. Suppose your name was George Gershwin. Write a complete program that would print your last name, followed by a comma, followed by your first name. Do not print anything else (that includes blanks). void main() { printf( "Gershwin,George" ) ; return 0 ; } Output 1. Given that an integer variable count has already been declared and assigned a value: Write a statement that writes the value of count to standard output. Do not write anything else to standard output -- just the value of count. printf ( " %d " , count ) ; 2. Given that a floating-point variable fraction has already been declared and assigned a value: Write a statement that writes the value of fraction to standard output. Do not write anything else to standard output -- just the value of fraction. printf ( " %f " , fraction ) ; 3. The exercise instructions here are LONG -- please read them all carefully. If you see an internal scrollbar to the right of these instructions, be sure to scroll down to read everything. Given that an integer variable i and a floating-point variable f have already been declared and given values: Write a statement in C that displays the values of i and f to standard output in the following format: i=value-of-i f=value-of-f Two Examples: Example 1: if the values of i and f were 25 and 12.34 respectively, the output would be: i=25 f=12.34 Example 2: if the values of i and f 's value were 703 and 3.14159, (respectively) the output would be: i=703 f=3.14159 Remember: you are GIVEN i and f-- that means they are already declared and they already have values! Don't change their values by assigning or initializing them! Just print them out the way we have shown above. Just write one statement to produce the output. Remember: you don't know what the actual values of i and f are-- they are unlikely to be the values used in the examples above! Remember: in your output you must be displaying both the name of the variable (like i) and its value. printf ( "i=%d f=%f" , i , f ) ; Declarations-1 Basics 1. Declare a variable populationChange, suitable for holding numbers like -593142 and 8930522. int populationChange ; 2. Declare a variable x , suitable for storing values like 3.14159 and 6.02 times ten to the 23rd power. double x ; Initialization 1. Declare an integer variable cardsInHand and initialize it to 13. int cardsInHand = 13 ; 2. Declare a variable temperature and initialize it to 98.6. double temperature = 98.6 ; 3. Declare a numerical variable precise and initialize it to the value 1.09388641. double precise = 1.09388641 ; Input 1. Given an int variable datum that has already been declared, write a statement that reads an integer value from standard input into this variable. scanf ( "%datum" , &datum ) ; Programs 1. Write a complete program that declares an integer variable, reads a value from the keyboard into that variable, and writes to standard output the square of the variable's value. Besides the number, nothing else should be written to standard output. int main() { int i ; scanf ( "%i" , &i ) ; i = i*i ; printf ( "%i" , i ) ; return 0 ; } 2. Write a complete program that declares an integer variable, reads a value from the keyboard into that variable, and writes to standard output the variable's value, twice the value, and the square of the value, separated by spaces. Besides the numbers, nothing else should be written to standard output except for spaces separating the values. int main() { int i ; scanf ( "%i" , &i ) ; printf ( "%i %i %i" , i , i*2 , i*i ) ; return 0 ; } QUICKSTART IN C++ Beginning 1. Write a statement that prints Hello World to the screen. cout << "Hello World" ; 2. Write a complete program that prints Hello World to the screen. #include <iostream> using namespace std; int main() { cout << "Hello World" ; } 3. Suppose your name was Alan Turing. Write a statement that would print your last name, followed by a comma, followed by your first name. Do not print anything else (that includes blanks). cout << "Turing,Alan" ; 4. Suppose your name was George Gershwin. Write a complete program that would print your last name, followed by a comma, followed by your first name. Do not print anything else (that includes blanks). #include <iostream> using namespace std; int main() { cout << "Gershwin,George" ; } Output 1. Given an integer variable count, write a statement that writes the value of count to standard output. (When we say "given", that means that count has ALREADY been declared-- so you should not declare it!) Do not write anything else to standard output -- just the value of count. In particular, your output should NOT include something like "count=". The output should be JUST the value of the variable count. printf(" %d",count) ; 2. Given a floating-point variable fraction, write a statement that writes the value of fraction to standard output. Do not write anything else to standard output -- just the value of fraction. printf(" %f",fraction) ; 3. The exercise instructions here are LONG -- please read them all carefully. If you see an internal scrollbar to the right of these instructions, be sure to scroll down to read everything. Given an integer variable i and a floating-point variable f, write a statement that writes both of their values to standard output in the following format: i=value-of-i f=value-of-f Thus, if i's value were 25 and f's value were 12.34, the output would be: i=25 f=12.34 But you don't know what i's value and f's value are. They might be 187 and 24.06. If that's what their values are, the output from your statement should be: i=187 f=24.06 Remember: you are GIVEN i and f-- that means they are already declared and they already have values! Don't change their values by assigning or initializing them! Just print them out the way we have shown above. Just write one statement to produce the output. Remember: in your output you must be displaying both the name of the variable (like i) and its value. cout << "i=" << i << " f=" << f ; Declarations-1 Basics 1. Declare a variable populationChange, suitable for holding numbers like -593142 and 8930522. int populationChange ; 2. Declare a variable x, suitable for storing values like 3.14159 and 6.02E23. double x ; Initialization-1 1. Declare an integer variable cardsInHand and initialize it to 13. int cardsInHand = 13 ; 2. Declare a variable temperature and initialize it to 98.6. double temperature = 98.6 ; 3. Declare a numerical variable precise and initialize it to the value 1.09388641. double precise = 1.09388641 ; Input 1. Given an int variable datum that has already been declared, write a statement that reads an integer value from standard input into this variable. cin >> datum ; Programs 1. Write a complete program that declares an integer variable, reads a value from the keyboard into that variable, and writes to standard output the square of the variable's value. Besides the number, nothing else should be written to standard output. #include <iostream> using namespace std; int main() { int i ; cin >> i ; cout << i*i ; return 0 ; } 2. Write a complete program that declares an integer variable, reads a value from the keyboard into that variable, and writes to standard output the variable's value, twice the value, and the square of the value, separated by spaces. Besides the numbers, nothing else should be written to standard output except for spaces separating the values. #include <iostream> using namespace std; int main() { int i ; cin >> i ; cout << i << " " << i*2 << " " << i*i ; return 0 ; } TYPES in C Boolean Literals-2 1. Write a literal representing C's false value. 0 2. Write a literal representing a true value. 1 Declarations-3 1. Declare a variable isACustomer, suitable for representing a true or false value. _Bool isACustomer ; Operations-2 1. Write an expression that evaluates to true if and only if the value of the integer variable x is equal to zero. (x==0) 2. Write an expression that evaluates to true if and only if the variables profits and losses are exactly equal. ( profits == losses ) 3. Given the char variable c, write an expression that is true if and only if the value of c is not the space character. ( c!=' ' ) 4. Write an expression that evaluates to true if the value of index is greater than the value of lastIndex. ( index > lastIndex ) 5. Working overtime is defined as having worked more than 40 hours during the week. Given the variable hoursWorked, write an expression that evaluates to true if the employee worked overtime. ( hoursWorked > 40 ) 6. Write an expression that evaluates to true if the value x is greater than or equal to y. ( x >= y ) 7. Given the variables numberOfMen and numberOfWomen, write an expression that evaluates to true if the number of men is greater than or equal to the number of women. ( numberOfMen >= numberOfWomen ) 8. Given a double variable called average, write an expression that is true if and only if the variable's value is less than 60.0. ( average < 60.0 ) 9. Given an int variable grossPay, write an expression that evaluates to true if and only if the value of grossPay is less than 10,000. ( grossPay < 10000 ) Character_Type Literals-3 1. Write a character literal representing the (upper case) letter A. 'A' 2. Write a character literal representing a comma. ',' 3. Write a character literal representing the digit 1. '1' 4. Write a literal representing the character whose ASCII value is 65. (char)65 5. Write a literal representing the largest character value. Suppose we are using unsigned one-byte characters. 255 Declarations-4 1. Declare a character variable named c. char c ; ConversionsAndCasting 1. Given two integer variables distance and speed, write an expression that divides distance by speed using floating point arithmetic, i.e. a fractional result should be produced. (float) distance / speed ARRAYS in C Declaration 1. Declare an array named scores of twenty-five elements of type int. int scores[25] ; 2. Write a statement that declares an array of char s named streetAddress that contains exactly eighty elements. char streetAddress[80] ; Initialization-2 1. Declare an array named a of 10 elements of type int and initialize the elements (starting with the first) to the values 10, 20, ..., 100, respectively. int a [10] = {10,20,30,40,50,60,70,80,90,100}; 2. Declare an array named taxRates of 5 elements of type double and initialize the elements (starting with the first) to the values 0.10, 0.15, 0.21, 0.28, 0.31, respectively. double taxRates [5] = {0.10, 0.15, 0.21, 0.28, 0.31}; 3. Write a statement to declare and initialize an array of int s named denominations that contains exactly six elements. Your declaration statement should initialize the elements of the array to the following values: 1, 5, 10, 25, 50, 100. (The value 1 goes into the first element; the value 100 to the last.) int denominations [6] = {1, 5, 10, 25, 50, 100} ; FUNCTIONS in C++ Invocation-1 ParameterLess-1 1. printTodaysDate is a function that accepts no parameters and returns no value. Write a statement that calls printTodaysDate. printTodaysDate() ; Scalar_variables-1 1. printErrorDescription is a function that accepts one int parameter and returns no value. Write a statement that calls the function printErrorDescription, passing it the value 14. printErrorDescription(14) ; 2. printLarger is a function that accepts two int parameters and returns no value. Two int variables, sales1 and sales2, have already been declared and initialized. Write a statement that calls printLarger, passing it sales1 and sales2. printLarger( sales1 , sales2 ) ; 3. add is a function that accepts two int parameters and returns their sum. Two int variables, euroSales and asiaSales, have already been declared and initialized. Another int variable, eurasiaSales, has already been declared. Write a statement that calls add to compute the sum of euroSales and asiaSales and store this value in eurasiaSales. eurasiaSales = add( euroSales , asiaSales ) ; 4. toThePowerOf is a function that accepts two int parameters and returns the value of the first parameter raised to the power of the second. An int variable cubeSide has already been declared and initialized. Another int variable, cubeVolume, has already been declared. Write a statement that calls toThePowerOf to compute the value of cubeSide raised to the power of 3, and store this value in cubeVolume. cubeVolume = toThePowerOf( cubeSide , 3 ) ; 5. max is a function that accepts two int parameters and returns the value of the larger one. Two int variables, population1 and population2, have already been declared and initialized. Write an expression (not a statement!) whose value is the larger of population1 and population2 by calling max. max( population1 , population2 ) 6. max is a function that accepts two int parameters and returns the value of the larger one. Four int variables, population1, population2, population3, and population4 have already been declared and initialized. Write an expression (not a statement!) whose value is the largest of population1, population2, population3, and population4 by calling max. (HINT: you will need to call max three times and you will need to pass the return values of two of those calls as arguments to max. REMEMBER: write an expression, not a statement.) max( max ( population1 , population2 ) , max ( population4 , population3 ) ) Arrays-1 1. printArray is a function that has two parameters. The first parameter is an array of int s and the second is an int, the number of elements in the array. The function prints the contents of the array parameter; it does not return a value. inventory is an array of int s that has been already declared and filled with values. n is an int variable that holds the number of elements in the array. Write a statement that prints the contents of the array inventory by calling the function printArray. printArray( inventory , n ) ; Prototypes-1 Scalar_variables-2 1. Write a statement that declares a prototype for a function printErrorDescription, which has an int parameter and returns nothing. void printErrorDescription(int) ; 2. Write a statement that declares a prototype for a function printLarger, which has two int parameters and returns no value. void printLarger( int , int ) ; 3. Write a statement that declares a prototype for a function twice, which has an int parameter and returns an int. int twice( int ) ; 4. Write a statement that declares a prototype for a function add, which has two int parameters and returns an int. int add ( int , int ) ; 5. Write a statement that declares a prototype for a function powerTo, which has two parameters. The first is a double and the second is an int. The function returns a double. double powerTo ( double , int ) ; Arrays-2 1. Write a statement that declares a prototype for a function printArray, which has two parameters. The first parameter is an array of int s and the second is an int, the number of elements in the array. The function does not return a value. void printArray ( int[] , int ) ; ParameterLess-2 1. Write a statement that declares a prototype for a function ]] > printTodaysDate, which has no parameters and doesn't return anything. void printTodaysDate() ; Definitions-1 ParameterLess-3 1. Write the definition of a function printDottedLine, which has no parameters and doesn't return anything. The function prints to standard output a single line (terminated by a new line character) consisting of 5 periods. void printDottedLine () { printf(".....\n") ; } Scalar_variables-3 1. Write the definition of a function printGrade, which has a char parameter and returns nothing. The function prints on a line by itself the message string Grade: followed by the char parameter (printed as a character) to standard output. Don't forget to put a new line character at the end of your line. Thus, if the value of the parameter is 'A', the function prints out Grade: A void printGrade ( char i ) { cout << "Grade: " << i << "\n" ; } 2. Write the definition of a function printAttitude, which has an int parameter and returns nothing. The function prints a message to standard output depending on the value of its parameter. If the parameter equals 1, the function prints disagree If the parameter equals 2, the function prints no opinion If the parameter equals 3, the function prints agree In the case of other values, the function does nothing. Each message is printed on a line by itself. void printAttitude( int i ) { if (i==1) { cout << "disagree\n" ; } else if (i==2) { cout << "no opinion\n" ; } else if (i==3) { cout << "agree\n" ; } else { } } 3. Write the definition of a function printLarger, which has two int parameters and returns nothing. The function prints the larger value of the two parameters to standard output on a single line by itself. void printLarger(int x, int y) { if (x>=y) { cout << x << "\n"; } else if (y>=x) { cout << y << "\n"; } } 4. Write the definition of a function twice, that receives an integer parameter and returns an integer that is twice the value of that parameter. int twice ( int i ) { return i*2 ; } 5. Write the definition of a function add, which receives two integer parameters and returns their sum. int add ( int dale , int reed ) { return dale+reed ; } 6. Write the definition of a function dashedLine, with one parameter, an int. If the parameter is negative or zero, the function does nothing. Otherwise it prints a complete line terminated by a new line character to standard output consisting of dashes (hyphens) with the parameter's value determining the number of dashes. The function returns nothing. void dashedLine(int a) { if (a<=0) { } else { cout << "-----" << a ; cout << "\n" ; } } 7. Write the definition of a function powerTo, which receives two parameters. The first is a double and the second is an int. The function returns a double. If the second parameter is negative, the function returns 0. Otherwise, it returns the value of the first parameter raised to the power of the second. double powerTo (double a,int b) { if (b<0) { return 0; } else { double temp=a; for(int z=0;z<b-1;z++) { a=a*temp; } return a; } } Arrays-3 1. Write the definition of a function printArray, which has two parameters. The first parameter is an array of int s and the second is an int, the number of elements in the array. The function does not return a value. The function prints out each element of the array, on a line by itself, in the order the elements appear in the array, and does not print anything else. void printArray(int i[],int j) { for(int x=0;x<j;x++) { cout << i[x] << "\n" ; } } Reference_Variables 1. Given an integer variable i, declare a reference variable r that is a reference to i. int &r = i ; 2. Assume a function addOne that accepts a single integer reference parameter and returns nothing. Call the function, passing it the variable i which has already been declared. addOne(i) ; 3. Write the header for a function addOne that accepts a single integer reference parameter and returns nothing. Name the parameter x. void addOne(int &x) 4. Write a function addOne that adds 1 to its integer reference parameter. The function returns nothing. void addOne(int &addto) { addto++; } Examples 1. Given the integer variables x, y, and z, write a fragment of code that assigns the smallest of x, y, and z to another integer variable min. Assume that all the variables have already been declared and that x, y, and z have been assigned values). if (x<=y&&x<=z) { min=x; } if (y<=x&&y<=z) { min=y; } if (z<=x&&z<=y) { min=z; } 2. Write the definition of a function min that has two int parameters and returns the smaller. int min(int i,int j) { if (i<j) { return i; } if (j<i) { return j; } } 3. Write the definition of a function named sumArray that receives two parameters: an array of int s and an int that contains the number of elements of the array. The function returns the sum of the elements of the array as an int. int sumArray(int s[],int k) { int sum=0; for(int i=0;i<k;i++) { sum=sum+s[i] ; } return (sum); } 4. Write the definition of a function, isReverse, whose first two parameters are arrays of integers of equal size, and whose third parameter is an integer indicating the size of each array. The function returns true if and only if one array is the reverse of the other. ("Reverse" here means same elements but in reverse order.) bool isReverse(int array1[],int array2[],int size) { for(int n=0 ; n<size ; n++) { if (array1[n] != array2[size-1-n]) { return false; } else { return true; } } } 5. Write the definition of a function reverse, whose first parameter is an array of integers and whose second parameter is the number of elements in the array. The function reverses the elements of the array. The function does not return a value. void reverse(int a[],int n) { int k , temp; for(k=0;k<n/2;k++) { temp = a[k]; a[k]=a[n-k-1]; a[n-k-1]=temp; } } FUNCTIONS in C Invocation-1 ParameterLess-1 1. printTodaysDate is a function that accepts no parameters and returns no value. Write a statement that calls printTodaysDate. printTodaysDate() ; Scalar_variables-1 Arrays-1 Prototypes-1 Scalar_variables-2 Arrays-2 ParameterLess-2 Definitions-1 ParameterLess-3 Scalar_variables-3 Arrays-3 Examples STRINGS CStrings Equal 1. Write an expression that evaluates to true if and only if the C-string s equals the C-string "end". ! strcmp(s,"end") Inequality 1. Write an expression that evaluates to true if the value of the C-string s1 is greater than the value of C-string s2. strcmp(s1,s2)>0 2. Write an expression that evaluates to true if the value of C-string lastName is greater than the C-string "Dexter". strcmp(lastName,"Dexter")>0 3. Write an expression that evaluates to true if and only if the C-string s does not equal "end". strcmp(s,"end")!=0 MaxMin-2 1. Given the string variables name1 and name2, write a fragment of code that assigns the larger of the two to the variable first (assume all three are already declared and name1 and name2 assigned values). if(strcmp(name1,name2)>0) { first=name1; } else { first=name2; } 2. Given the char * variables name1, name2 , and name3, write a fragment of code that assigns the largest value to the variable max (assume all three have already been declared and have been assigned values). max = name1; if( strcmp(name2,max) > 0) max = name2; if( strcmp(name3,max) > 0) max = name3; 3. Write a function max that has two C string parameters and returns the larger of the two. char* max(char* a, char* b) { int result = strcmp(a, b); if(result>0) return a; else return b; } 4. Write a function min that has three C string parameters and returns the smallest. char* min(char* a, char* b, char* c) { return strcmp(a,b) < 0 ? strcmp(a,c) < 0? a: c : strcmp(b,c) < 0? b: c; } C_POINTERS Parameters-1 Definitions-2 1. Write the definition of a function zeroIt, which is used to zero out a variable. The function is used as follows: int x=5; zeroIt(&x); /* x is now equal to 0 */ void zeroIt (int *p) { *p=0; } 2. Write the definition of a function doubleIt, which doubles the value of its argument but returns nothing so that it can be used as follows: int x=5; doubleIt(&x); /* x is now equal to 10 */ void doubleIt(int *x) // pass in a pointer as your 'usage' dictates { *x *= 2; // multiply the contents of the pointer by 2 return; } 3. Write the definition of a function tripleIt, which triples its argument but returns nothing so that it can be used as follows: int x=5; tripleIt(&x); /* x is now equal to 15 */ void tripleIt(int *x) // pass in a pointer as your 'usage' dictates { *x *= 3; // multiply the contents of the pointer by 2 return; } 4. Write the definition of a function divide that takes four arguments and returns no value. The first two arguments are of type int. The last two arguments arguments are pointers to int and are set by the function to the quotient and remainder of dividing the first argument by the second argument. The function does not return a value. The function can be used as follows: int numerator=42, denominator=5, quotient, remainder; divide(numerator,denominator,&quotient,&remainder); /* quotient is now 8 */ /* remainder is now 2 */ void divide(int x, int y, int *a, int *b) { *a = x/y; *b = x%y; return; } 5. Write the definition of a function minMax that has five parameters. The first three parameters are integers. The last two are set by the function to the largest and smallest of the values of the first three parameters. The function does not return a value. The function can be used as follows: int a=31, b=5, c=19, big, small; minMax(a,b,c,&big,&small); /* big is now 31 */ /* small is now 5 */ void minMax(int a, int b, int c, int* big, int* small) { if(a<b && a<c) { *small=a; } else if(b<a && b<c) { *small=b; } else { *small=c; } if(a>b && a>c) { *big=a; } else if(b>a && b>c) { *big=b; } else { *big=c; } } Invocation-2 1. zeroIt is a function that takes one argument and returns no value. The argument is a pointer to int. The function stores the value 0 back into the variable pointed to by the argument. x is an int variable that has been declared. Write a statement that sets the value stored in x to zero by invoking the function zeroIt. zeroIt(&x); 2. doubleIt is a function that takes one argument and returns no value. The argument is a pointer to int. The function doubles the value that the argument points to and stores it back. savings is an int variable that has been declared and initialized. Write a statement that doubles the value stored in savings by invoking the function doubleIt. For example, if the value in savings was 7 before your statement, after your statement its value would be 14. doubleIt(&savings); 3. tripleIt is a function that takes one argument and returns no value. The argument is a pointer to int. The function triples the value that the argument points to and stores it back. penalty is an int variable that has been declared and initialized. Write a statement that triples the value stored in penalty by invoking the function tripleIt. For example, if the value in penalty was 7 before your statement, after your statement its value would be 21. tripleIt(&penalty); 4. divide is a function that takes four arguments and returns no value. The first two arguments are of type int. The last two arguments arguments are pointers to int that are set by the function to the quotient and remainder of dividing the first argument by the second argument. The function does not return a value. x and y are two int variables that have been declared and initialized. q and r are two int variables that have been declared. Write a statement that sets the value of q to the quotient of x divided by y, and sets the value of r to the remainder of x divided by y, by calling divide. divide(x,y,&q,&r); 5. minMax is a function that takes five arguments and returns no value. The first three arguments are of type int. The last two arguments are pointers to int that are set by the function to the largest and smallest of the values of the first three parameters, respectively. x, y and z are three int variables that have been declared and initialized. big and small are two int variables that have been declared. Write a statement that sets the value of big to the largest of x, y, z and sets the value of small to the smallest of x, y, z by calling minMax. minMax(x,y,z,&big,&small); Prototypes-2 1. Write a statement that declares a prototype for a function zeroIt, which can be used as follows: int x=5; zeroIt(&x); /* x is now equal to 0 */ void zeroIt(int *x); 2. Write a statement that declares a prototype for a function doubleIt, which has a single parameter of type pointer to int. void doubleIt(int *x); 3. Write a statement that declares a prototype for a function tripleIt, which can be used as follows: int x=5; tripleIt(&x); /* x is now equal to 15 */ void tripleIt(int *x); 4. Write a statement that declares a prototype for a function divide that takes four arguments and returns no value. The first two arguments are of type int. The last two arguments arguments are pointers to int that are set by the function to the quotient and remainder of dividing the first argument by the second argument. The function does not return a value. void divide (int x, int y, int *q , int *r); 5. Write a statement that declares a prototype for a function minMax, which has five parameters. The first three parameters are integers. The last two are parameters that are set by the function to the largest and smallest of the values of the first three parameters. The function does not return a value. void minMax(int x, int y, int z,int *big, int *small); Precedence-2 1. Write an expression that evaluates to 1 more than the value in the location pointed to by the integer pointer variable ip. Thus, if ip points to a location containing the value 3, the expression should evaluate to 4. *ip+1 2. Write an expression that retrieves the value in the location immediately after the location pointed to by the integer pointer variable ip. *(ip+1) POINTERS in C++ Parameters-1 Definitions-2 1. Write the definition of a function zeroIt, which is used to zero out a variable. The function is used as follows: int x=5; zeroIt(&x); /* x is now equal to 0 */ void zeroIt (int *p) { *p=0; } 2. Write the definition of a function doubleIt, which doubles the value of its argument but returns nothing so that it can be used as follows: int x=5; doubleIt(&x); /* x is now equal to 10 */ void doubleIt(int *x) // pass in a pointer as your 'usage' dictates { *x *= 2; // multiply the contents of the pointer by 2 return; } 3. Write the definition of a function tripleIt, which triples its argument but returns nothing so that it can be used as follows: int x=5; tripleIt(&x); /* x is now equal to 15 */ void tripleIt(int *x) // pass in a pointer as your 'usage' dictates { *x *= 3; // multiply the contents of the pointer by 2 return; } 4. Write the definition of a function divide that takes four arguments and returns no value. The first two arguments are of type int. The last two arguments arguments are pointers to int and are set by the function to the quotient and remainder of dividing the first argument by the second argument. The function does not return a value. The function can be used as follows: int numerator=42, denominator=5, quotient, remainder; divide(numerator,denominator,&quotient,&remainder); /* quotient is now 8 */ /* remainder is now 2 */ void divide(int x, int y, int *a, int *b) { *a = x/y; *b = x%y; return; } 5. Write the definition of a function minMax that has five parameters. The first three parameters are integers. The last two are set by the function to the largest and smallest of the values of the first three parameters. The function does not return a value. The function can be used as follows: int a=31, b=5, c=19 big, small; minMax(a,b,c,&big,&small); /* big is now 31 */ /* small is now 5 */ void minMax(int a, int b, int c, int* big, int* small){ if(a<b && a<c) { *small=a; } else if(b<a && b<c) { *small=b; } else { *small=c; } if(a>b && a>c) { *big=a; } else if(b>a && b>c) { *big=b; } else { *big=c; } } Invocation-2 1. zeroIt is a function that takes one argument and returns no value. The argument is a pointer to int. The function stores the value 0 back into the variable pointed to by the argument. x is an int variable that has been declared. Write a statement that sets the value stored in x to zero by invoking the function zeroIt. zeroIt(&x); 2. doubleIt is a function that takes one argument and returns no value. The argument is a pointer to int. The function doubles the value that the argument points to and stores it back. savings is an int variable that has been declared and initialized. Write a statement that doubles the value stored in savings by invoking the function doubleIt. For example, if the value in savings was 7 before your statement, after your statement its value would be 14. doubleIt(&savings); 3. tripleIt is a function that takes one argument and returns no value. The argument is a pointer to int. The function triples the value that the argument points to and stores it back. penalty is an int variable that has been declared and initialized. Write a statement that triples the value stored in penalty by invoking the function tripleIt. For example, if the value in penalty was 7 before your statement, after your statement its value would be 21. tripleIt(&penalty); 4. divide is a function that takes four arguments and returns no value. The first two arguments are of type int. The last two arguments arguments are pointers to int that are set by the function to the quotient and remainder of dividing the first argument by the second argument. The function does not return a value. x and y are two int variables that have been declared and initialized. q and r are two int variables that have been declared. Write a statement that sets the value of q to the quotient of x divided by y, and sets the value of r to the remainder of x divided by y, by calling divide. divide(x,y,&q,&r); 5. minMax is a function that takes five arguments and returns no value. The first three arguments are of type int. The last two arguments are pointers to int that are set by the function to the largest and smallest of the values of the first three parameters, respectively. x, y and z are three int variables that have been declared and initialized. big and small are two int variables that have been declared. Write a statement that sets the value of big to the largest of x, y, z and sets the value of small to the smallest of x, y, z by calling minMax. minMax(x,y,z,&big,&small); Prototypes-2 1. Write a statement that declares a prototype for a function zeroIt, which can be used as follows: int x=5; zeroIt(&x); /* x is now equal to 0 */ void zeroIt(int *x); 2. Write a statement that declares a prototype for a function doubleIt, which has a single parameter of type pointer to int. void doubleIt(int *x); 3. Write a statement that declares a prototype for a function tripleIt, which can be used as follows: int x=5; tripleIt(&x); /* x is now equal to 15 */ void tripleIt(int *x); 4. Write a statement that declares a prototype for a function divide that takes four arguments and returns no value. The first two arguments are of type int. The last two arguments arguments are pointers to int that are set by the function to the quotient and remainder of dividing the first argument by the second argument. The function does not return a value. void divide (int x, int y, int *q , int *r); 5. Write a statement that declares a prototype for a function minMax, which has five parameters. The first three parameters are integers. The last two are parameters that are set by the function to the largest and smallest of the values of the first three parameters. The function does not return a value. void minMax(int x, int y, int z,int *big, int *small); Precedence-2 1. Write an expression that evaluates to 1 more than the value in the location pointed to by the integer pointer variable ip. Thus, if ip points to a location containing the value 3, the expression should evaluate to 4. *ip+1 Write an expression that retrieves the value in the location immediately after the location pointed to by the integer pointer variable ip. *(ip +1) Variables Declarations-4 1. Declare a variable ip that can be assigned the address of an int variable. In other words, declare ip to be of type "pointer to int". int *ip; 2. Declare a variable cp that can be assigned the address of an char variable. In other words, declare cp to be of type "pointer to char". char *cp; 3. Declare a variable dp that can be assigned the address of a double variable. In other words, declare dp to be of type "pointer to double". double *dp; Address-of 1. Assume the variable diff has already been declared. Write an expression whose value is the address of diff. &diff 2. Assume that an int variable diff has already been declared. Assume further a variable diffPointer of type "pointer to int" has also already been declared. Write a statement that assigns the address of diff to diffPointer. diffPointer=&diff; 3. Assume that an int variable counter has already been declared. Assume further a variable counterPointer of type "pointer to int" has also already been declared. Write a statement that makes counterPointer "point" to counter. counterPointer = &counter; Indirection 1. Assume that strikeCounter has already been declared to be a "pointer to int". Assume further that strikeCounter has been initialized -- its value is the address of some int variable. Write an expression whose value is four (4) times the value of the variable that strikeCounter is pointing to. *strikeCounter*4 2. Assume that strikeCounter has already been declared to be a "pointer to int". Assume further that strikeCounter has been initialized -- its value is the address of some int variable. Write a statement that assigns the value 27 to the variable that strikeCounter is pointing to. *strikeCounter=27; 3. Assume that strikeCounter has already been declared to be a "pointer to int". Assume further that strikeCounter has been initialized -- its value is the address of some int variable. Write a statement that adds 22 to the value of the variable that strikeCounter is pointing to. *strikeCounter+=22; 4. Assume that ip1, ip2, and ip3 have already been declared to be of type "pointer to int". Assume further that each of these pointer variables have been initialized -- each points to some int variable. Write a statement that computes the sum of the variables that ip1 and ip2 point to, and assigns that value (the sum) to the variable that ip3 points to. *ip3 = *ip1 + *ip2; Pointer_Arithmetic 1. Assume that ip has been declared to be a pointer to int and that result has been declared to be an array of 100 elements. Assume further that ip has been initialized to point to an element in the first half of the array. Write an expression whose value is the element in the array after the element that ip points to. *ip + 1 2. Assume that ip has been declared to be a pointer to int and that result has been declared to be an array of 100 elements. Assume further that ip has been initialized to point to an element in the first half of the array. Write a statement that makes ip point to the next element in the array. ip += 1; 3. Assume that ip and jp have both been declared to be pointers to int and that result has been declared to be an array of 100 elements. Assume further that ip has been initialized to point to an element in the first half of the array. Write a statement that makes jp point to the element in the array just after the one that ip points to. jp =ip + 1; 4. Assume that ip has been declared to be a pointer to int and that result has been declared to be an array of 100 elements. Assume further that ip has been initialized to point to an element in the first half of the array. Write an expression whose value is the sum of the element that ip points to plus the next two elements. *ip + *ip + 1 + *ip + 2 5. Assume that ip and jp have both been declared to be pointers to int and that result has been declared to be an array of 100 elements. Assume further that ip has been initialized to point to an element in the first half of the array. Write a statement that makes jp point to the element in the array 5 positions after the one that ip points to. jp =ip + 5; 6. Assume that ip, jp, and tp have all been declared to be pointers to int and that result has been declared to be an array of 100 elements. Assume further that ip has been initialized to point to an element in the first half of the array and that jp has been initialized to point to an element in the second half of the array. Write some code that makes jp point to the element that ip was pointing to and that makes ip point to the element that jp was pointing to. tp = jp ; jp = ip; ip=tp; Arrays 1. Assume that ip has been declared to be a pointer to int and that enrollment has been declared to be an array of 20 elements. Write a statement that makes ip point to the first element in the array. ip=enrollment; 2. Assume that ip has been declared to be a pointer to int and that enrollment has been declared to be an array of 20 elements. Write a statement that makes ip point to the last element in the array. ip = &enrollment[19]; 2. Assume that ip has been declared to be a pointer to int and that enrollment has been declared to be an array of 20 elements. Assume also that section has been declared to be an int and has been initialized to some value between 5 and 10. Write a statement that makes ip point to the element in the array indexed by section. ip = &enrollment[section]; RECURSION 1. Assume the availability of a function called printStars. The function receives an int argument. If the argument is positive, the function prints (to standard output) the given number of asterisks. Thus, if the printStars(8) is called, ******** (8 asterisks) will be printed. Assume further that the variable starCount has been declared and initialized to a positive integer. Write some code that prints starCount asterisks to standard output by: first printing a single asterisk (and no other characters) then calls printStars to print the remaining asterisks. if(starCount-1>=0) { cout <<"*"; printStars(starCount-1); } 2. Assume the availability of a function called printStars. The function receives an int argument. If the argument is positive, the function prints (to standard output) the given number of asterisks. Thus, if the printStars(8) is called, ******** (8 asterisks) will be printed. Assume further that the variable starCount has been declared and initialized to a some integer, possibly negative or zero. Write some code that does nothing if starCount is not positive but that otherwise prints starCount asterisks to standard output by: first printing a single asterisk (and no other characters) then calls printStars to print the remaining asterisks. if(starCount>0) { cout <<"*"; printStars(starCount-1); } 3. Write a function called printStars. The function receives an int parameter. If the parameter is positive, the function prints (to standard output) the given number of asterisks; otherwise the function does nothing. The function does not return a value. Thus, if the printStars(8) is called, ******** (8 asterisks) will be printed. The function must not use a loop of any kind (for, while, do-while) to accomplish its job. Instead, it gets the job done by examining its parameter, returning if the parameter's value is not positive. If the parameter is positive, it prints a single asterisk (and no other characters) then (recursively) calls itself to print the remaining asterisks. void printStars(int x) { if (x > 0){ cout <<"*"; printStars(x-1); } } Posted by Just A Hot Blond Girl at 11:06 PM 9 comments: Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest Older Posts Home Subscribe to: Posts (Atom) Followers Blog Archive ▼ 2012 (1) ▼ January (1) My Final Java, C, & C++ Questions & Answers ► 2011 (12) ► October (12) Awesome Inc. template. Powered by Blogger.