Sie sind auf Seite 1von 31

CS201- Introduction to Programming Kashif Nadeem 03006986459 Kashifn47@gmail.com www.kashifn47.webs.

com

Question No: 1 ( Marks: 1 ) - Please choose one A precise sequence of steps to solve a problem is called Statement Program Utility Routine Question No: 2 ( Marks: 1 ) - Please choose one The Compiler of C language is written in Java Language UNIX FORTRON Language C Language Question No: 3 ( Marks: 1 ) - Please choose one Initialization of variable at the time of definition is, Must Necessary Good Programming None of the given options Question No: 4 ( Marks: 1 ) - Please choose one In if structure the block of statements is executed only, When the condition is false When it contain arithmetic operators When it contain logical operators When the condition is true Question No: 5 ( Marks: 1 ) - Please choose one Which of the following function(s) is/are included in stdlib.h header file? double atof(const char *nptr) int atoi(const char *nptr) char *strcpy ( char *s1, const char *s2) 1 and 2 only Question No: 6 ( Marks: 1 ) - Please choose one Dealing with structures and functions passing by reference is the most economical method True False Question No: 7 ( Marks: 1 ) - Please choose one Pointer is a variable which store, Data Memory Address Data Type Values Question No: 8 ( Marks: 1 ) - Please choose one Preprocessor program perform its function before ______ phase takes place. Editing Linking Compiling Loading

Question No: 9 ( Marks: 1 ) - Please choose one Which of the following can not be a variable name? area _area 10area area2 Question No: 10 ( Marks: 1 ) - Please choose one Which looping process is best, when the number of iterations is known? for while do-while all looping processes require that the iterations be known Question No: 11 ( Marks: 1 ) - Please choose one Which character is inserted at the end of string to indicate the end of string? new line tab null carriage return Question No: 12 ( Marks: 1 ) - Please choose one How many bytes are occupied by declaring following array of characters? char str[] = programming; 10 11 12 13 Question No: 13 ( Marks: 1 ) - Please choose one Which of the following header file defines the rand() function? iostream.h conio.h stdlib.h stdio.h Question No: 14 ( Marks: 1 ) - Please choose one Commenting the code _____________________ Makes a program easy to understand for others. Make programs heavy, i.e. more space is needed for executable. Makes it difficult to compile All of the given options. Question No: 15 ( Marks: 1 ) - Please choose one What's wrong with this for loop? for (int k = 2, k <=12, k++) the increment should always be ++k the variable must always be the letter i when using a for loop there should be a semicolon at the end of the statement the commas should be semicolons Question No: 16 ( Marks: 1 ) - Please choose one

For which array, the size of the array should be one more than the number of elements in an array? int double float char Question No: 17 ( Marks: 1 ) To Which category of the software Compiler and Interpreter belongs? Question No: 18 ( Marks: 1 ) What is the result of the expression x = 2 + 3 * 4 4 / 2 Question No: 19 ( Marks: 2 ) Write a declaration statement for an array of 10 elements of type float. Include an initialization statement of the first four elements to 1.0, 2.0, 3.0 and 4.0. Question No: 20 ( Marks: 3 ) Write down the output of the following code? int array[7], sum = 0; for(int i=0;i<7;i++) { array[i] = i; sum+= array[i]; } cout<< Sum = <<sum; What will be the output of the following segment of C++ code? int A[5] = {1 , 2, 3, 4}; int i; for (i=0; i<5; i++) { A[i] = 2*A[i]; cout << A[i] << " "; } Question No: 22 ( Marks: 10 ) Write a C++ program that will determine if a departmental store customer has exceeded the credit limit on a charge account. Program should input the following facts in five variables 1. 2. 3. 4. 5. Account number Balance at the beginning of month (Beginning balance) total of all items charged by customer this month (charges) total of all credits (credits) allowed credit limit

Calculate the new balance New balance = Beginning balance + charges credits Determine if new balance exceeds the allowed credit limit. For those customers whose credit limit is exceeded. The program should display the message Credit Limit exceeded. -------------------------------------------------------------------------------------------------------------------------------Question No: 1 ( Marks: 1 ) - Please choose one

What is the output of the following statement?

int i = 2.5; do { cout i * 2; } while (i > 3 && i < 10); 510 5 48 error Question No: 2 ( Marks: 1 ) - Please choose one What does !(7) evaluate to in decimal where ! is a NOT operator? 7 8 9 10 Question No: 3 ( Marks: 1 ) - Please choose one The condition in while loop may contain logical expression but not relational expression. True False Question No: 4 ( Marks: 1 ) - Please choose one Searching is easier when an array is already sorted

Question No: 5 ( Marks: 1 ) - Please choose one If an array has 100 elements, what is allowable range of subscripts?

