Ds malik c++ programming Chapter-2 Solution(The Basics of a C++ Program)

1 comment

Chapter-2 The Basics of a C++ Program

1. Mark the following statements as true or false. = Solution

a. An identifier can be any sequence of digits and letters.

b. In C++, there is no difference between a reserved word and a predefined identifier.

c. A C++ identifier can start with a digit.

d. The operands of the modulus operator must be integers.

e. If a = 4; and b = 3;, then after the statement a = b; the value of b is still 3.

f. In the statement cin >> y;, y can only be an int or a double variable.

g. In an output statement, the newline character may be a part of the string.

h. The following is a legal C++ program:
int main()
{
return 0;
}

i. In a mixed expression, all the operands are converted to floating-point numbers.

j. Suppose x = 5. After the statement y = x++; executes, y is 5 and
x is 6.

k. Suppose a = 5. After the statement ++a; executes, the value of a is still 5 because the value of the expression is not saved in another variable.

2.       Which of the following are valid C++ identifiers? Solution

a.            myFirstProgram

b.            MIX-UP

c.             C++Program2                   

d.            quiz7

e.            ProgrammingLecture2

f.             1footEquals12Inches     

g.            Mike'sFirstAttempt

h.            Update Grade

i.             4th        

j.             New_StudenT


3.       What is the difference between a keyword and a user-defined identifier? Solution 

4.       Which of the following is a reserved word in C++?  Solution

a.      Const    b.     include     c.     Char    d.     void    e.     int    f.     Return

5.       Are the identifiers firstName and FirstName the same? Solution

6.      Evaluate the following expressions.

a. 25 / 3                    b. 20 - 12 / 4 * 2          c. 32 % 7      d. 3 - 5 % 7

e. 18.0 / 4                 f. 28 - 5 / 2.0                g. 17 + 5 % 2 - 3

h. 15.0 + 3.0 * 2.0 / 5.0

7.      If x = 5, y = 6, z = 4, and w = 3.5, evaluate each of the following statements,if possible. If it is not possible, state the reason.

a. (x + z) % y             b. (x + y) % w           c. (y + w) % x        d. (x + y) *w

e. (x % y) % z           f. (y % z) % x             g. (x *z) % y         h. ((x *y) *w) *z 

8.      Given:

int num1, num2, newNum;

double x, y;

Which of the following assignments are valid? If an assignment is not valid, state the reason.

When not given, assume that each variable is declared.

a. num1 = 35;

b. newNum = num1 – num2;

c. num1 = 5; num2 = 2 + num1; num1 = num2 / 3;

d. num1 * num2 = newNum;

e. x = 12 * num1 - 15.3;

f. num1 * 2 = newNum + num2;

g. x / y = x * y;

h. num2 = num1 % 2.0;

i. newNum = static_cast<int> (x) % 5;

j. x = x + y - 5;

k. newNum = num1 + static_cast<int> (4.6 / 2);

9.      Do a walk-through to find the value assigned to e. Assume that all variables are properly declared.

a = 3;

b = 4;

c = (a % b) * 6;

d = c / b;

e = (a + b + c + d) / 4; 

10.      Which of the following variable declarations are correct? If a variable declaration is not correct, give the reason(s) and provide the correct variable declaration.

n = 12; //Line 1

char letter = ; //Line 2

int one = 5, two; //Line 3

double x, y, z; //Line 4 

11.      Which of the following are valid C++ assignment statements? Assume that i, x, and percent are double variables.

a. i = i + 5; 

b. x + 2 = x; 

c. x = 2.5 *x; 

d. percent = 10%;

12.      Write C++ statement(s) that accomplish the following.

a. Declare int variables x and y. Initialize x to 25 and y to 18.

b. Declare and initialize an int variable temp to 10 and a char variable ch to 'A'.

c. Update the value of an int variable x by adding 5 to it.

d. Declare and initialize a double variable payRate to 12.50.

e. Copy the value of an int variable firstNum into an int variable tempNum.

f. Swap the contents of the int variables x and y. (Declare additional variables, if necessary.)

g. Suppose x and y are double variables. Output the contents of x, y, and the expression 

     x + 12 / y - 18.

h. Declare a char variable grade and set the value of grade to 'A'.

i. Declare int variables to store four integers.

j. Copy the value of a double variable z to the nearest integer into an int variable x.

13.      Write each of the following as a C++ expression.

a. 32 times a plus b

b. The character that represents 8

c. The string that represents the name Julie Nelson.

