discussion8_no_ans

Discussion8_no_ans - CS31 Introduction to Computer Science I Discussion 8 TA Paul Wais([email protected] Discussion Section 1L Information TA Paul

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
CS31: Introduction to Computer Science I Discussion 8 May 20, 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 Survey! If you haven’t already, please take a moment after class to fill out a brief survey rating this Disc. Section: http://goo.gl/J6uGA 2 Pointer Practice What does the following code print? 1 double * findMin( double * a, int n) 2 { 3 if (n > 0) 4 { 5 double minVal = a[0]; 6 double * min = &a[0]; 7 for ( int i = 1; i < n; i++) 8 { 9 if (a[i] < minVal) 10 { 11 minVal = a[i]; 12 min = &a[i]; 13 } 14 } 15 return min; 16 } 17 else 18 return NULL; 19 } 20 21 int main() 22 { 23 double nums[] = {0.1, 0.2, 0.4, 0.001, 0.8}; 24 double * min; 25 min = findMin(nums, 5); 26 cout << * min; 27 } Answer: 1
Background image of page 1

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

View Full DocumentRight Arrow Icon
Suppose we were to change the line in main() min = findMin(nums, 5); to min = findMin(nums, 0); What would the new program print? Answer: 2.1 Pointer Pass-by-Reference and Iteration with Pointers Last time we discussed that when a function gets called with a pointer, the function actually gets a copy of the pointer’s address. By default, pointer arguments are pass by value. It’s also possible to pass pointers main() in the above program to: 1 int main() 2 { 3 double nums[] = {0.1, 0.2, 0.4, 0.001, 0.8}; 4 double * min; 5 setMin(nums, 5, min); 6 cout << * min; 7 } Write a function setMin() that behaves the same as findMin() except that setMin() assigns a pointer argument to the minimum value of an array. Now, rewrite setMin() to use no square brackets. 2
Background image of page 2
Finally, rewrite setMin() without using any local variables of type int (other than the parameter n). 2.2
Background image of page 3

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

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 07/06/2011 for the course CS 31 taught by Professor Melkanoff during the Spring '00 term at UCLA.

Page1 / 7

Discussion8_no_ans - CS31 Introduction to Computer Science I Discussion 8 TA Paul Wais([email protected] Discussion Section 1L Information TA Paul

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online