0 - 99 1 - 99 0 - 100 1 - 100 Question No: 6 ( Marks: 1 ) - Please choose one What will be the value of a and b after executing the following statements? a = 3; b = a++; 3, 4 4, 4 3, 3 4, 3 Question No: 7 ( Marks: 1 ) - Please choose one

What will be the correct syntax to initialize all elements of two-dimensional array to value 0?

int arr[2][3] = {0,0} ; int arr[2][3] = {{0},{0}} ; int arr[2][3] = {0},{0} ;

int arr[2][3] = {0} ;

Question No: 8

( Marks: 1 )

- Please choose one

Which of the following function returns the size of a string variable? strlength() stringlen() strlen() strLength() Question No: 9 ( Marks: 1 ) - Please choose one What will be the range of numbers generated by function rand () % 9? 0 to 9 1 to 9 0 to 8 1 to 8

Question No: 11 ( Marks: 1 ) - Please choose one Computer can understand only machine language code.

Question No: 13 ( Marks: 1 ) - Please choose one What does 5 ^ 6 , evaluate to in decimal where ^ is Exclusive OR operator?

Question No: 14 ( Marks: 1 ) - Please choose one If the file is not properly closed in the program, the program ____________. Terminate normally Indicate Runtime error Indicate Compile time error Crashes Question No: 15 ( Marks: 1 ) - Please choose one Which of the following header file include string conversion functions?

string.h stdlib.h ctype.h sconvert.h Question No: 16 ( Marks: 1 ) - Please choose one In Program commenting the code liberally is

Question No: 17 ( Marks: 1 ) Which header file must be included while handling files?

Question No: 18 ( Marks: 1 ) What is meant by C++ statement: const int *ptr = &x;

Question No: 19 ( Marks: 2 ) What is a truth Table?

Question No: 20

( Marks: 3 )

(i) An array day is declared as: int day[] = {1, 2, 3, 4, 5, 6, 7}; How many elements does array 'day' has? (ii) If the declaration is changed as: int day[7] = {1, 2, 3, 4, 5, 6, 7}; How many elements does array 'day' has? Question No: 21 ( Marks: 5 )

What are similarities and differences between Structures and Unions? Question No: 22 ( Marks: 10 )

Write a void function( ); that takes integer numbers from the user and then displays the sum of odd and even numbers entered by the user. Your program should terminate if user enters a negative number ---------------------------------------------------------------------------------------------------------------------------------FINALTERM EXAMINATION Spring 2009 CS201- Introduction to Programming Question No: 1 ( Marks: 1 ) - Please choose one There are mainly -------------------- types of software Two Three Four

Five Question No: 2 ( Marks: 1 ) - Please choose one When x = 7; then the expression x%= 2; will calculate the value of x as, 1 3 7 2 Question No: 3 ( Marks: 1 ) - Please choose one A pointer variable can be, Decremented only Incremented only Multiplied only Both 1 and 2 Question No: 4 ( Marks: 1 ) - Please choose one setprecision is a parameter less manipulator. True False Question No: 5 ( Marks: 1 ) - Please choose one We can change a Unary operator to Binary operator through operator overloading. False True Question No: 6 ( Marks: 1 ) - Please choose one delete operator is used to return memory to free store which is allocated by the new operator True False Question No: 7 ( Marks: 1 ) - Please choose one When we do dynamic memory allocation in the constructor of a class, then it is necessary to provide a destructor. True False Question No: 8 ( Marks: 1 ) - Please choose one What is the functionality of the following statement? String str[5] = {String(Programming), String(CS201)}; Default constructor will call for all objects of array Parameterized constructor will call for all objects of array Parameterized constructor will call for first 2 objects and default constructor for remaining objects Default constructor will call for first 3 objects and Parameterized constructor for remaining objects Question No: 9 ( Marks: 1 ) - Please choose one What is the sequence of event(s) when allocating memory using new operator? Only block of memory is allocated for objects Only constructor is called for objects Memory is allocated first before calling constructor Constructor is called first before allocating memory Question No: 10 ( Marks: 1 ) - Please choose one Deleting an array of objects without specifying [] brackets may lead to memory leak True False Question No: 11 ( Marks: 1 ) - Please choose one Which of the following data type will be assumed if no data type is specified with constant? short float int double Question No: 12 ( Marks: 1 ) - Please choose one

