CS 1 - FINAL

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Is it possible to make an integer array bigger once the program begins to execute? Explain.

No, it is not possible. Once an array is created, it is fixed at that size. If you need for a list of values to be able to "grow" as the program executes, use a vector instead.

Can you \0' -terminate a numeric array?

No, you cannot \0' terminate a numeric array.

Problem #3: What is the value of the following expression? int x = 10, y = 20, z = 30; ! ( x < y ) | | y > z || z > x && z > y

TRUE. Solution: ! (true) || false || true && true false || false || true && true false || false || true false || true true

Problem #4: What is the value of the following expression? int x = 10, y = 20, z = 30; ! (y < z ) || ! (x < y ) || z < x || x < y && x < z && z > x

TRUE. Solution: ! (y < z ) || ! (x < y ) || z < x || x < y && x < z && z > x ! true || ! true || false || true && true && true false || false || false || true && true && true false || false || false || true && true false || false || false || true false || false || true false || true true

Problem #5: What is the value of the following: x is a Boolean variable. x || ! x

TRUE. Solution: It doesn't matter whether x is true or false, the above expression always evaluates to true.

Problem #2: What is the value of the following logical expressions? int i = 2, j = 3 , k =4; i == j || j < k && k > i

TRUE. Relational operators have higher precedence than logical operators && has a higher precedence over ||. Solution: ( i == j) || ( (j<k) && (k > i) ) false || ( true && true ) false || true true true

What technique can a programmer use when he is trying to find the minimum or maximum value in an array?

The "trick" a programmer can use when he or she is trying to find the minimum or maximum value in an array is to set the first value of the array to the minimum or maximum value and use this min or max as the comparison value.

Why is the \0' (null ) character important in C-strings?

The '\0' character is important in C-strings because it indicates the end of the valid data in the character array. Many functions, such as, the cout and string functions, require the \0' character to work properly.

How to convert a number from hex to binary? Example: Convert FA36D to binary. ( in this case it does not matter which side you start from:

Find the equivalent binary bit patterns of each hex number from the table at that is your answer. In this case: F = 1111 A = 1010 3 = 0011 6 =0110 D= 1101 So your answer is: 1111 1010 0011 0110 1101

Problem #1 (Arrays Final): Identify the compiler errors. int list{25}, i; float a, b, c; for(i = 0, i<25; ++i) { listi = 0.0; }

First, on line 1: int list{25}, i; We use square brackets for the array index, not {}. Next, on line 5: listi = 0.0; We do not declare what listi is (like if it is a string, integer, double, character, float, etc.)

What is meant by the term "going out of bounds" on an array? Does C++ automatically check and stop you (the programmer) from going out of bounds with your array? Explain.

Going out of bounds in an array means that you are accessing array elements beyond what is legally declared. For example, if I declare an array of ten integers, int n[10]; and then tried to access n[10], this is going out of bounds with the array. C++ does not check, nor stop you from doing this.

Problem #9 (Branching): Determine output. x = 10 if (x > 50) cout << "Hi"; cout << "Hi2"; cout << "Hi3";

Hi2Hi3. Solution: The last two print statements are not part of the if statement. If you want these two statements also to be a part of the if statement you should put all three print statements within braces {}.

Truth Table?

T && T: true T && F: false F && T: false F && F: false T || T: true T || F: true F || T: true F || F: false

Problem #12: Write the switch statement below as an if else if statement. switch (x) { case 10: i = i +1; break; case 20: i = i +2; break; }

if (x ==10) i = i +1; else if (x ==20) i = i +2;

Problem #18 (Loops): What is missing in the code snippet below? int x; while ( x <= 5) { cout << "Hi"; x = x + 1; }

x is not initialized before the while statement.

Operator Precedence

! * / % + - < <= > >= && ||

Logical Operators

! || &&

Numerical Operators

+ - * / %

Why do programmers divide up the code into Functions such as compute, display etc?

1. NOT to make programs run faster? 2. YES to reuse of code. Makes code size smaller. 3. YES to it divides up the work. It modularizes the work.

Problem #14 (De-Morgan): Rewrite using De-Morgan's Theorem. 1.) (! (x>=0 && x<=10) ) 2.) (! (x<=10 || x>20))

1.) (x<0 || x>10) 2.) (x>10 && x<=20)

Which of the following is a pretest loop and which one is a post test loop? 1) While 2) Do while 3) For

1.) WHILE LOOP IS A PRE TEST LOOP. Solution: Each time we test before we enter. Also called 0 to N loop. Minimum number of times we enter the loop is 0. 2.) DO WHILE IS A POST TEST LOOP Solution: We enter the loop and test at the end of loop to decide whether to go around next time. Also called 1 to N loop. Minimum number of times we enter the loop is 1. 3.) FOR LOOP IS A PRE TEST LOOP Solution: Each time, we test before we enter the loop Also called 0 to N loop. Minimum number of times we enter the loop is 0.

