{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

discussion6_no_ans

discussion6_no_ans - CS31 Introduction to Computer Science...

This preview shows pages 1–3. Sign up to view the full content.

CS31: Introduction to Computer Science I Discussion 6 May 6, 2011 TA: Paul Wais ( [email protected] ) Discussion Section 1L Information TA: Paul Wais ( [email protected] ) Office Hours: Thursdays 11:30am - 1:30pm in Boelter Hall 2432 Discusion Website: http://www.cs.ucla.edu/ ˜ pwais 1 Midterm: Common Problems Let’s briefly review a couple concepts related to midterm problems that people had trouble with. For a more complete list, see http://cs31.org/10-basic-mistakes 1.1 Return vs Break vs Continue vs cout return exits a function, possibly yielding a value (i.e. if the function is not void ) to the code invoking the function. cout will print something to a terminal. break will exit a loop or a switch statement. If there are several nested loops and/or switch statements, break always exits the body of the loop or switch where the break appears. continue immediately advances a loop to the condition check that occurs after an iteration. What does the example code below print? 1 int findx( int a[], int n, int x) 2 { 3 int i = 0; 4 while (i < n) 5 { 6 if (a[i] != x) 7 { 8 i++; 9 continue ; 10 } 11 else 12 break ; // We could also return i here. Why? 13 } 14 return i; 15 } 16 17 int main() 18 { 19 int arr[5] = {1, 2, 3, 4, 5}; 20 int q = findx(arr, 5, 1); 21 q = findx(arr, 5, 5); 22 findx(arr, 5, 2); 23 cout << findx(arr, 5, 3); 24 } Answer: 1

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
1.2 Pass by Value, Pass by Reference, and Array Parameters Pass by Value means that a function gets a copy of a variable’s value. Pass by Reference means that a function gets direct access to a variable. Array Parameters are always Pass by Reference . What does the example code below print? 1 void pbv( int x) 2 { 3 x * = 10; 4 } 5 6 void pbr( int &y) 7 { 8 y * = 10; 9 } 10 11 void arr( int x[]) 12 { 13 x[0] * = 10; 14 } 15 16 int main() 17 { 18 int x = 1, y = 1; 19 int z[1] = {1}; 20 pbv(x); 21 pbv(z[0]); 22 pbr(z[0]); 23 pbv(y); 24 arr(z); 25 pbr(z[0]); 26 27 cout << "x is " << x << " y is " << y << " z[0] is " << z[0] << endl; 28 } Answer: 1.3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 7

discussion6_no_ans - CS31 Introduction to Computer Science...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online