There is an array of characters having name course that has to be initialized by string programming which of the following is the correct way to do this, i. course[] = {p, r, o, g, r, a, m, m, i, n, g}; ii. course[] = programming ; iii. course[12] = programming ; iv. course = programming ; Choose the correct options. (i) and (ii) only (i) and (iv) only (i) and (iii) only (ii) and (iii) only Question No: 13 ( Marks: 1 ) - Please choose one What will be the correct syntax of the following statement? ptr is a constant pointer to integer. const int *ptr ; const *int ptr ; int const *ptr ; int *const ptr ; Question No: 14 ( Marks: 1 ) - Please choose one Overloaded member operator Primitive data type Question No: 15 ( Marks: 1 ) - Please choose one Loader loads the executable code from hard disk to main memory. True False Question No: 16 ( Marks: 1 ) - Please choose one Which of the following is the correct C++ syntax to allocate space dynamically for an array of 10 int? new int(10) ; new int[10] ; int new(10) ; int new[10]; Question No: 17 ( Marks: 1 ) - Please choose one The prototype of friend functions must be written ____ the class and its definition must be written ____ inside, inside the class inside, outside the class outside, inside the class outside, outside the class Question No: 18 ( Marks: 1 ) - Please choose one Like member functions, ______ can also access the private data members of a class. Non-member functions Friend functions Any function outside class None of the given options

Question No: 19 ( Marks: 1 ) - Please choose one To perform manipulation with input/output, we have to include _____ header file. iostream.h stdlib.h iomanip.h fstream.h Question No: 20 ( Marks: 1 ) - Please choose one The endl and flush are _______ Functions Operators Manipulators Objects Question No: 21 ( Marks: 1 ) - Please choose one If we want to use stream insertion and extraction operators with _______ then we have to overload these operators. int, float, double objects of class int, float, object int, char, float Question No: 22 ( Marks: 1 ) - Please choose one The static data members of a class can be accessed by ________ only class only objects both class and objects none of given options Question No: 23 ( Marks: 1 ) - Please choose one Classes defined inside other classes are called ________ classes looped nested overloaded none of the given options. Question No: 24 ( Marks: 1 ) - Please choose one Which value is returned by the destructor of a class? A pointer to the class. An object of the class. A status code determining whether the class was destructed correctly Destructors do not return a value. Question No: 25 ( Marks: 1 ) - Please choose one
Consider the following code segment class M { friend int operator!(const M &); ... }; !s ... // code of line implies that operator!(s)

Let assume if s is an object of the class then function is implemented as ___________ Member function Non-member function Binary operator function None of the given options Question No: 26 ( Marks: 1 ) - Please choose one When the compiler overloads the assignment (=) operator by default then __________

compiler does member wise assignment. compiler does not allow default overload of assignment (=) operator member of the class are not assigned properly None of the given options Question No: 27 ( Marks: 1 ) - Please choose one If text is a pointer of class String then what is meant by the following statement? text = new String [5]; Creates an array of 5 string objects statically Creates an array of 5 string objects dynamically Creates an array of pointers to string Creates a string Object Question No: 28 ( Marks: 1 ) - Please choose one Static variable which is defined in a function is initialized __________. Only once during its life time Every time the function call Compile time of the program None of the above Question No: 29 ( Marks: 1 ) - Please choose one The appropriate data type to store the number of rows and colums of the matrix is____________. float int char none of the given options. Question No: 30 ( Marks: 1 ) - Please choose one Copy constructor becomes necessary while dealing with _______allocation in the class. Dynamic memory Static memory Both Dynamic and Static memory None of the given options Question No: 31 ( Marks: 1 ) What is drawback of writing the definitions of all the functions before main function?

Question No: 32

( Marks: 1 )

How do we provide the default values of function parameters?

Question No: 33 ( Marks: 2 ) What is difference between endl and \n?

Question No: 34 ( Marks: 2 ) When does an object get destroyed? Question No: 35 ( Marks: 3 ) What is the difference between structure and class? Question No: 36 ( Marks: 3 ) What will be the output of following functions if we call these functions three times? 1) void func1(){

int x = 0; x++; cout << x << endl; } 2) void func2(){ static int x = 0 ; x++; cout << x << endl ; } Question No: 37 ( Marks: 3 )

Why stream insertion and stream extraction operators cannot be overloaded as member functions? Question No: 38 ( Marks: 5 )

What is difference between Unary and binary operators and how they can be overloaded? Question No: 39 ( Marks: 5 )

What steps we must follow to design good program? Question No: 40 ( Marks: 10 )

Write the program that inputs an octal number from the user and then display the entered octal number into hexadecimal number using manipulators (parameter-less, parameterized) and member function of input/output streams. Question No: 41 ( Marks: 10 )

Develop a class Vector having two data members; x and y. The class should also provide the following Overloaded operator capabilities. a) Overload the addition operator(+) to add two Vectors b) Overload the assignment operator(=) to assign Resultant Vector c) Write function Display() to display x, y coordinates Note: Addition of vector Let suppose there are two vectors A and B with their x, y coordinates. --------------------------------------------------------------------------------------------------------------------------MID-TERM - SPRING 2007

Question No: 1 ( Marks: 1 ) - Please choose one Analysis is the -------------- step in designing a program Last Middle Post Design First