Problem #1 (Functions): What is the output of the code below? This is a pass by value/copy. void calculate (double n1, double n2) { n1 = 5.5; n2 = 6.6; } int main ( ) { double x = 1.1; double y = 2.2; calculate (x, y); cout << x << " " << y << endl; calculate (1.1, 2.2); cout << x << " " << y << endl; }

1.1 2.2 1.1 2.2 In the example, the function main calls the function calculate twice. In each case, the parameters are passed to function calculate by value/copy. In pass by value/copy, the values of actual parameters are copied into formal parameters. For the first call to calculate, the values of x and y are copied into n1 and n2 respectively. For the second call to calculate, 1.1 and 2.2 are copied into n1 and n2 respectively.

Problem #2 (Functions): What is the output of the code below? This is a pass by reference/alias. void calculate (double & n1, double & n2) { n1 = 5.5; n2 = 6.6; } void main ( ) { double x = 1.1; double y = 2.2; cout << x << " " << y << endl; calculate (x, y); cout << x << " " << y << endl; }

1.1 2.2 5.5 6.6 Discussion: In the code, the values of x, y before call to calculate are 1.1 and 2.2. After the call the values are 5.5 and 6.6. This is because the actual parameters x and y are being passed by reference/alias. Therefore, formal parameters n1 and n2 are not separate variables but just new names for x and y. When the called function calculate changes the value of n1 and n2, it is really changing the values of x and y.

Problem #13 (Loops): What is the output? count = 1; while (count<=100) { count = count +1; } cout << count << endl;

101. We enter the loop initially when count is 1. Inside the loop count is incremented by 1. We go back to while statement, the count is now 2. We reenter the loop. We enter the loop for count = 1, 2 ...100 when count is 101 we don't enter the loop , we go past the loop and display 101.

Problem #28 (Loops): How many times does the loop iterate? for (i= 0; i <=10; i++) doSomething();

11. Discussion: The above loop is a poorly written loop. It appears from looking at the For statement that it may go around 10 times. But actually it goes around 11 times. To improve readability of the loop and to make it go around 11 times, the above loop should be written as below: for (i= 0; i < 11;i++) doSomething(); for (i=1; i <= 11; i++) doSomething( ): My Discussion: Remember, in this for loop, we need to count EVERY TIME WE GO INTO THE LOOP. NOT WHEN WE START RE-LOOPING.

Convert to binary: 27

11011. Q | R 27/2 = 13 | 1 13/2 = 6 | 1 6/2 = 3 | 0 3/2 = 1 | 1 1/2 = 0 | 1 We put together our remainders from bottom to top.

Add together: 1101101 1101111

11011100. Note that adding 1 1 will be 0 with a remainder of 1. Adding 1 1 1 will be 1 with a remainder of 1.

Add together: FAC 3BD

