Tuesday, June 19, 2012

Homework 10: Vectors-2 Vectors (Part 2)

1. Assume that an array of integers named  a that contains exactly five elements has been declared and initialized. Write a single statement that assigns a new value to the first  element of the array. This new value should be equal to twice the value stored in the last  element of the array. Do not modify any values in the array other than the first element. Instructor's notes: An array is used just like a vector, only it does not have any member functions. That means you cannot use the size member function for this exercise, but you do know the size is 5

a [ 0 ] = 2 * a [ 4 ] ;

2. Assume v is a vector that has been declared and initialized. Write an expression whose value is the number of values that have been stored in v.

v . size ( )

3. Assume that an vector of  int named  a has been declared with 12 elements and that the integer variable  k holds a value between 0 and 6. Assign 15 to the vector element whose index is  k .

a [ k ] = 15 ;

4. Given that an vector of  int named  a has been declared, and that the integer variable  n contains the number of elements of the vector  a , assign -1 to the last  element in  a . Instructor's notes: Do not use a member function in your solution to this problem.

a [ n - 1 ] = - 1 ;

5. Given that an vector of  int named  a has been declared with 12 elements and that the integer variable  k holds a value between 0 and 6. Assign 9 to the element just after  a[k] .

a [ k + 1 ] = 9 ;

6. Given that an array of  int named  a has been declared with 12 elements and that the integer variable  k holds a value between 2 and 8. Assign 22 to the element just before  a[k] . Instructor's notes: This question works exactly the same for vectors, so just switch the name array with vector in the exercise description. In other words, think of a as a vector, not an array.

a [ k - 1 ] = 22 ;

7.  An vector of  int named  a that contains exactly five elements has already 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 the element of the vector indexed by  j . This new value should be equal to twice the value stored in the next element of the vector (i.e. the element after the element indexed by  j ). Do not modify any other elements of the vector! 

a [ j ] = 2 * a [ j + 1 ] ;

No comments:

Post a Comment