Question No: 2 ( Marks: 1 ) Please choose one The remainder (%) operator is, .An arithmetic operator A logical operator A relational operator A division operator Question No: 3 ( Marks: 1 ) - Please choose one When a call to function statement is encountered, The control is transfer to its Prototype The control is transfer to its definition The compiler stop execution of whole program The program hangs Question No: 4 ( Marks: 1 ) - Please choose one In C/C++ language when an array is passed to a function then by default its passing Mechanism is, Call by value It depends on type of array Call by Reference

It depends on the return type of function. Question No: 5 ( Marks: 1 ) - Please choose one Computer can do, More than what we tell it Less then what we tell it Like human being Exactly what we tell it Question No: 6 ( Marks: 1 ) - Please choose one int x = 2 * 3 + 4 * 5; What value will x contain in the sample code above? 22 26 46 50 Question No: 7 ( Marks: 1 ) - Please choose one In flow chart process is represented by Rectangle Arrow symbol Oval Circle Question No: 8 ( Marks: 1 ) - Please choose one Which one of the following will declare a pointer to an integer at address 0x22ff74 in memory? int *x; *x = 0x22ff74; int *x = &0x22ff74; int *x = *0x22ff74;

int *x( &0x22ff740 );

Question No: 9 ( Marks: 1 ) - Please choose one When we are using const keyword with a variable x then initializing it at the time of declaration is Must Optional Not necessary A syntax error Question No: 10 ( Marks: 1 ) - Please choose one int numarray[4][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; What value does numarray [0][3] in the sample code above contain? 3 5 7 4 Question No: 11 ( Marks: 5 ) Write Header files for the functions, i. ii. iii. iv. v. sqrt(); getline(); printf(); exit(); rand();

Question No: 12 ( Marks: 5 ) Write down the output of the following code?

int array[7], sum = 0; for(int i=0;i<7;i++) { array[i] = i; sum+= array[i]; } cout<< Sum = <<sum; Question No: 13 ( Marks: 15 ) Write a program which consists of three variables Area, Per, Base, this program should find and display the area of triangle using the formula, Area = (Base * Per)/2 ; Take the value of variables Per and Base from the user. Question No: 14 ( Marks: 15 ) Write a function BalerAvg which calculate and display the average of a player (Baler), call this function in main program (function). Take input of runs given and ball delivered from the user in main funciton. The average may be calculated by the formula, Average = (Total Runs given * 60) / (Total number of balls delivered);

MID-TERM - SPRING 2006

Question No. 1

Marks : 10

Write the function definitions for the following: a) A function test() that would take three integer values x, y and z (as parameters), find the largest and return the result to the calling function.

b) A function sum() that would take the one integer array myArray[ ] of size 10 (as parameter), calculate the sum of the elements of myArray[ ] and display the result. Note: The function sum() returns no value. Question No. 2 Marks : 6

Write a program that will create and display the following series: 65, 44, 27, 14, 5, 0, -1, 2, 9, 20. Hint: The series is created by the formula 2x2 3x for x=-5 to 4 The variable x is of type integer.

Question No. 3

Marks : 2

The value of 2*15/3*7+3*2 is

146 76 8 70 Question No. 4 Marks : 2 Carefully analyze the following lines of code and chose the correct option.

ch1=a;

ch2=a;

ch1 and ch2 are strings ch1 is string and ch2 is character ch2 is string and ch1 is character ch1 and ch2 are characters Question No. 5 Marks : 2

The size of a double variable is

2 bytes 4 bytes 8 bytes 10 bytes Question No. 6 Marks : 2 An array is also called an array variable array declaration struct constant pointer

Question No. 7 Marks : 10 What will be the output of the following programs?

a) Program1 #include <iostream> int main() { unsigned short x = 1;

for (int i = 0; i < 10; i++) { cout << x << endl; x = x << 1; } return 0; } b) Program2 #include <iostream.h> int main() { unsigned short x = 1024; while(x>=1) { cout <<x << endl; x =x >> 1; } return 0; } Question No. 8 Marks : 6

Calculate the following expressions for x=3 and y=2 1) ++x++*++y 2) 3*++x+--y 3) ++x*4*++y

Introduction to Computers and C++ Programming

Solutions
SOLUTIONS
1.10 Categorize each of the following items as either hardware or software: a) CPU