1369. Note that adding something together that gets you a number bigger than 16 (because that's how many numbers we have on chart) requires us to subtract by 16. In this case, C=12, D=13 so 12+13 which is 25. Now we subtract by 16 which gives us 9. We have a remainder of 1 because WE SUBTRACTED BY 16 ONE TIME.

Problem #19 (Loops): What is the output of the code snippet below? int total = 0, num; string in; cout << "Enter a whole number" << endl; cin >> num; while (num != -1) { cout << "Enter a whole number" << endl; cin >> num; total = total + num; } cout << total; For the above, assume that the user provides the following sequence of numbers as input. 20 10 5 - 1

14. Solution: The above is a poorly written loop. In a well written loop, Process Part that assigns value to total should be the first statement in the loop. The Update Part inputting the whole number should be the last statement in the loop. The effect of this poorly written loop is: 1. The first value entered does not get totaled. 2. The -1 value gets erroneously totaled. My Explanation: We first enter 20, then because 20 is not equal to -1, we enter the while loop. Now we enter 10, then do the total which is just (0+10). We loop again because the number we input was 10, and 10 is not equal to -1. NEW TOTAL IS NOW 10. We enter 5, then do the total which is just (10+5). We loop again because the number we input was 5, and 5 is not equal to -1. NEW TOTAL IS NOW 15. We enter -1, then do the total which is just (15+-1). We do not loop anymore because the number we input was -1, and -1 is equal to -1. We now just get an output of 14 as we exit the loop.

Convert to decimal: AB

171. Left to right. B*16^0 + A*16^1 Convert letters using the table: = 11 * 1 + 10 * 16 = 171

Problem #17 (Loops): What is the output? x = 2; while ( x<6) { cout << x << " "; x ++; }

2 3 4 5 Solution: We enter the loop for x values of 2, 3, 4, 5 and output them. When x is 6 we don't enter the loop and we don't display x value.

Problem #4 (Functions): In the code below, what are the value of imain and ifloat after return from method call test. void test ( int i, float f) { i=i+1; f=f+2; } void main ( ) { int imain=2 ; float fmain=5.0 ; test(imain,fmain); //display imain, fmain }

2 5.0 Discussion: imain and i are two different variables. (pass by copy/value). fmain and f are two different variables (pass by copy/value). The function test can modify the contents of i but it cannot modify the contents of imain because they are two different variables (pass by copy/value). Similarly, the function test can modify the contents of f but it cannot modify the contents of fmain because they are two different variables (pass by copy/value). Therefore, during call to test, the contents of imain and fmain remain unchanged. My Discussion: Basically, because this is a pass by value, in our void main function, the actual argument doesn't change. Also our void test function doesn't tell us to console our anything, so we ignore.

Problem #3 (Functions): What is the output of the code fragment? void test( int I, float f) { I = I + 1; f = f + 2.0; } void main ( ) { int imain = 2; float fmain = 5.0; test (2, 5.0); cout << imain << " " << fmain<< endl; test (imain, 5.0); cout << imain << " " << fmain<< endl; test (2, fmain); cout << imain << " " << fmain<< endl; test (imain, fmain); cout << imain << " " << fmain<< endl; }

2 5.0 2 5.0 2 5.0 2 5.0 In pass by value/copy, the actual parameter can either be a value (expression, constant) or a variable In the code above, each of the call to test is valid.

Problem #5 (Functions): In the code above, what are the value of imain and fmain after return from function call test? void test ( int i, float & f) { i=i+1; f=f+2; } void main ( ) { int imain=2; float fmain=5.0; test(imain,fmain); //display imain, fmain }

2 7.0 Discussion: imain and i are two different vaiables. (pass by copy/value).fmain and f are two names for the same variables (pass by alias/reference). The function test can modify the contents of i but it cannot modify the contents of the variable imain because they are two different variables (pass by copy/value). The function test can modify the contents of fmain because fmain and f are the two names for the same variable (pass by alias/reference). Therefore, during call to test, the contents of imain remain unchanged but the contents of fmain change from 5.0 to 7.0 because the function test adds 2 to them. My Discussion: Here, doing our void main function, we know that our imain in test(imain, fmain) IS A PASS BY VALUE. So, we know that our actual value will not change. However, we know that fmain IS A PASS BY REFERENCE. So, we know that the actual value will change.

Problem #21 (Loops): What is the output? (NESTED) total = 0; outerCount = 1; while (outerCount <= 4) { innerCount = 1; while (innerCount <= outerCount) { total = total + innerCount; innerCount ++; } outerCount ++; } cout << total;

20. Solution: We go around the outer loop a total of 4 times. For each pass through the outer loop we go around the inner loop one or more times depending upon the value of the outerCount. We go around the inner loop equal to the value of the outer count. The outerCount varies from 1 to 4 hence we go around the inner loop 1 times, 2 times, 3 times, and 4 times respecitively. Each pass through the inner loop innerCount varies from 1 to the value of the outercount. The value of the outerCount and the corresponding values of the innerCount are given below given. Add all the inner Count values, we get 1+(1+2)+(1+2+3)+(1+2+3+4) 1+3+6+10 20

Problem #6 (Functions): In the code below, what are the value of imain and ifloat after return from function call test? void test ( int & i, float f) { i=i+1; f=f+2.0; } void main ( ) { int imain=2; float fmain=5.0; test(imain,fmain); //display imain, fmain }

3 5.0 Discussion: imain and i are two names for the same variables (pass by alias/reference). fmain and f are two different variables. (pass by copy/value). The function test can modify the contents of imain because imain and i are two names for the same variable (pass by alias/reference). The function test cannot modify the contents of the variable fmain because f and fmain are two different variables (pass by copy/value). Therefore, during call to test, the contents of imain change from 2 to 3 because the method test adds 1 to them but the contents of fmain remains unchanged.

Problem #8 (Branching): Determine output. z = 3; if (z>5) z = z +1 else if (z>7) z = z + 2; cout << z;

3. Solution: In an if else if statement, tests are done in a sequence. In the above case all tests fail. So if else if statement is skipped.

Problem #22 (Loops): What is the output? total = 0; for (count = 3; count <= 6; count ++) total = total + (2* count); cout << " The total is : " << total << endl;

36. Solution: For this, we go inside the for loop because it is true. Now we solve the total which is (0+(2*3)) to get 6. Loop again and increment to 4. Now we solve the total which is (6+(2*4)) to get 14. Loop again and increment to 5. Now we solve the total which is (14+(2*5)) to get 24. Loop again and increment to 6. Now we solve the total which is (24+(2*6)) to get 36. We exit loop because if we increment to 7, the for loop becomes false. Discussion: If since we do not use brackets {}, our for loop only applies to the statement right below. Not the cout statement on the very bottom. If we used brackets to include the cout statement, we would get an output of: The total is : 6 The total is : 14 The total is : 24 The total is : 36 Since we are telling the program to console out, and the reloop. In the original problem, we console out after we exit the loop.

convert 1101100011 to hexadecimal.

363h. We simply split into groups of four starting from the right. Then if we do not have even sets of four, we will add a 0 to the left-most side. Then, simply use the conversion chart.

Problem #3 (Arrays): What is the output of the code snippet below? int x [] = {5,2,9}; for(int i=0 ; i<3 ; i++) { cout << x[i] << endl; }

5, 2, 9. Discussion: In this code, notice how our for loop makes us go around 3 times, meaning we take from the array declaration 3 numbers which are 5, 2, and 9.

Problem #7 (Branching): Determine output. x = 5; if (x>1) x = x +1; else if (x>3) x = x + 2; else x = x + 3; cout << x;

6. Solution: In an if else if statement, tests are done in a sequence. When a test passes, the if else if statement ends. The remaining tests are not done.

Problem #11 (Branching): What is the output? char ch = 'A'; int i = 0; switch (ch) { case 'A': i = i +1; case 'B': i = i +2; case 'C': i = i +3; } cout << i << endl;

6. Solution: In the above code, for case 'A', break statement is missing. When break statement is missing, the program continues to the next instruction until it encounters a break statement or switch statement finishes. In the above code, the program executes the following sequence: i = i +1; i = i + 2; i = i + 3;

Convert to hex: 105

69. 1.) Divide 105 (given #) by 16 2.) This gives you a quotient of approx. 6 and remainder of approx 9. 3.) Now, we keep dividing until the quotient is 0. So now divide 6 by 16. 4.) The quotient is approx 0 and remained of approx. 6. 5.) Last, we get our answer by looking at our remainders and putting them together, from bottom to top.

How to convert a number from binary to hex?

6E. Simple: Given a binary value of 1101110, we first need to separate the binary by sets of four. If we do not have a set of four, add a 0 to the left, like below: 0110 1110 Then, we just look at our chart and convert to hexadecimals. Complex: Given a binary value of 1101110, we first need to separate the binary by sets of four. If we do not have a set of four, add a 0 to the left, like below: 0110 1110 Next, from the right to left of every set, do 2^n and increase the amount each time as we go to the left. Start from 0 like so: 0 1 1 0 1 1 1 0 2^3 2^2 2^1 2^0 2^3 2^2 2^1 2^0 Then, multiply our answers from doing the power by the original binary value. REFER TO PHONE IMAGE! LAST, we look at conversion chart and covert numbers to hexadecimals.

Relational Operators

== != <= >= > <

Problem #25 (Loops): What is the output? max = 10; count = 20; do { cout << "A"; count ++ } while (count <= max); cout << "B";

A B. Discussion: In a do while loop we will always execute the inside once. Now, because 20 (count) is NOT LESS THAN OR EQUAL TO 10 (max), we exit the loop. We told the program to console out A in the do while loop, and then we console out B as we exit. So we get an output of A B. This is a post test (1 to N) loop, we enter the loop at least once.

What type of array is a character string?

A character string is an array of chars, as seen in the following declaration. char Name[40];

Problem #6 (Final Arrays): sk the user for a character array and then reverse the characters. If the user entered Hello World, the new string would read dlroW olleH. #include <iostream> using namespace std; int main() { char saying[50], revSaying[50]; int i; cout << "\nEnter a saying."; cin.getline(saying,50); for(i = 0; i< 50; ++i) { revSaying[i] = saying[50-i]; } return 0; }

A problem is that reversing action shown here will reverse all fifty characters. The leading characters in the revSaying will contain "trash" from the trailing portion of saying as well as the '\0'. If you tried to write the reversed C-string, you'd maybe see trash only. To fix this, we should find the length of the input. This length is used to reverse just the valid characters in the string, like this: int length = strlen(saying); // reports # of letters for(i = 0; i < length; ++ i) { revSaying[i] = saying[ length - 1 - i ] ; } //then put a '\0' at end of the revSaying revSaying [ length - 1 ] = '\0';

Problem #1 (Arrays) : What is the size of above array? And what is the valid index range for the array x above. double x[10];

Array Size: 10, and the valid index range is 0 to 9. My Discussion: Array values are counted from 0.

How are arrays passed?

Array are passed by Address Copy Discussion: The copy of the array address is passed from caller to callee.

Problem #26 (Loops): What is the output? max = 10 for ( count = 20; count <= max; count ++) { cout << "A"; } cout << "B";

B. Discussion: For loop is a pretest (0 to N) loop. We test with count = 20 and max = 10, the test fails, we never enter the loop.

Problem #29 (Loops): What is the output? For (count=1; count>5; count++) cout << "Hi"; cout << "Bye";

Bye. Discussion: The test does not pass the very first time. So we never enter the loop.

Numeric Expression

Contains numeric operators and numeric operands and evaluate to get a numeric value. int x = 5; double z = 2.3; // Numerical Expression: 12 13.5 x + 12 13.5 * z (x-2) * (z/3))

Problem #10 (Branching): Determine output. x = 10; z = 5; if (x < 5) if (z < 2) cout <<"Hi"; else cout << "Hi2";

DISPLAYED NOTHING. Solution: First, rewrite the code, and indent properly like below. Secondly, note that we have a dangling else statement (when there is an else statement that can belong to more than one if statement). According to the syntax rules, a dangling else always goes with (belongs to) the closest if statement. x = 10; z = 5; if (x < 5) if (z <2) cout << "Hi" << endl; else //a dangling else. belongs to the nearest if cout << "Hi2" << endl; If you want the dangling else to belong to the outer (farther) if statement you will use braces {} to indicate that as shown below. x = 10 z = 5 if (x<5) { if (z<2) cout << "Hi" << endl; } else cout << "Hi2" << endl; Reference: https://www.cs.drexel.edu/~jpopyack/Courses/GovSchool/2005/Wi04/lectures/08.2_nested_conditionals/DanglingElse.html?CurrentSlide=3

Problem #27 (Loops): Enumerate the number of times each of the following loop iterates (goes around). for (count=0;count<5;count++) doSomething(); for (count=1; count<=5;count++) doSomething(); for (count = 5;count>=1;count--) doSomething(); for (count= 5; count >0; count--) doSomething();

Each of the above loops iterates (go around) 5 times. My Discussion: Remember, in this for loop, we need to count EVERY TIME WE GO INTO THE LOOP. NOT WHEN WE START RE-LOOPING.

List a set of data that could be stored in a one-dimensional array.

Example : One dimensional array: phone bills data for a year.

Problem #6: What is the value of the following: x is a Boolean variable. x && ! x

FALSE. Solution: It doesn't matter whether x is true or false, the above expression always evaluates to false.

Problem #1: What is the value of the following expressions? int i = 5, j =7 k=9; j<5 || i<=7 && k==10;

FALSE. Relational operators have higher precedence than logical operators && has a higher precedence over ||. Solution: (j<5 || (i<=7 && k==10)) false || true&&false false || false false

If you declare two arrays sized to 10 and you attempt to assign both arrays out to the 12th element, what is the result of this action?

If the arrays are declared together in the program, int N[10], M[10]; assigning into M[10] and M[11] will actually overwrite the N[0], N[1] elements. If these are first declared in the program, accessing N[10] will cause the program to crash. If there are other variable declared before it, assigning into N[10] and N[11] will corrupt this other data stored adjacent to the N array.

Problem #20 (Loops): What is the output? cout << "X"; count = 1; while (count < 2); { cout << "Y"; count ++; } cout << "Z";

Infinite Loop. Solution: Putting semicolons after while and if statements in C++. In while, it will enter an infinite loop.

Input (Incoming) parameters & output (outgoing) parameters.

Input or Incoming parameters: These are parameters that carry data into the method.If a parameter is passed by value/copy, it is always an input/incoming parameter for the method. Output or outgoing parameters: These are parameters that carry data out of the method.If a parameter is passed by alias/reference, it can be an input/incoming parameters if the caller uses it to pass a value to the called method. It can also be an output (outgoing) parameter, if the called method puts something in it for the caller to receive it on return after the call.

Problem #5 (Arrays): What is the output of the code snippet below? int x [] = {1,2,3,4}; for(int i=4; i>=0;i--) { cout << x [i] << endl; }

It will display 1 2 3 4 and some junk value at x[4] or give runtime error. Discussion: The loop will attempt to access x[4] during the first iteration. Since x[4] is non-existent, it will display either some junk value at that location or get runtime error. My Discussion: The array declaration gives us only 4 numbers. Our loop tells us to go around 5 times, but because our array declares 4 numbers, we will get a junk value. x[0] = 1 | WHEN i = 0 x[1] = 2 | WHEN i = 1 x[2] = 3 | WHEN i = 2 x[3] = 4 | WHEN i = 3 x[4] = N/A

Problem #6 (Arrays): What is the output of the code snippet below? int x[] = {1,2,3,4}; for (int i=3; i>=0; i--) { cout << x [i] << endl; }

It will display 1 2 3 4. Discussion: The array declares 4 values. Our loop tells us to go around 4 times. In this case, we will display everything in the array declaration, and no junk value will occur like in other examples.

Problem #7 (Arrays): What is the output of the code snippet below? int x[] = {10,20,30,40,50,60}; for (int i=0; i<6; i=i+2) { cout << x[i] << endl; }

It will display 10 30 50. Discussion: The array declares 6 values. Our loop tells us to go around only 3 times. However... x[0] = 10 x[1] = 20 x[2] = 30 x[3] = 40 x[4] = 50 x[5] = 60 Above is our array values initialized at 0, however, our loop tells us that i = 0, 2, 4. Now look above again and see how 0 = 10, 2 = 30, 4 = 50.

Problem #8: What is the output of the code snippet below? int x[]={10,20 ,30, 40 ,50 ,60}; for (int i=0; i<3; i++) { cout << (x [i*2] << endl; }

It will display 10 30 50. Discussion: Our array declares 6 values, and our loop tells us to go around 3 times. x[0] = 10 x[1] = 20 x[2] = 30 x[3] = 40 x[4] = 50 x[5] = 60 Our console out then tells us to multiply i by 2. So we enter loop at i = 0, then i = 1 * 2, then i = 2 * 2.

Problem #4 (Arrays): What is the output of the code snippet below? int x [] = {4,5,6}; for(int i=0; i<=3; i++) cout << x[i] << " " << endl;

It will display 4 5 6 and some junk value at x[3] or give runtime error. Discussion: The valid index range for the above array is from 0 to 2. There is no x[3]. So you will either print some junk value at that location or get runtime error because we only have 3 numbers in our array declaration. x[0] = 4 x[1] = 5 x[2] = 6

Logical Expression

Made of logical operators and boolean operands and evaluates a Boolean value. int i = 5, j=7, k=9; bool b1=true, b2=false; // Logical Expressions: b1 b2 ! b1 ! b2 b1 || b2 b1 && b2 i < j && j <k i < j || j <k

Relational Expression

Made of relational operators and numeric operands and evaluate to get a Boolean value. int x = 10, y = 20, z = 30; double d1 = 5.2, d2 = 6.5; // Relational Expressions: (x < y) (x > 5) (x == y) (x != y) (d2 > d1)

In Pass by alias/reference, can the calling method pass a value?

No. Using pass by alias/reference, the formal parameters cannot be a value (expression, constant), it must be a variable name. This is because, in pass by alias/reference, the formal parameter and the actual parameter are two names for the entity. This entity has to be variable because the called function may want to store a value in it.

Must actual parameters and formal parameters have different names?

No. An actual parameter and its corresponding formal parameters may have the same or different names.

Is there a way to write the entire contents of a numeric array in one cout statement?

Not directly nor easily. You could write one HUGE cout statement, listing each element of the array.

Problem #3 (Arrays Final): Identify the compiler errors. #include <iostream> using namespace std; char [] FillArray(); int main() { int values[75]; values = FillArray(); return 0; }

On line 5: char [] FillArray(); You cannot use an array and function, or you cannot return an array from a function. On line 10: values = FillArray(); Values is invalid.

Problem #4 (Arrays Final): Identify the compiler errors. #include <iostream> using namespace std; void SortArray(int values[]); int main() { int values[75]; SortArray(values[75]); return 0; } void SortArray(int values) { for(i = 0; i < 75; ++i) { if(values[i] < values[i-1]); values[i] = values[i-1]; } }

On line 9: SortArray(values[75]); Do not put [75] in the call. This will try to send one value from the array. My Discussion: Basically for line 9, make sure our function when calling, does not have an array number inside it because we already declare that the array has 75 numbers.

Problem #5 (Arrays Final): Fill a 100-element floating point array with the values 0.01, 0.02,... , 0.99, 1.0. #include <iostream> using namespace std; int main() { float x[100]; int i; for(i = 1; i <= 100;++i) { x[i] = i/100; } return 0; }

On line 9: for(i = 1; i <= 100;++i) We are out of bounds at <= 100, should be < 100 because our array is at x[100], initialized at 0 so 0~99. On line 11: x[i] = i/100; We are asking for floating points like 0.01, 0.02, ... Remember that integer / integer is an integer, but floats take over if they are divided by an integer

Which of the following is a valid function header? a. void display b. void display( ) c. display( )

Only b) is valid.

