CS Logo

Homework 5

 

This homework is intended to gauge your understanding of pointers and arrays.

 

1. (20 points) Write C++ statements to accomplish the following:

 

a. Display the value of the seventh element in array foo.

b. Input a value into element 4 of foo.

c. Initialize the first five values of an integer array, bar, to be 8.

d. Initialize all the values of an integer array, bar, to be 0.

e. Return the value of the fourth element in the array bar without using the [] operator.

 

2. (20 points) Find the error in each of the following:

 

a. char str[5];

    cin >> str;

 

    Where the user enters "Hello"

 

b. int a[3];

   cout << a[1] << " " << a[2] << " " << a[3] << endl;

  

c. float f[3] = { 1.1, 3.2, 11.8, 2.4 };

 

d. double d[2][10];

    d[1,9] = 2.345;

 

e. int x[10][10][10];

    x[1][10][1] = 5;

  

3. (20 points) Read in 5 values from the user, store the values in an array. Now find the sum of the values and print the result.

 

4. (20) Write a C++ statement to do each of the following:

 

a. Declare a pointer lptr that points to a variable of type long.

 

b. Assign the address of variable value1 to lptr.

 

c. Print the value of the variable pointed to by lptr.

 

d. Assign the value pointed at by lptr to value2.

 

e. Declare an array of 20 integers on the heap. (Extra Credit)

 

5. (20 points) Rewrite the program in problem 3 so that you do not use the [] operator anywhere (except to initialize your array). Use pointer notation to complete the program.