1.10 Categorize each of the following items as either hardware or software: a) CPU ANS: hardware. b) C++ compiler ANS: software. c) ALU ANS: hardware. d) C++ preprocessor ANS: software. e) input unit ANS: hardware. f) an editor program ANS: software. 1.11 Why might you want to write a program in a machine-independent language instead of a machinedependent language? Why might a machine-dependent language be more appropriate for writing certain types of programs? ANS: Machine independent languages are useful for writing programs to be executed on multiple computer platforms. Machine dependent languages are appropriate for writing programs to be executed on a single platform. Machine dependent languages tend to exploit the efficiencies of a particular machine. 1.12 Fill in the blanks in each of the following statements: a) Which logical unit of the computer receives information from outside the computer for use by the computer? . ANS: input unit. b) The process of instructing the computer to solve specific problems is called . ANS: computer programming. c) What type of computer language uses English-like abbreviations for machine language instructions? . ANS: high-level language. d) Which logical unit of the computer sends information that has already been processed by the computer to various devices so that the information may be used outside the computer? . ANS: output unit. e) Which logical unit of the computer retains information? . ANS: memory unit and secondary storage unit. f) Which logical unit of the computer performs calculations? . ANS: arithmetic and logical unit. g) Which logical unit of the computer makes logical decisions? . ANS: arithmetic and logical unit. h) The level of computer language most convenient to the programmer for writing programs quickly and easily is

.ANS: high-level language. i) The only language that a computer can directly understand is called that computer's . ANS: machine language. j) Which logical unit of the computer coordinates the activities of all the other logical units? . ANS: central processing unit. 1.13 Discuss the meaning of each of the following objects: a) cin ANS: This object refers to the standard input device that is normally connected to the keyboard. b) cout ANS: This object refers to the standard output device that is normally connected to the computer screen. c) cerr ANS: This object refers to the standard error device that is normally connected to the computer screen. 1.14 Why is so much attention today focused on object-oriented programming in general and C++ in particular? ANS: Object-oriented programming enables the programmer to build reusable software components that model items in the real world. Building software quickly, correctly, and economically has been an elusive goal in the software industry. The modular, object-oriented design and implementation approach has been found to increase productivity 10 to 100 times over conventional programming languages while reducing development time, errors, and cost. C++ is extremely popular because it is a superset of the widely used C programming language. Programmers already familiar with C have an easier time learing C++. 1.15 Fill in the blanks in each of the following: a) are used to document a program and improve its readability. ANS: comments b) The object used to print information on the screen is . ANS: cout c) A C++ statement that makes a decision is . ANS: if d) Calculations are normally performed by statements. ANS: assignment e) The object inputs values from the keyboard. ANS: cin 1.16 Write a single C++ statement or line that accomplishes each of the following: a) Print the message "Enter two numbers". ANS: cout << "Enter two numbers"; b) Assign the product of variables b and c to variable a.

ANS: a = b * c; c) State that a program performs a sample payroll calculation (i.e., use text that helps to document a program). ANS: // Sample Payroll Calculation Program d) Input three integer values from the keyboard and into integer variables a, b and c. ANS: cin >> a >> b >> c; 1.17 State which of the following are true and which are false. If false, explain your answers. a) C++ operators are evaluated from left to right. ANS: False. Some operators are evaluated from left to right, while other operators are evaluated right to left . b) The following are all valid variable names: _under_bar_, m928134, t5, j7, her_sales, his_account_total, a, b, c, z, z2. ANS: True. All variables begin with an underscore or letter. c) The statement cout << "a = 5;"; is a typical example of an assignment statement. ANS: False. The statement is an output statement. a = 5; is output to the screen. d) A valid C++ arithmetic expression with no parentheses is evaluated from left to right. ANS: False. Arithmetic operators can appear in any order in an expression. Since multiplication, division, and modulus have higher precendence than addition and subtraction the statement cannot be true. e) The following are all invalid variable names: 3g, 87, 67h2, h22, 2h. ANS: False. h22 is a valid variable name. 1.18 Fill in the blanks in each of the following: a) What arithmetic operations are on the same level of precedence as multiplication? . ANS: division and modulus. b) When parentheses are nested, which set of parentheses is evaluated first in an arithmetic expression? . ANS: innermost. c) A location in the computer's memory that may contain different values at various times throughout the execution of a program is called a . ANS: variable. 1.19 What, if anything, prints when each of the following C++ statements is performed? If nothing prints, then answer nothing. Assume x = 2 and y = 3. a) cout << x; ANS: 2 b) cout << x + x; ANS: 4 c) cout << "x="; ANS: x= d) cout << "x = " << x; ANS: x = 2

e) cout << x + y << " = " << y + x; ANS: 5 = 5 f) z = x + y; ANS: nothing. g) cin >> x >> y; ANS: 23. h) // cout << "x + y = " << x + y; ANS: nothing. i) cout << "\n"; ANS: A newline is output which positions the cursor at the beginning of the next line on the screen. 1.20 Which of the following C++ statements contain variables whose values are replaced? a) cin >> b >> c >> d >> e >> f; b) p = i + j + k + 7; c) cout << "variables whose values are destroyed"; d) cout << "a = 5"; ANS: Parts (a) and (b). 1.21 Given the algebraic equation y = ax3 + 7, which of the following, if any, are correct C++ statements for this equation? a) y = a * x * x * x + 7; b) y = a * x * x * ( x + 7 ); c) y = ( a * x ) * x * ( x + 7 ); d) y = (a * x) * x * x + 7; e) y = a * ( x * x * x ) + 7; f) y = a * x * ( x * x + 7 ); ANS: Parts (a), (d) and (e). 1.22 State the order of evaluation of the operators in each of the following C++ statements and show the value of x after each statement is performed. a) x = 7 + 3 * 6 / 2 - 1; ANS: *, /, +, -, =, 15 b) x = 2 % 2 + 2 * 2 - 2 / 2; ANS: %, *, /, +, -, =, 3 c) x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) ); ANS: *, /, +, *, *, 324 ------------------------------------------------------------------------------------------------------------------------------