Problem #9: For the code snippet below, what are the contents of the array x at the end of the loop? int x [4]; for (int i=0; i<4;i++) { x[i] = i+3; if (i>=4) x[i-1] = x[i]+4; } //display content of the array. for (int i=0; i<4; i++) cout << x[i] << " ";

Output will be 3, 4, 5, 6. My Discussion: Our array declaration is 4 values. We move to our for loop, where we enter at 0 and go around 4 times. x[0] = 0 + 3, then x[1] = 1 + 3, then x[2] = 2 + 3, then x[3] = 3 + 3 And now x[4] = {3, 4, 5, 6} We do not enter if statement, doesn't execute because it is not true. But we enter our next for loop, where we go around 4 times. x[0] = 3 x[1] = 4 x[2] = 5 x[3] = 6

Problem #11 (Arrays): For the code snippet below, what are the contents of the array x at the end of the loop? int x [4]; for (int i=0; i<4; i++) { x[i]=i+1; if (i>=2) x[i-1]=x[i]+2; } //display contents of x for (int i=0; i<4; i++) cout << x[i] <<" ";

Output will display 1 5 6 4. My Discussion: Our array declares 4 values, initialized at 0. We go to our for loop where we go around a total of 4 times (i = 0~3). In the loop, x[0] = 0 + 1, x[1] = 1 + 1, x[2] = 2 + 1, x[3] = 3 + 1 However, when i is >= 2, we do x[2-1] = x[2] + 2, and x[3-1] = x[3] + 2. We now have x[0] = 1, x[1] = 2, x[1] = 5, x[2] = 6, x[3] = 4 Now we move into our last for loop where we enter a total of 4 times, (i = 0~3). We display x[0], x[1], x[2], and x[3], which is 1, 5, 6, 4 consecutively.