d. (b2 - 4ac) / 2a

e. (a + b)/c(ef)-gh

f. (-b + (b2 - 4ac)) / 2a

14.      Suppose x, y, z, and w are int variables. What value is assigned to each of these variables after the last statement executes?

x = 5; z = 3;

y = x - z;

z = 2 * y + 3;

w = x - 2 * y + z;

z = w - x;

w++;

15.      Suppose x, y, and z are int variables and w and t are double variables. What value is assigned to each of these variables after the last statement executes?

x = 17;

y = 15;

x = x + y / 4;

z = x % 3 + 4;

w = 17 / 3 + 6.5;

t = x / 4.0 + 15 % 4 - 3.5;

16.      Suppose x, y, and z are int variables and x = 2, y = 5, and z = 6. What is the output of each of the following statements?

a. cout << "x = " << x << ", y = " << y << ", z = " << z << endl;

b. cout << "x + y = " << x + y << endl;

c. cout << "Sum of " << x << " and " << z << " is " << x + z << endl;

d. cout << "z / x = " << z / x << endl;

e. cout << "2 times " << x << " = " << 2 *x << endl;

17.      What is the output of the following statements? Suppose a and b are int variables, c is a double variable, and a = 13, b = 5, and c = 17.5.

a. cout << a + b – c << endl;

b. cout << 15 / 2 + c << endl;

c. cout << a / static_cast<double>(b) + 2 * c<< endl;

d. cout << 14 % 3 + 6.3 + b / a << endl;

e. cout << static_cast<int>(c) % 5 + a – b<< endl;

f. cout << 13.5 / 2 + 4.0 * 3.5 + 18 << endl;

18.      Write C++ statements that accomplish the following.

a. Output the newline character.

b. Output the tab character.

c. Output double quotation mark.

19.      Which of the following are correct C++ statements?

a. cout << "Hello There!" << endl;

b. cout << "Hello";<< " There!" << endl;

c. cout << "Hello"<< " There!" << endl;

d. cout << 'Hello There!' << endl;

20.      Give meaningful identifiers for the following variables.

a. A variable to store the first name of a student.

b. A variable to store the discounted price of an item.

c. A variable to store the number of juice bottles.

d. A variable to store the number of miles traveled.

e. A variable to store the highest test score.

21.      Write C++ statements to do the following.

a. Declare int variable num1 and num2.

b. Prompt the user to input two numbers.

c. Input the first number in num1 and the second number in num2.

d. Output num1, num2, and 2 times num1 minus num2. Your output must identify each number and the expression.

22.      The following program has syntax mistakes. Correct them. On each successive

line, assume that any preceding error has been corrected.

#include <iostream>
const int SECRET_NUM = 11,213;
const PAY_RATE = 18.35
main(){
       int one, two;
       double first, second;
       one = 18;
       two = 11;
       first = 25;
       second = first * three;
       second = 2 * SECRET_NUM;
       SECRET_NUM = SECRET_NUM + 3;
       cout << first << " " << second << SECRET_NUM << endl;
       paycheck = hoursWorked * PAY_RATE
              cout << "Wages = " << paycheck << endl;
       return 0;
}

23.      The following program has syntax mistakes. Correct them. On eachsuccessive line, assume that any preceding error has been corrected.

const char = STAR = '*'
const int PRIME = 71;
int main
{
       int count, sum;
       double x;
       count = 1;
       sum = count + PRIME;
       x := 25.67;
       newNum = count * ONE + 2;
       sum + count = sum;
       x = x + sum * COUNT;
       cout << " count = " << count << ", sum = " << sum
              << ", PRIME = " << Prime << endl;
}

24.      The following program has syntax errors. Correct them. On each successive line, assume that any preceding error has been corrected.

#include <iostream>
using namespace std;
int main()
{
       int temp;
       string first;
       cout << "Enter first name: ;
              cin >> first
              cout << endl;
       cout << "Enter last name: ;
              cin >> last;
       cout << endl;
       cout << "Enter today's temperature: ";
       cin >> temperature;
       cout << endl;
       cout << first << " " << last << today's temperature is: ";
              << temperature << endl;
       return 0;
}

25.      What action must be taken before a variable can be used in a program?

26.      Preprocessor directives begin with which of the following symbols:

a. *        b. # (Answer)        c. $            d. !       e. None of these.

27.      Write equivalent compound statements if possible.

a. x = 2 *x 

b. x = x + y - 2; 

c. sum = sum + num;