Control Structures Solutions


2.14 Identify and correct the error(s) in each of the following: a) if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else

cout << "Age is less than 65 << endl"; ANS: The semicolon at the end of the if should be removed. The closing double quote after the second endl should be placed after 65. b) if ( age >= 65 ) cout << "Age is greater than or equal to 65" << endl; else; cout << "Age is less than 65 << endl"; ANS: The semicolon after the else should be removed. The closing double quote after the second endl should be placed after 65. c) int x = 1, total; while ( x <= 10 ) { total += x; ++x; } ANS: Variable total should be initialized to 0. d) While ( x <= 100 ) total += x; ++x; ANS: The W in while should be lowercase. The whiles body should be enclosed in braces {}. e) while ( y > 0 ) { cout << y << endl; ++y; } ANS: The variable y should be decremented (i.e., --y;) not incremented ( ++y;).

Functions Solutions
3.16 Write statements that assign random integers to the variable n in the following ranges: a) 1 n 2 ANS: n = 1 + rand() % 2; b) 1 n 100 ANS: n = 1 + rand() % 100; c) 0 n 9 ANS: n = rand() % 10; d) 1000 n 1112 ANS: n = 1000 + rand() % 13; e) 1 n 1 ANS: n = rand() % 3 - 1; f) 3 n 11 ANS: n = rand() % 15 - 3;

3.17 For each of the following sets of integers, write a single statement that will print a number at random from the set. a) 2, 4, 6, 8, 10. ANS: cout << 2 * ( 1 + rand() % 5 ) ) << \n; b) 3, 5, 7, 9, 11. ANS: cout << 1 + 2 * ( 1 + rand() % 5 ) ) << \n; c) 6, 10, 14, 18, 22. ANS: cout << 6 + 4 * ( rand() % 5 ) << \n; ----------------------------------------------------------------------------------------------------------------------------------

Arrays Solutions
Solutions 4.6 Fill in the blanks in each of the following: a) C++ stores lists of values in . ANS: arrays. b) The elements of an array are related by the fact that they . ANS: have the same name and type. c) When referring to an array element, the position number contained within square brackets is called a . ANS: subscript. d) The names of the four elements of array p are , , and . ANS: p[ 0 ], p[ 1 ], p[ 2 ], p[ 3 ] e) Naming an array, stating its type and specifying the number of elements in the array is called the array. ANS: declaring. f) The process of placing the elements of an array into either ascending or descending order is called . ANS: sorting. g) In a double-subscripted array, the first subscript (by convention) identifies the of an element, and the second subscript (by convention) identifies the of an element. ANS: row, column. h) An m-by-n array contains rows, columns and elements. ANS: m, n, m x n.

i) The name of the element in row 3 and column 5 of array d is . ANS: d[ 2 ][ 4 ]. 4.7 State which of the following are true and which are false; for those that are false, explain why they are false. a) To refer to a particular location or element within an array, we specify the name of the array and the value of the particular element. ANS: False. The name of the array and the subscript of the array are specified.