Literals

Represents fixed values (1, 1.1, c). Fives types: integer, float, character, string, boolean, escape values.

How to convert a number from binary to decimal? Example: 1011011

Reverse the original given binary number first. 1 -> 1 = index 0 = 2 ^ 0 = 1 0 -> 1 = index 1 = 2 ^ 1 = 2 1 -> 0 = index 2 = 2 ^ 2 = 4 1 -> 1 = index 3 = 2 ^ 3 = 8 0 -> 1 = index 4 = 2 ^ 4 = 16 1 -> 0 = index 5 = 2 ^ 5 = 32 1 -> 1 = index 6 = 2 ^ 6 = 64 NOW, ADD EVERY NUMBER WITH A 1 (THE REVERSED BINARY / THE COLUMN AFTER "->") so, 1 + 2 + 8 + 16 + 64 = 91

Problem #15 (De-Morgan): What is the ending condition for the loop? int x = 10 while (x >9 && x<50) { x = x +1; }

Rewrite: (!(x>9 && x<50)) Use DeMorgan's Theorem ANSWER: (x <=9 || x>=50) (EITHER ANSWER)

Problem #16 (De-Morgan): What is the ending condition for the loop? int z = 1 while (z <10 || z >20) { }

Rewrite: (!(z<10 || z>20)) Use DeMorgan's Theorem ANSWER: (z>=10 && z<=20) (EITHER ANSWER)