d. z = z *x + 2 *z; 

e. y = y / (x + 5);

28.      Write the following compound statements as equivalent simple statements.

a. x += 5 - z; 

b. y *= 2 *x + 5 - z; 

c. w += 2 *z + 4;

d. x -= z + y - t; 

e. sum += num;

29.      Suppose a, b, and c are int variables and a = 5 and b = 6. What value is assigned to each variable after each statement executes? If a variable is undefined at a particular statement, report UND (undefined).

                                        a              b             c

a = (b++) + 3;                __            __           __

c = 2 * a + (++b);          __            __           __

b = 2 * (++c) - (a++);   __            __           __

30.      Suppose a, b, and sum are int variables and c is a double variable. What value is assigned to each variable after each statement executes? Suppose a = 3, b = 5, and c = 14.1.

                               a                  b                c                  sum

sum = a + b + c;   ___             ___            ___                 ___

c /= a;                    ___             ___            ___                 ___

b += c - a;              ___             ___            ___                 ___ 

a *= 2 * b + c;       ___             ___            ___                 ___


31.      What is printed by the following program? Suppose the input is: 20 15

#include <iostream>
using namespace std;
const int NUM = 10;
const double X = 20.5;
int main()
{
       int a, b;
       double z;
       char grade;
       a = 25;
       cout << "a = " << a << endl;
       cout << "Enter two integers: ";
       cin >> a >> b;
       cout << endl;
       cout << "The numbers you entered are "
              << a << " and " << b << endl;
       z = X + 2 * a - b;
       cout << "z = " << z << endl;
       grade = 'A';
       cout << "Your grade is " << grade << endl;
       a = 2 * NUM + z;
       cout << "The value of a = " << a << endl;
       return 0;
}

32.      What is printed by the following program? Suppose the input is:

Miller
34
340

#include <iostream>
#include <string>
using namespace std;
const int PRIME_NUM = 11;
int main()
{
       const int SECRET = 17;
       string name;
       int id;
       int num;
       int mysteryNum;
       cout << "Enter last name: ";
       cin >> name;
       cout << endl;
       cout << "Enter a two digit number: ";
       cin >> num;
       cout << endl;
       id = 100 * num + SECRET;
       cout << "Enter a positive integer less than 1000: ";
       cin >> num;
       cout << endl;
       mysteryNum = num * PRIME_NUM - 3 * SECRET;
       cout << "Name: " << name << endl;
       cout << "Id: " << id << endl;
       cout << "Mystery number: " << mysteryNum << endl;
       return 0;
}

33.      Rewrite the following program so that it is properly formatted.

#include <iostream>
#include <string>
using namespace std;
const double X = 13.45; const int Y=34;
const char BLANK= ' ';
int main()
{string firstName,lastName;int num;
double salary;
cout<<"Enter first name: "; cin>> firstName; cout<<endl;
cout<<"Enter last name: "; cin
       >>lastName;cout<<endl;
cout<<"Enter a positive integer less than 70:";
cin>>num;cout<<endl; salary=num*X;
cout<<"Name: "<<firstName<<BLANK<<lastName<<endl;cout
       <<"Wages: $"<<salary<<endl; cout<<"X = "<<X<<endl;
cout<<"X+Y = " << X+Y << endl; return 0;
}

34.      What type of input does the following program require, and in what order does the input need to be provided?

#include <iostream>
using namespace std;
int main()
{
       int age;
       double weight;
       string firstName, lastName;
       cin >> firstName >> lastName;
       cin >> age >> weight;
       return 0;
}


PROGRAMMING EXERCISES

01.      Write a program that produces the following output:

**********************************

* Programming Assignment 1                 *

* Computer Programming I                     *

* Author: ???                                            *

* Due Date: Thursday, Jan. 24                 *

**********************************

In your program, substitute ??? with your own name. If necessary, adjust the positions and the number of the stars to produce a rectangle.

02.      Write a program that produces the following output:

CCCCCCCCC                              ++                                ++

CC                                                 ++                               ++

CC                                    ++++++++++++++    +++++++++++++++

CC                                   ++++++++++++++     +++++++++++++++

CC                                                ++                                 ++

CCCCCCCCC                             ++                                 ++

03.      Consider the following program segment

//include statement(s)

//using namespace statement

int main()

{

//variable declaration

//executable statements

//return statement

}

a. Write C++ statements that include the header files iostream.

b. Write a C++ statement that allows you to use cin, cout, and endl without the prefix std::.