b) An array declaration reserves space for the array. ANS: True. c) To indicate that 100 locations should be reserved for integer array p, the programmer writes the declaration p[ 100 ]; ANS: False. A data type must be specified. An example of a correct definition would be: unsigned p[ 100 ];. . d) A C++ program that initializes the elements of a 15-element array to zero must contain at least one for statement. ANS: False. The array can be initialized in a declaration with a member initializer list. e) A C++ program that totals the elements of a double-subscripted array must contain nested for statements. ANS: False. The sum of the elements can be obtained without for loops, with one for loop, three for loops, etc. 4.8 Write C++ statements to accomplish each of the following: a) Display the value of the seventh element of character array f. ANS: cout << f[ 6 ] << \n; b) Input a value into element 4 of single-subscripted floating-point array b. ANS: cin >> b[ 4 ]; c) Initialize each of the 5 elements of single-subscripted integer array g to 8. ANS: int g[ 5 ] = { 8, 8, 8, 8, 8 }; or for ( int j = 0; j < 5; ++j ) g[ j ] = 8; d) Total and print the elements of floating-point array c of 100 elements. ANS: for ( int k = 0; k < 5; ++k ) { total += c[ k ]; // assume total declared and initalized cout << c[ k ] << \n } e) Copy array a into the first portion of array b. Assume double a[ 11 ], b[ 34 ]; ANS: for ( int i = 0; i < 11; ++i ) b[ i ] = a[ i ]; f) Determine and print the smallest and largest values contained in 99-element floating-point array w. ANS: // assume all variables declared and initialized for ( int j = 0; j < 99; ++j ) if ( w[ j ] < smallest ) smallest = w[ j ]; else if ( w[ j ] > largest ) largest = w[ j ];

4.9 Consider a 2-by-3 integer array t. a) Write a declaration for t. ANS: int t[ 2 ][ 3 ]; b) How many rows does t have? ANS: 2 c) How many columns does t have? ANS: 3 d) How many elements does t have? ANS: 6 e) Write the names of all the elements in the second row of t. ANS: t[ 1 ][ 0 ], t[ 1 ][ 1 ], t[ 1 ][ 2 ] f) Write the names of all the elements in the third column of t. ANS: t[ 0 ][ 2 ], t[ 1 ][ 2 ] g) Write a single statement that sets the element of t in row 1 and column 2 to zero. ANS: t[ 0 ][ 1 ] = 0; h) Write a series of statements that initialize each element of t to zero. Do not use a repetition structure. ANS: t[ 0 ][ 0 ] = 0; t[ 0 ][ 1 ] = 0; t[ 0 ][ 2 ] = 0; t[ 1 ][ 0 ] = 0; t[ 1 ][ 1 ] = 0; t[ 1 ][ 2 ] = 0; i) Write a nested for structure that initializes each element of t to zero. ANS: for ( int i = 0; i < 2; ++i ) for ( int j = 0; j < 3; ++j ) t[ i ][ j ] = 0; j) Write a statement that inputs the values for the elements of t from the terminal. ANS: for ( int r = 0; r < 2; ++r ) for ( int c = 0; c < 3; ++c ) t[ r ][ c ] = 0;

k) Write a series of statements that determine and print the smallest value in array t. ANS: int smallest = t[ 0 ][ 0 ]; for ( int r = 1; r < 2; ++r ) for ( int c = 1; c < 3; ++c ) if ( t[ r ][ c ] < smallest ) smallest = t[ r ][ c ]; cout << smallest;

l) Write a statement that displays the elements of the first row of t ANS: cout << t[ 0 ][ 0 ] << << t[ 0 ][ 1 ] << << t[ 0 ][ 2 ] << \n; m) Write a statement that totals the elements of the fourth column of t. ANS: t does not contain a fourth column. n) Write a series of statements that prints the array t in neat, tabular format. List the column subscripts as headings across the top and list the row subscripts at the left of each row. ANS: cout << " 0 1 2\n"; for ( int r = 0; r < 2; ++r ) { cout << r << ; for ( int c = 0; c < 3; ++c ) cout << t[ r ][ c ] << " "; cout << \n; } -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Pointers and Strings Solutions


Solutions 5.8 State whether the following are true or false. If false, explain why. a) Two pointers that point to different arrays cannot be compared meaningfully. ANS: True. b) Because the name of an array is a pointer to the first element of the array, array names may be manipulated in precisely the same manner as pointers. ANS: False. An array name cannot be used to refer to another location in memory. 5.9 Answer each of the following. Assume that unsigned integers are stored in 2 bytes and that the starting address of the array is at location 1002500 in memory. a) Declare an array of type unsigned int called values with 5 elements, and initialize the elements to the even integers from 2 to 10. Assume that the symbolic constant SIZE has been defined as 5. ANS: unsigned values[ SIZE ] = { 2, 4, 6, 8, 10 }; b) Declare a pointer vPtr that points to an object of type unsigned int. ANS: unsigned *vPtr;

c) Print the elements of array values using array subscript notation. Use a for structure and assume integer control variable i has been declared. ANS: for ( i = 0; i < SIZE; ++i ) cout << setw( 4 ) << values[ i ]; d) Give two separate statements that assign the starting address of array values to pointer variable vPtr. ANS: vPtr = values; and vPtr = &values[ 0 ];