What happens if you forget to place a null character in a character array and then write the array using cout?

The cout object will continue to write characters to the screen until it sees a NULL character '\0'.

Why is the for loop a handy tool when working with arrays?

The for loop provides an integer count/index value that can be used to traverse the array accessing each element.

Problem #10 (Arrays): For the code snippet below, what are the contents of the array x at the end of the loop? int x [6]; for (int i=0; i<6;i++) { x[i] = i+3; if (i>=4) x[i-1] = x[i]+4; } //display content of the array. for (int i=0; I < 6; i++) cout << x[i] << " ";

The output will be 3 4 5 11 13 8. My Discussion: Our array declares 6 values, but initialized at 0. We then go to our for loop where we go around 6 times. x[0] = 0 + 3, x[1] = 1 + 3, x[2] = 2 + 3, x[3] = 3 + 3, x[4] = 4 + 3, x[5] = 5 + 3 However, when i is 4 or 5, we enter our if statement. x[4-1] = x[4] + 4, x[5-1] = x[5] + 4 Now, our values are x[0] = 3, x[1] = 4, x[2] = 5, x[3] = 11, x[4] = 12, x[5] = 8 We then display our array values when array is 0, 1, 2, 3, 4, 5.

What are actual and formal parameters?

The parameters provided in a function call are called actual parameters. (These are the parameters passed by the caller). The parameters specified in the function header are called formal parameters. (These are the parameters received by the called function).