c. Write C++ statements that declare the following variables: num1, num2, num3, and average of type int.

d. Write C++ statements that store 125 into num1, 28 into num2, and -25 into num3.

e. Write a C++ statement that stores the average of num1, num2, and num3, into average.

f. Write C++ statements that output the values of num1, num2, num3, and average.

g. Compile and run your program.

04.      Repeat Exercise 3 by declaring num1, num2, and num3, and average of type double. Store 75.35 into num1, -35.56 into num2, and 15.76 into num3.

05.      Consider the following C++ program in which the statements are in the incorrect order. Rearrange the statements so that it prompts the user to input the length and width of a rectangle and output the area and perimeter of the rectangle.

#include <iostream>
{
       int main()
              cout << "Enter the length: ";
       cin >> length;
       cout << endl;
       int length;
       area = length * width;
       return 0;
       int width;
       cin>> width;
       cout << "Enter the width: "
              cout << endl;
       cout << "Area = " << area << endl;
       cout << "Perimeter = " << perimeter << endl;
       int area;
       using namespace std;
       int perimeter;
}

06.      Consider the following program segment:

//include statement(s)
//using namespace statement
int main()
{
//variable declaration
//executable statements
//return statement
}
a. Write C++ statements that include the header files iostream and string.

b. Write a C++ statement that allows you to use cin, cout, and endl without the prefix std::.

c. Write C++ statements that declare the following variables: name of type string and studyHours of type double.

d. Write C++ statements that prompt and input a string into name and a double value into studyHours.

e. Write a C++ statement that outputs the values of name and studyHours with the appropriate text. For example, if the value of name is "Donald" and the value of studyHours is 4.5, the output is:
Hello, Donald! on Saturday, you need to study 4.5 hours for the exam.

f. Compile and run your program.

07.      Write a program that prompts the user to input a decimal number and outputs the number rounded to the nearest integer.

08.      Consider the following program segment:

//include statement(s)
//using namespace statement
int main()
{
//variable declaration
//executable statements
//return statement
}

a. Write C++ statements that include the header files iostream and string.

b. Write a C++ statement that allows you to use cin, cout, and endl without the prefix std::.

c. Write C++ statements that declare and initialize the following named constants: SECRET of type int initialized to 11 and RATE of type double initialized to 12.50.

d. Write C++ statements that declare the following variables: num1, num2, and newNum of type int; name of type string; and hoursWorked and wages of type double.

e. Write C++ statements that prompt the user to input two integers and store the first number in num1 and the second number in num2.

f. Write a C++ statement(s) that outputs the values of num1 and num2, indicating which is num1 and which is num2. For example, if num1 is 8 and num2 is 5, then the output is: The value of num1 = 8 and the value of num2 = 5.

g. Write a C++ statement that multiplies the value of num1 by 2, adds the value of num2 to it, and then stores the result in newNum. Then, write a C++ statement that outputs the value of newNum.

h. Write a C++ statement that updates the value of newNum by adding the value of the named constant SECRET. Then, write a C++ statement that outputs the value of newNum with an appropriate message.

i. Write C++ statements that prompt the user to enter a person’s last name and then store the last name into the variable name.

j. Write C++ statements that prompt the user to enter a decimal number between 0 and 70 and then store the number entered into hoursWorked.

k. Write a C++ statement that multiplies the value of the named constant RATE with the value of hoursWorked and then stores the result into the variable wages.

l. Write C++ statements that produce the following output:
Name: //output the value of the variable name
Pay Rate: $ //output the value of the variable rate
Hours Worked: //output the value of the variable
//hoursWorked
Salary: $ //output the value of the variable wages
For example, if the value of name is "Rainbow" and hoursWorked is
45.50, then the output is:
Name: Rainbow
Pay Rate: $12.50
Hours Worked: 45.50
Salary: $568.75

m. Write a C++ program that tests each of the C++ statements that you wrote in parts a through l. Place the statements at the appropriate place in the previous C++ program segment. Test run your program (twice) on the following input data:
a. num1 = 13, num2 = 28; name = "Jacobson"; hoursWorked =
48.30.
b. num1 = 32, num2 = 15; name = "Crawford"; hoursWorked =
58.45.

09.      Write a program that prompts the user to enter five test scores and then prints the average test score. (Assume that the test scores are decimal numbers.)

10.      Write a program that prompts the user to input five decimal numbers. The program should then add the five decimal numbers, convert the sum to the nearest integer, and print the result.

11.      Write a program that does the following:

