CSCI 152 Quiz 2 ( 1 Mar ) Name _____KEY_______________
Spring 2005
1.
Given the following declarations:
int list[10] = { 7, 1, 5, 4, 3, 8, 0, 9, 6, 2 };
int n = 5;
Answer these questions, using the original values for each
question:
a) Write a statement which will
decrease the value
of the last element by 1. ________list[9]
= list[9] - 1
b) What is the value of list [n] ? ________8____________________
c) What is the value of list [n - 1] ? ________3____________________
d) What is the output of this
loop:
for (n = 1; n < 9; n = n + 2)
cout << list [n]; ________1 4 8 9______________
2. a) Write a
declaration for an array of integers
named sales that has 10 rows and 5 columns: _______int sales[10][5];__
b) Write a nested for loop to initialize all of the
values in your sales array declared in a) to a
value
of -1:
for (int row=0; row < 10; row++)
{
for (int col=0; col
< 5; col++)
{
sales[row][col] = -1;
}
}
3. Given these declarations: int array[5];
int n, k;
Code a loop which assigns these values to array: Value | 0 | 2 | 4 | 6 | 8 |
k = 0;
for (n=0; n < 5; n++)
{
array[n] = k;
k = k + 2;
}
4.
Given these declarations: int sample[5];
int k;
Show the values which are assigned to the array by the execution of the
following code:
for
(k = 1; k < 5; k++) |
| | |
| |
if
(k > 2) | |
2
| 3 | 9 | 16 |
sample[k] = k * k;
else
sample[k] = k + 1;
5.
a) Write
a function which will take parameters of an array of integers and an integer
which
is the
number of elements in the array. The
function should count and return the
number of
values in the array which are negative.
int
odds(int array[], int size)
{
int
oddsum = 0;
for (int i=0; i<size;
i++)
{
if (array[i] < 0)
oddsum++;
}
return oddsum;
}
b) Call your function from (a) to
store in the variable numNeg the number of
negative
values in
the 100-element array MyArray.
numNeg =
odds(MyArray, 100);
c) Call your function from (a) to
store in the variable nonNeg the number of values
in the
array YourArray which are not negative. The number of elements currently assigned
to YourArray is stored in the variable size.
int numNeg;
numNeg = odds(YourArray, size);
nonNeg = size – numNeg;