Problem #2 (Arrays): Which of the following is valid initialization? 1. int x = {10,20,30}; 2. int x [ ] = {10,20,30}; 3. int x [ ] = {10 20 30};

The second form is valid. Discussion: Others are invalid. The third is invalid because the values are not separated by commas. The first is invalid because x is not an array (missing angular brackets)

What does the size value represent in an array declaration statement?

The size value represents how many array elements are being reserved. For example, int n[50]; where 50 is the size, means we are reserving 50 integer elements.

What is meant by the term zero-indexed?

The term "zero-indexed" means that the first value (or element) in an array is referenced by using a zero, such as Numbers[0], instead of using a one, such as Numbers[1].

What data type must be used as an array index?

The type of value that must be used as an array index is an integer.

Problem #2 (Arrays Final): Identify the compiler errors. #include <iostream> using namespace std; int main() { float numbers[100]; int j; cout << numbers; }

There are no compiler errors here. However, it may ask to return 0.

Problem #8 (Array Finals): Assume that two arrays, x and y, are both fifty-element arrays and that they contain double values. This function is supposed to switch the lowest x value with the lowest y value; that is, the lowest value in x is switched with the lowest value in y. void Switcher(double x[], double y[]) { double low_x = 0, low_y = 0; int i, i_x, i_y; for(i = 0; i < 50; ++ i) { if(x[i] < low_x) low_x = x[i]; //find low x i_x = i; //remember x index if(y[i] < low_y) low_y = y[i]; //find low y i_y = i; //remember y index } y[i_y] = low_x; x[i_x] = low_y; }

This routine initially sets the low values to 0.0, and we do not know the range of values for these arrays. Chances are, unless the arrays contain all negative values, we will not find the correct low values. A second problem is due to the fact that both if statements do not contain { }, both assignment statements into i_x and i_y will be performed at each pass of the loop. The resulting action is that the last two values always will be switched. There are three corrections. First set the initial low values to the first element in the arrays, set the initial index values to 0, and use the { } with the if statements. double low_x = x[0], low_y = y[0]; int i, i_x = 0, i_y = 0; for(i = 0; i < 50; ++ i) { if ( x[i] < low_x) { low_x = x[i]; i_x = i; } // same for the y array } After the for loop, we must then assign the low values into the opposing arrays, like this: x[i_x] = low_y; y[i_y] = low_x;

Name three situations in which data are maintained ideally as an array.

Three situations where data ideally is maintained as an array include: 1) daily information for weather data, grouped by months or years; 2) text information stored as a character array; and 3) the closing price of an individual stock for a period of five years.

