What is the output of the following (working) code when embedded in a complete and correct program? It is acceptable to declare and initialize a variable inside a for
statement as shown.
char symbol[3] = {'a', 'b', 'c'}; for (int index = 0; index < 3; index++) cout << symbol[index];
a b c
What is wrong with the following piece of code?
int sample_array[10]; for (int index = 1; index <= 10; index++) sample_array[index] = 3 * index;
The indexed variables of sample_array
are sample_array[0]
through sample_array[9]
, but this piece of code tries to fill sample_array[1]
through sample_array[10]
. The index 10
in sample_array[10]
is out of range.
Consider the following function definition:
void tripler(int& n) { n = 3 * n; }
Given the following variable declarations within a code block, which of the following are acceptable function calls?
int a[3] = {4, 5, 6}, number = 2;
tripler(number);
This is acceptable.
tripler(a[2]);
This is acceptable.
tripler(a[3]);
This is illegal because 3 is an out of range index.
tripler(a[number]);
This is acceptable. It is the same as tripler(a[2]);
above.
tripler(a);
This is illegal because tripler expects a single integer variable, and the argument here is an entire array.
Write a function definition for a void function called show_the_world
which accepts an array of integers as one of its arguments and prints out the entire array, no more, no less.
void show_the_world(int a[], int size_of_a) { cout << "The array contains the following values:\n"; for (int i = 0; i < size_of_a; i++) cout << a[i] << " "; cout << endl; }
What is a string?
A string variable is an array of characters that contains the null character '\0' at the end of the string value. This is a distinction in how the array is used rather than a distinction about what the array is. A string variable is an array fo characters, but it is used in a different way.
Which of the following declarations are equivalent? Match them up and explain why they behave the same.
char string_var[10] = "Hello";
This is equivalent to the following declaration, but initializes the string "the easy way."
char string_var[10] = {'H', 'e', 'l', 'l', 'o', '\0'};
This is equivalent to the first string, but is done "the hard way". Note both still have room for 10 characters (including the null).
char string_var[10] = {'H', 'e', 'l', 'l', 'o'};
This is an array of characters, not a string. It is unique.
char string_var[6] = "Hello";
This will create a string with room for exactly the 5 characters in "Hello" and the null terminator: 6 chars total.
char string_var[] = "Hello";
This will also create a string with room for exactly the 5 characters in "Hello" and the null terminator: 6 chars total.
name
(up to 80 characters long), wage rate
, accrued vacation
(a whole number of days), and status
which will consist of a single character code. Call the type EmployeeRecord
.
struct EmployeeRecord { char name[80]; double rate; // or float int vacation; // or short char status; };