e) Print the elements of array values using pointer/offset notation. ANS: for ( i = 0; i < SIZE; ++i ) cout << setw( 4 ) << *( vPtr + i ); f) Print the elements of array values using pointer/offset notation with the array name as the pointer. ANS: for ( i = 0; i < SIZE; ++i ) cout << setw( 4 ) << *( values + i ); g) Print the elements of array values by subscripting the pointer to the array. ANS: for ( i = 0; i < SIZE; ++i ) cout << setw( 4 ) << vPtr[ i ]; . h) Refer to the fifth element of values using array subscript notation pointer/offset notation with the array name as the pointer, pointer subscript notation, and pointer/offset notation. ANS: values[ 4 ], *( values + 4 ), vPtr[ 4 ], *( vPtr + 4 ) i) What address is referenced by vPtr + 3? What value is stored at that location? ANS: The address of the location pertaining to values[ 3 ] (i.e., 1002506). 8. j) Assuming vPtr points to values[ 4 ], what address is referenced by vPtr -= 4? What value is stored at that location? ANS: The address of where values begins in memory (i.e., 1002500). 2. 5.10 For each of the following, write a single statement that performs the indicated task. Assume that long integer variables value1 and value2 have been declared and that value1 has been initialized to 200000. a) Declare the variable lPtr to be a pointer to an object of type long. ANS: long *lPtr; b) Assign the address of variable value1 to pointer variable lPtr. ANS: lPtr = &value1; c) Print the value of the object pointed to by lPtr. ANS: cout << *lPtr << \n; d) Assign the value of the object pointed to by lPtr to variable value2. ANS: value2 = *lPtr;

e) Print the value of value2. ANS: cout << value2 << \n; f) Print the address of value1. ANS: cout << &value1 << \n; g) Print the address stored in lPtr. Is the value printed the same as the address of value1? ANS: cout << lPtr << \n; yes. 5.11 Do each of the following.

a) Write the function header for function zero that takes a long integer array parameter bigIntegers and does not return a value. ANS: void zero( long bigIntegers[] ) or void zero( long *bigIntegers ) b) Write the function prototype for the function in part (a). ANS: void zero( long [] ); or void zero( long * ); c) Write the function header for function add1AndSum that takes an integer array parameter oneTooSmall and returns an integer. ANS: int add1Andsum( int oneTooSmall[] ) or int add1Andsum( int *oneTooSmall ) d) Write the function prototype for the function described in part (c). ANS: int add1Andsum( int [] ); or int add1Andsum( int * ); -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Bits, Characters, Strings and Structures Solutions


Solutions 16.6 Provide the definition for each of the following structures and unions: a) Structure Inventory containing character array partName[ 30 ], integer partNumber, floating-point price, integer stock and integer reorder. ANS: struct Inventory { char partName[ 30 ]; int partNumber; double price; int stock; int reorder; }; b) A structure called Address that contains character arrays streetAddress[ 25 ], city[ 20 ], state[ 3 ] and zipCode[ 6 ]. ANS: struct Address { char streetAddress[ 25 ]; char city[ 20 ]; char state[ 3 ]; char zipCode[ 6 ]; }; c) Structure Student that contains arrays firstName[ 15 ] and lastName[ 15 ], and variable homeAddress of type struct Address from part (b). ANS: struct Student { char firstName[ 15 ]; char lastName[ 15 ]; struct Address homeAddress; };

d) Structure Test containing 16 bit fields with widths of 1 bit. The names of the bit fields are the letters a to p. ANS: struct Test { unsigned a:1, b:1, c:1, d:1, e:1, f:1, g:1, h:1, i:1, j:1, k:1, l:1, m:1, n:1, o:1, p:1; }; 16.7 Consider the following structure definitions and variable declarations, struct Customer { char lastName[ 15 ]; char firstName[ 15 ]; int customerNumber; struct { char phoneNumber[ 11 ]; char address[ 50 ]; char city[ 15 ]; char state[ 3 ]; char zipCode[ 6 ]; } personal; } customerRecord, *customerPtr; customerPtr = &customerRecord; Write a separate expression that accesses the structure members in each of the following parts: a) Member lastName of structure customerRecord. ANS: customerRecord.lastName b) Member lastName of the structure pointed to by customerPtr. ANS: customerPtr->lastName c) Member firstName of structure customerRecord. ANS: customerRecord.firstName d) Member firstName of the structure pointed to by customerPtr. ANS: customerPtr->firstName e) Member customerNumber of structure customerRecord. ANS: customerRecord.customerNumber f) Member customerNumber of the structure pointed to by customerPtr. ANS: customerPtr->customerNumber g) Member phoneNumber of member personal of structure customerRecord. ANS: customerRecord.personal.phoneNumber h) Member phoneNumber of member personal of the structure pointed to by customerPtr. ANS: customerPtr->personal.phoneNumber i) Member address of member personal of structure customerRecord. ANS: customerRecord.personal.address j) Member address of member personal of the structure pointed to by customerPtr. ANS: customerPtr->personal.address

k) Member city of member personal of structure customerRecord. ANS: customerRecord.personal.city l) Member city of member personal of the structure pointed to by customerPtr. ANS: customerPtr->personal.city m) Member state of member personal of structure customerRecord. ANS: customerRecord.personal.state n) Member state of member personal of the structure pointed to by customerPtr. ANS: customerPtr->personal.state o) Member zipCode of member personal of structure customerRecord. ANS: customerRecord.personal.zipCode p) Member zipCode of member personal of the structure pointed to by customerPtr. ANS: customerPtr->personal.zipCode -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------