a. Prompts the user to input five decimal numbers.

b. Prints the five decimal numbers.

c. Converts each decimal number to the nearest integer.

d. Adds the five integers.

e. Prints the sum and average of the five integers.

12.      Write a program that prompts the capacity, in gallons, of an automobile fuel tank and the miles per gallons the automobile can be driven. The program outputs the number of miles the automobile can be driven without refueling.

13.      Write a C++ program that prompts the user to input the elapsed time for an event in seconds. The program then outputs the elapsed time in hours, minutes, and seconds. (For example, if the elapsed time is 9630 seconds, then the output is 2:40:30.)

14.      Write a C++ program that prompts the user to input the elapsed time for an event in hours, minutes, and seconds. The program then outputs the elapsed time in seconds.

15.      To make a profit, a local store marks up the prices of its items by a certain percentage. Write a C++ program that reads the original price of the item sold, the percentage of the marked-up price, and the sales tax rate. The program then outputs the original price of the item, the percentage of the mark-up, the store’s selling price of the item, the sales tax rate, the sales tax, and the final price of the item. (The final price of the item is the selling price plus the sales tax.)

16.      Write a program that prompts the user to input a length expressed in centimeters. The program should then convert the length to inches (to the nearest inch) and output the length expressed in yards, feet, and inches, in that order. For example, suppose the input for centimeters is 312. To the nearest inch, 312 centimeters is equal to 123 inches. 123 inches would thus be output as:

       3 yard(s), 1 feet (foot), and 3 inch(es).

17.      Write a program to implement and test the algorithm that you designed for Exercise 15 of Chapter 1. (You may assume that the value of p = 3.141593. In your program, declare a named constant PI to store this value.)

18.      A milk carton can hold 3.78 liters of milk. Each morning, a dairy farm ships cartons of milk to a local grocery store. The cost of producing one liter of milk is $0.38, and the profit of each carton of milk is $0.27. Write a program that does the following:

a. Prompts the user to enter the total amount of milk produced in themorning.

b. Outputs the number of milk cartons needed to hold milk. (Round your answer to the nearest integer.)

c. Outputs the cost of producing milk.

d. Outputs the profit for producing milk.

19.      Redo Programming Exercise 18 so that the user can also input the cost of producing one liter of milk and the profit on each carton of milk.

20.      You found an exciting summer job for five weeks. It pays, say, $15.50 per hour. Suppose that the total tax you pay on your summer job income is 14%. After paying the taxes, you spend 10% of your net income to buy new clothes and other accessories for the next school year and 1% to buy school supplies. After buying clothes and school supplies, you use 25% of the remaining money to buy savings bonds. For each dollar you spend to buy savings bonds, your parents spend $0.50 to buy additional savings bonds for you. Write a program that prompts the user to enter the pay rate for an hour and the number of hours you worked each week. The program then outputs the following:

a. Your income before and after taxes from your summer job.

b. The money you spend on clothes and other accessories.

c. The money you spend on school supplies.

d. The money you spend to buy savings bonds.

e. The money your parents spend to buy additional savings bonds for you.

21.      A permutation of three objects, a, b, and c, is any arrangement of these objects in a row. For example, some of the permutations of these objects are abc, bca, and cab. The number of permutations of three objects is six. Suppose that these three objects are strings. Write a program that prompts the user to enter three strings. The program then outputs the six permutations of those strings.

22.      Write a program that prompts the user to input a number of quarters, dimes, and nickels. The program then outputs the total value of the coins in pennies.

23.      Newton’s law states that the force, F, between two bodies of masses M1 and M2 is given by:

in which k is the gravitational constant and d is the distance between the bodies. The value of k is approximately 6.67 10-8 dyn. cm2/g2. Write a program that prompts the user to input the masses of the bodies and the distance between the bodies. The program then outputs the force between the bodies.

24.      One metric ton is approximately 2205 pounds. Write a program that prompts the user to input the amount of rice, in pounds, in a bag. The program outputs the number of bags needed to store one metric ton of rice.

25.      Cindy uses the services of a brokerage firm to buy and sell stocks. The firm charges 1.5% service charges on the total amount for each transaction, buy or sell. When Cindy sells stocks, she would like to know if she gained or lost on a particular investment. Write a program that allows Cindy to input the number of shares sold, the purchase price of each share, and the selling price of each share. The program outputs the amount invested, the total service charges, amount gained or lost, and the amount received after selling the stock.

1 Questions:

Unknown said...

there are some questions dnt have answers???