Problem #7 (Array Finals): Fill a character array with the uppercase alphabet (place A in [0], B in [1], etc.). #include <iostream> using namespace std; int main() { char alphabet[26]; int i; for(i = 0; i< 26; ++i) { alphabet[i] = i; } return 0; }

To put chars values into alphabet, need to remember chars are stored as ASCII integer codes. To fix this assignment, the integer must be offset to the ASCII 65 (for A) and cast into a char. Two fixes are shown here: for(i = 0; i < 26; ++ i) { alphabet[i] = static_cast<char> (i + 65); } or for(i = 65; i < 91; ++ i) { alphabet[i] = static_cast<char>( i ) ; } We get 65 because ASCII 65 is A and so on is B, C, D... ALSO 90 is end of alphabet.

De-Morgan's Theorem

Use DeMorgan's law: !( P && Q) = !P || !Q !( P || Q) = !P && !Q For: 1.) !(x!=5 && x!=7) 2.) !(x<5 || x>=7) 3.) !( !(a>3 && b>4) && (c != 5)) My answers: 1.) x==5 || x==7 2.) x>=5 && x < 7 3.) (a>3 && b>4) || c==5

When passing an array to a function, what is actually passed to the function?

When a program is passing an array to a function (in a call statement), the address of the first element of the array is passed to the function.

When you create an array and pass it to a function, a pointer is actually passed to the function. Explain how this is the C++ language's original call by reference technique.

When a program is passing an array to a function (in a call statement), the address of the first element of the array is passed to the function. It is the original call by reference because the address (reference) to the array is being passed.

Is there a performance overhead in calling a function?

Yes, calling a function has overhead involved.

Can the BubbleSort be changed so it sorts from high to low? What do you need to change in the code to make this happen?

Yes, it can be changed to sort from high to low. The comparison statement in the nested for loop is where the low to high/high to low order is established. If the comparison is if( numbers[j-1] > numbers[j] ) this swaps higher values down in the array, so it is ordered low to high. If the comparison is if( numbers[j-1] < numbers [j] ) this swaps lower values down in the array, so it is ordered high to low. You only need to switch the < and > to change the resultant sort order in the array.

Is it possible to have an array of C-strings? Is so, give an example of the declaration.

Yes, you can create an array of C-strings. It is actually a two-dimensional C-string array. For example, to create an array of 10 C-strings, each 50 chars long, you'd declare it like this: char text[10][50];

When a parameter is passed by copy, can the actual parameter be a value (constant, expression) instead of a variable.

Yes.

What do you see if you cout the name of an array?

You will see the hex address that is the [0] element location in memory. The name of the array is actually a pointer that is pointing to the first element in the array.

How many different values 4 bytes can hold?

a. The answer to this is 2 to the power of the number of bits. So in the above question, the answer will be 2^32 (2 to the power of 32). b. 1 byte = 8 bits, 4 bytes = 4*8=32 bits

&& Truth Table

false&&false=false false&&true=false true&&false=false true&&true=true All must be true, to be true

|| Truth Table

false||false=false false||true=true true||false=true true||true=true All must be false, to be false

Problem #23 (Loops): Write the following while loop as a for loop. count = -3; while (count <= 10) { total = total + count; count ++; }

for (count = -3; count <= 10; count ++) { total = total + count; } Discussion: Every While statement can be converted to an equivalent For statement. Every For statement can also be converted to an equivalent While statement.

Problem #24 (Loops): Write a piece of code that enters a loop and asks the user to input a non-negative number. If the user enters a negative number, the code goes back into the loop and asks the user again to enter a non-negative number. The code keeps going back into the loop until the user enters a non-negative number. Notice that the code enters the loop at least once. This is an application of 1 to N loop. Therefore, use a Do While statement.

int num; do { cout << "Enter a number"; cin >> num; } while (num < 0); Discussion: In this do while loop, the user inputs a number. If that number make the while statement true, we keep going in the loop. For example, if we entered -1, -2, -3... because it is LESS THAN 0. Once we enter something that makes the while loop false, we exit the loop. So if we entered a non-negative number.

What are the variables in C++?

int, double, char, string, bool


Set pelajaran terkait

Aller Retour Questions Chapter 1 à 12

View Set

NR 412 Vision, Hearing, Vestibular

View Set

Muscles moving the ankle joint, foot, and phalanges (Inversion, Eversion, Dorsiflexion, Plantarflexion)

View Set

John F. Kennedy + Nonfiction Study Guide

View Set