Vous êtes sur la page 1sur 54

Chapter 2

OBJECTIVE
1. Mark the following statements as true or false.
a. An identifier can be any sequence of digits and letters.
False

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


predefined identifier.
False

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


False

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


True

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


still 3.
True

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


variable.
False

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


the string.
True
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.
True

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


is 6.
True

j. 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.
False
2. Which of the following are valid C++ identifiers?
a. my First Program
It is VALID

b. MIX-UP
It is INVALID

c. C++Program2
It is INVALID

d. quiz7
It is VALID

e. ProgrammingLecture2
It is VALID
f. 1footEquals12Inches
It is INVALID

g. Mike's First Attempt


It is INVALID

h. Update Grade
It is INVALID

i. 4th
It is INVALID

j. New Student
It is VALID
3. Which of the following is a reserved word in C++?
a. Const
It is reserved word

b. include
It is not a reserved word

c. Char
It is reserved word
d. void
It is reserved word

e. int
It is reserved word
f. Return
It is reserved word
4. What is the difference between a keyword and a user-defined
identifier?

5. Are the identifiers firstName and FirstName the same?


No the identifiers firstName and FirstName are not same.
6. Evaluate the following expressions.
a. 25 / 3
8.333333333333333.

b. 20 - 12 / 4 * 2
4

c. 32 % 7
14

d. 3 - 5 % 7
-4

e. 18.0 / 4
4.5

f. 28 - 5 / 2.0
11.5

g. 17 + 5 % 2 - 3
16
h. 15.0 + 3.0 * 2.0 / 5.0
7.2
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
(5 + 4) % 6 = 9 % 6 =3

b. (x + y) % w
(5 + 6) % 3.5 = 11.0 % 3.5, =0.5

c. (y + w) % x
(6 + 3.5) % 5 = 9.5 % 5.0 =4.5

d. (x + y) *w
(5 + 6) * 3.5 = 11.0 * 3.5 =38.5

e. (x % y) % z
(5 % 6) % 4 = 5 % 4 =1

f. (y % z) % x
(6 % 4) % 5 = 2 % 5 =2

g. (x *z) % y
(5 * 4) % 6 = 20 % 6 =2

h. ((x *y) *w) *z


((5 * 6) * 3.5) * 4 = 30.0 * 3.5 * 4.0 =420.0
8. Given: int num1, num2, new Num; 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;
valid

b. new Num = num1 num2;


valid

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


valid

d. num1 * num2 = new Num;


Invalid

e. x = 12 * num1 - 15.3;
valid

f. num1 * 2 = new Num + num2;


Inalid

g. x / y = x * y;
Invalid

h. num2 = num1 % 2.0;


valid
i. new Num = static_cast<int> (x) % 5;
Invalid

j. x = x + y - 5;
valid

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


valid
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;
c=18

d = c / b;
d=4

e = (a + b + c + d) / 4;
e=7
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
Incorrect

char letter = ; //Line 2


Incorrect

int one = 5, two; //Line 3


correct

double x, y, z; //Line 4
Correct
11. Which of the following are valid C++ assignment statements?
Assume that i, x, and percent are double variables.
a. i = i + 5;
Correct

b. x + 2 = x;
Incorrect

c. x = 2.5 *x;
Correct

d. percent = 10%;
Incorrect
12. Write C++ statement(s) that accomplish the following.
a. Declare int variables x and y. Initialize x to 25 and y to 18.
int x;
int y;
x = 25;
y = 18;

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


int temp;
temp = 10;
char ch;
ch = A;

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


Int x;
x =x+ 5;

d. Declare and initialize a double variable pay Rate to 12.50.


double payRate;
payRate = 12.5;

e. Copy the value of an int variable first Num into an int variable temp
Num.
int firstnum, tempnum,z;
z=firstnum;
firstnum=tempnum;
tempnum=z;

f. Swap the contents of the int variables x and y. (Declare additional


variables, if necessary.)
cout<<x=<<x<<y=<<y<<endl;
cout<<x+12/y-8=<<x+12/y-8<<endl;

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


and the expression x + 12 / y - 18.
doublez=3;
int x;
x=z
h. Declare a char variable grade and set the value of grade to 'A'.
char grade;
grade=A
i. Declare int variables to store four integers.
Int a, b, c, d;
j. Copy the value of a double variable z to the nearest integer into an int
variable x
int z;
int x;
13. Write each of the following as a C++ expression.
a. 32 times a plus b
32 * a + b

b. The character that represents 8


8'

c. The string that represents the name Julie Nelson.


Julie Nelson

d. (b2 - 4ac) / 2a
(b * 2 4 * a * c) / (2 * a)

e. (a + b) / c (ef)-gh
(a + b) / c * (e * f) g * h

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


(b + (b * 2 4 * a * c)) / (2 * a)

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++;
x =5;
z =3;
y = x - z; 2= 5 3;
z = 2 * y + 3; 7= 2*2 + 3;
w = x - 2 * y + z; 8= 5 - 2*2+7
z = w - x; 3= 8 5
w++; =9
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;
x=20.75

z = x % 3 + 4;
z=4.51

w = 17 / 3 + 6.5;
w=12.16666

t = x / 4.0 + 15 % 4 - 3.5;
t=1.35
16. 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.
17. 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;
}
Output
a=25
Enter two integers: 20 15
The number you entered are 34 and 56
Z=45.5
Your grade is A
The value of a = 65.5
18. 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 mystery Num;
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<<mysetry number: " << mysteryNum << endl;
return 0;
}
Output
Enter last name: Miller
Enter a two digit number: 34
Enter a positive integer less than 1000: 340
Name: Miller
Id: 3417
Mystery number: 323
Chapter 2
SUBJECTIVE

1. 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.
ANS:
#include <iostream>
using namespace std;
void main()
{
float hours, mins, seconds;
float time;
cout << "Enter Elapsed time for the event\nPlease enter
in this format" << endl;
cout << "Hours : Minutes : Seconds" << endl;
cin >> hours >> mins >> seconds;
time = (hours * 3600) + (mins * 60) + seconds;
cout << "Your Elapsed time in seconds is =" << time << "
seconds" << endl;
}
2. 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 stores 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).
ANS:
#include <iostream>
using namespace std;
void main()
{
float item, markup, ST;
float pp, STR, sp, fp;
cout << "Welcome to NHM Cash N Carry" << endl;
cout << "Please enter Orginal price" << endl;
cin >> item;
cout << "Enter profit percentage" << endl;
cin >> pp;
cout << "Enter Sales Tax Rate" << endl;
cin >> STR;
markup = (item*pp) / 100;
sp = item + markup;
ST = (sp*STR) / 100;
fp = sp + ST;
cout << "\tYour BILL" << endl;
cout << "Original price = " << item << endl;
cout << "Markup of " << pp << "% = " << markup << endl;
cout << "Selling Price = " << sp << endl;
cout << "Sales Tax Rate = " << STR << "%" << endl;
cout << "Sales Tax = " << ST << endl;
cout << "Final price = " << fp << endl;
cout << "Thanks for shopping" << endl;
}
3. 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, 1 feet (foot), and 3 inches
ANS:
#include<iostream>
using namespace std;
void main()
{
double z;
int inch, yard, feet;
cout << "Enter the length in centimeters = ";
cin >> z;
inch = (z/2.54)+0.5;
yard = inch / 36;
feet = (inch / 12)/10;
cout << "The length in yard = " << yard << endl;
cout << "The length in feet = " << feet << endl;
cout << "The length in inches = " << inch << endl;
cout << yard << " yard, " << feet << " feet (foot), and
";
inch = inch % 10;
cout << inch << " inches"<<endl;
}
4. 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
the morning.
b. Outputs the number of milk cartons needed to hold milk. (Round to
int.)
c. Outputs the cost of producing milk.
d. Outputs the profit for producing milk
ANS:
#include<iostream>
using namespace std;
void main()
{
int milk;
float cost, profit, liter;
cout << "Enter the amount of milk cartons = ";
cin >> milk;
liter = milk*3.78;
cost = liter*0.38;
profit = milk*0.27;
cout << "the number of milk cartons = " << milk << endl;
cout << "cost of producing milk = " << cost << "$" <<
endl;
cout << "profit for producing milk = " << profit << "$"
<< endl;
}
Chapter 3
OBJECTIVE
1. Mark the following statements as true or false:
i. >>is used with cout and << is used with cin.
False

ii. Attempting to read invalid data into a variable causes the input
stream to enter the fail state.
True

iii. In the statement cin >> x; x must be a variable.


True

iv. The statement cin >> num; is equivalent to the statement num
>> cin;.
False

v. To use cin and cout, the program must include the header file
string.
False

vi. An output stream is a stream from a source to a computer.


True
vii. An input stream is a stream from a computer to a destination.
True

viii. When inputting data into a variable, the operator>>skips all


leading Whitespace characters.
True

viii. The statement cout<<Hello; would print Hello on the screen.


False

ix. To move the output to next line, endline expression is used.


False
Chapter 3
SUBJECTIVE
1. Suppose x and y are int variables and ch is a char variable.
Consider the following input: 5 28 36
What value (if any) is assigned to x, y, and ch after each of the following
statements executes? (9 marks)
Cin >> x >> y >> ch;
Cin >> ch >> x >> y;
Cin >> x >> ch >> y;

Statement Input Value stored in


memory
Cin >> x >> y >> ch; 5 28 36 x = 5, y = 28, ch =
3,
6 is held for later
input.
Cin >> ch >> x >> y; 5 28 36 Ch = 6, x = 5 , y =
28,
36 is held for later
input.
Cin >> x >> ch >> y; 5 28 36 x = 36, ch = 5, y =
28,
36 is held for later
input.

#include<iostream>
using namespace std;
void main()
{
int x, y; char ch;
cin >> x >> y >> ch; cout <<"x "<< x <<" y "<< y
<<" ch "<< ch << endl;
cin >> ch >> x >> y; cout <<"ch "<< ch <<" x "<<
x <<" y "<< y << endl;
cin >> x >> ch >> y; cout <<"x "<< x <<" ch "<<
ch <<" y "<< y << endl;
}
Output:

2. Given the input: 46 A 49 and the C++ code:


int x = 10, y = 18;
char z = '*';
cin>> x >> y >> z;
cout<< x << " " << y << " " << z << endl;
What is the output?

Statements input Value stored in


memory
int x = 10, y = 18; x = 10, y=18
char z = '*'; z = *

cin>> x >> y >> z; 46 A 49 x = 46, y = 18, z = *

#include <iostream>
using namespace std;
void main()
{
int x = 10, y = 18;
char z = '*';
cin >> x >> y >> z;
cout << x << " " << y << " " << z << endl;
}
Output:

3. Suppose that x and y are int variables, z is a double variable, and ch


is a char variable. Suppose the input statement is: cin >> x >> y >> ch
>> z; What values, if any, are stored in x, y, z, and ch if the input is: (9
marks)

a. 35 62.78

b. 86 32A 92.6

c. 12 .45A 32

# Statement Input Value stored in


memory
a cin >> x >> y >> ch 35 62.78 x = 35, y = 62, ch = .
>> z; , z = 78

b cin >> x >> y >> ch 86 32A 92.6 x = 86, y= 32, ch =


>> z; A, z = 92.6
c cin >> x >> y >> ch 12 .45A 32 x = 12, y = 32, ch =
>> z; A, z = 92.6
.45 is wrong input for
int data type so it
terminates the
further input and the
variables value
doesnt change.
#include <iostream>
using namespace std;
void main()
{
int x, y; char ch; double z;
cin >> x >> y >> ch >> z; cout << "x " << x << " y "
<< y << " ch " << ch << " z " << z << endl;

cin >> x >> y >> ch >> z; cout << "x " << x << " y "
<< y << " ch " << ch << " z " << z << endl;

cin >> x >> y >> ch >> z; cout << "x " << x << " y "
<< y << " ch " << ch << " z " << z << endl;
}
Output:
Chapter 4
OBJECTIVE
1. Given following values of variables, write down the output of C++
expressions mentioned below.
bool found = true;
int age = 20;
double hours = 45.30;
int count = 20;
char ch = 'B';
Expression value
!found
False
hours > 40.00
True
!(found && (age >=
18)) False
(count >= 0) &&
(count <= 100) True
('A' <= ch && ch <=
'Z') False
2. Write down the order of precedence of following operators as
1st, 2nd, 3rd, and so on. For your guidance, the precedence of
expressions in first and second row is already mentioned as 1st
and 3rd. please fill the rest of the cells in the same way.
Operator Precedence
!, +, - (unary operators) 1st

+, - 3rd

<, <=, >=, > 4th

|| 7th

&& 6th

==, != 5th

*, /, % 2nd

3. Solve following objective statements


a. Circle the best answer
if (60 <= 12 * 5)
cout << "Hello";
cout << " There";

Outputs the following:


(i) HelloThere
(ii) Hello
(iii) Hello
(iv) ThereThere
The Correct answer is (i) HelloThere
b. Circle the best answer

if (7 <= 7)
cout << 6 - 9 * 2 / 6 << endl;
Outputs the following:
(i) -1
(ii) 3
(iii) 3.0
(iv) None of these
The Correct answer is (ii) 3
3. Write down the output of following program
#include <iostream>
using namespace std;
int main() {
int myNum = 10;
int yourNum = 30;
if (yourNum % myNum == 3)
{
yourNum = 3;
myNum = 1;
}//end if
else if (yourNum % myNum == 2)
{
yourNum = 2;
myNum = 2;
}// end else if
else
{
yourNum = 1;
myNum = 3;
} //end else
cout << myNum << " " << yourNum << endl;
return 0;
} //end main
OUTPUT :- (i) 1
(ii) 3
5. Rewrite following programs using conditional (ternary) operator
a. if (x >= y)
z = x - y;
else
z= y - x;
(x>=y)?
z= x-y;
z= y-x

b. if (hours >= 40.0)


wages = 40 * 7.50 + 1.5 * 7.5 * (hours - 40);
else
wages = hours * 7.50;
wages = 40*7.50 + q 5*7.5*(hours) : wages = hours*7.50

Chapter 4
SUBJECTIVE
1. Write down C++ program for the problem mentioned as following.
Suppose that over Speed and fine are double variables. Assign the
value to fine as follows: If 0 < over Speed <= 5, the value assigned to
fine is $20.00; if 5 < overSpeed <= 10, the value assigned to fine is
$75.00 if 10 < overSpeed <= 15, the value assigned to fine is $150.00; if
overSpeed > 15, the value assigned to fine is $150.00 plus $20.00 per
mile over 15.
#include<iostream>
using namespace std;
void main()
{
double overspeed, fine, miles;
cout << "Enter the overspeed" << endl;
cin >> overspeed;
if (0 < overspeed&&overspeed <= 5)
{
cout << "Fine=$20.0" << endl;
}
else if (5 < overspeed&&overspeed <= 10)
{
cout << "Fine=$75.0" << endl;
}
else if (10 < overspeed&&overspeed <= 15)
{
cout << "Fine=$110.0" << endl;
}
else if (overspeed > 15)
{
cout << "Enter the miles car has covered over 15"
<< endl;
cin >> miles;
fine = 150.0 + (20 * miles);
cout << "Fine=$" << fine << endl;
}
else
{
cout << " " << endl;
}
system("pause");
}
2. Write the missing statements in the following program so that it
prompts the user to input two numbers. If one of the numbers is 0, the
program should output a message indicating that both numbers must
be nonzero. If the first number is greater than the second number, it
outputs the first number divided by the second number; if the first
number is less than the second number, it outputs the second number
divided by the first number; otherwise, it outputs the product of the
numbers.
#include <iostream>
using namespace std;
int main()
{
double firstNum, secondNum;
cout << "Enter two nonzero numbers: ";
cin >> firstNum >> secondNum;
cout << endl;
//Missing statements
return 0;
}

#include<iostream>
using namespace std;
void main()
{
double a, b;
cout << "Enter first value" << endl;
cin >> a;
cout << "Enter second value" << endl;
cin >> b;
if (a == 0 || b == 0)
{
cout << "Each number must be greater than zero" <<
endl;
}
else if (a > b)
{
cout << "a/b=" << a / b << endl;
}
else if (b > a)
{
cout << "b/a=" << b / a << endl;
}
else
{
cout << "a*b=" << a*b << endl;
}
system("pause");
}
3. Write a program that works like a calculator. The program should
take value1, value2 as integer values and an operator optr as
character value. It should then output the values, the operator, and
the result. (For division, if the denominator is zero, output an
appropriate message.) Some sample outputs follow:
3+4=7
13 * 5 = 65
12 / 0 [print: invalid input]

#include<iostream>
using namespace std;
void main()
{
int value1, value2;
char optr;
double result;
cout << "Enter first number = ";
cin >> value1;
cout << "Enter second number = ";
cin >> value2;
cout << "Enter the operation which you want to perform =
";
cin >> optr;
if (optr == '+')
{
cout << "result = " << value1 + value2 << endl;
}
else if (optr=='-')
{
cout << "result = " << value1 - value2 << endl;
}
else if (optr=='*')
{
cout << "result = " << value1*value2 << endl;
}
else if (optr=='/')
{
if (value2==0)
{
cout << "invalid answere" << endl;
}
else
{
cout << "result = " << value1 / value2 <<
endl;
}
}
else
{
cout << "you Enter wrong operator" << endl;
}
}
4. Write a program that prompts the user to input three numbers.
Now, by using selection (if, if-else) control structure, the program
should then output the numbers in ascending order.

#include<iostream>
using namespace std;
void main()
{
int num1, num2, num3;
cout << "Enter 1st number = ";
cin >> num1;
cout << "Enter 2nd number = ";
cin >> num2;
cout << "Enter 3rd number = ";
cin >> num3;
if (num1 < num2 && num1 < num3)
{
if (num2 < num3)
cout << num1 << "\n" << num2 << "\n" << num3
<< endl;
else
cout << num1 << "\n" << num3 << "\n" << num2
<< endl;
}
if (num2 < num1 && num2 < num3)
{
if (num1 < num3)
cout << num2 << "\n" << num1 << "\n" << num3
<< endl;
else
cout << num2 << "\n" << num3 << "\n" << num1
<< endl;
}
if (num3 < num1 && num3 < num2)
{
if (num1 < num2)
cout << num3 << "\n" << num1 << "\n" << num2
<< endl;
else
cout << num3 << "\n" << num2 << "\n" << num1
<< endl;
}
}
5. A box of cookies can hold 24 cookies, and a container can hold 75
boxes of cookies. Write a program that prompts the user to enter the
total number of cookies, the number of cookies in a box, and the
number of cookie boxes in a container. The program then outputs the
number of boxes and the number of containers to ship the cookies.
Note that each box must contain the specified number of cookies, and
each container must contain the specified number of boxes. If the last
box of cookies contains less than the number of specified cookies, you
can discard it and output the number of leftover cookies. Similarly, if
the last container contains less than the number of specified boxes,
you can discard it and output the number of leftover boxes.
#include<iostream>
using namespace std;
void main()
{
int cookies = 0, box = 0, cont = 0;
cout << "Enter the numbers of cookies you want to
order:-";
cin >> cookies;
box = cookies / 24;
cont = box / 75;
if (cookies % 24 == 0)
{
if (box % 75 == 0)
{
cout << "You need " << box << " number of
boxes and " << cont << " number of containers to ship the
cookies." << endl;
}
else
{
cout << "You need " << box << " number of
boxes and " << cont << " number of containers to ship the
cookies." << endl;
cout << "As the last container did not filled
completely so left over boxes are = " << (box % 75) << endl;
}
}
else
{
if (box % 75 == 0)
{
cout << "You need " << box << " number of
boxes and " << cont << " number of containers to ship the
cookies." << endl;
}
else
{
cout << "You need " << box << " number of
boxes and " << cont << " number of containers to ship the
cookies." << endl;
cout << "As the last container did not filled
completely so left over boxes are =" << (box % 75) << endl;
}
cout << "The last box did not fill completely so
left over cookies are = " << (cookies % 24) << endl;
}
system("pause");
}

Chapter 5
OBJECTIVE

1. Mark the following statements as true or false:


a. In a counter-controlled while loop, it is not necessary to initialize
the loop control variable.
False
b. It is possible that the body of a while loop may not execute at all.
True

c. In an infinite while loop, the while expression (the decision maker)


is initially false, but after the first iteration it is always true.
False
d. The while loop:
j = 0;
while (j <= 10)
j++;
terminates if j > 10.
True
e. A sentinel-controlled while loop is an event-controlled while loop
whose termination depends on a special value.
True
f. A loop is a control structure that causes certain statements to
execute over and over.
True
Chapter 5
SUBJECTIVE
2. Write output of the following C++ code segments:
intnum = 5;
while (num> 5)
num = num + 2;
cout<<num<<endl;

#include <iostream>
using namespace std;
void main()
{
intnum = 5;
while (num> 5)
num = num + 2;
cout<<num<<endl;
}
#include<iostream>
using namespace std;
void main()
{
int num = 5;
while (num>5)
num = num + 2;
cout << num << endl;
}
3. Correct the following code so that it finds the sum of 20 numbers:

sum = 0;
while (count < 20)
cin>>num;
sum = sum + num;
count++;
#include<iostream>
using namespace std;
void main()
{
int sum = 0;
int count = 1;
while (count <= 20)
{
sum = sum + count;
count++;
cout << sum << endl;
}
}
4. Rewrite the following as a for loop.

int i = 0, value = 0;
while (i <= 20)
{
if (i % 2 == 0 && i <= 10)
value = value + i * i;
else if (i % 2 == 0 && i > 10)
value = value + i;
else
value = value - i;
i = i + 1;
}
cout<< "value = " << value <<endl;
What is the output of this loop?
#include<iostream>
using namespace std;
void main()
{
int value = 0;
for (int i = 0; i <= 20; )
{
if (i % 2 == 0 && i <= 10)
value = value + i * i;
else if (i % 2 == 0 && i > 10)
value = value + i;
else
value = value - i;
i = i + 1;
}
cout << "value =" << value << endl;
}

5. What is the output of the following program?


#include <iostream>
using namespace std;
int main()
{
int x, y, z;
x = 4; y = 5;
z = y + 6;
do
{
cout<< z << " ";
z = z + 7;
}
while (((z - x) % 4) != 0);
cout<<endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int x, y, z;
x = 4; y = 5;
z = y + 6;
do
{
cout << z << " ";
z = z + 7;
} while (((z - x) % 4) != 0);
cout << endl;
return 0;
}
6. What is the output of the following program segment?
int count = 5;
while (--count > 0)
cout<< count << " ";
cout<<endl;
#include<iostream>
using namespace std;
void main()
{
int count = 5;
while (--count > 0)
cout << count << " ";
cout << endl;
}

7. Write a program that prompts the user to input an integer and then
outputs both the individual digits of the number and the sum of the
digits. For example, it should output the individual digits of 3456 as 3 4
5 6, output the individual digits of 8030 as 8 0 3 0, output the individual
digits of 2345526 as 2 3 4 5 5 2 6, output the individual digits of 4000 as
4 0 0 0, and output the individual digits of -2345 as 2 3 4 5.
#include<iostream>
#include<math.h>
using namespace std;
void main()
{
int num, digit, sum = 0, rev = 0;
cout << "Enter any number = ";
cin >> num;
while (num>0)
{
rev = rev * 10;
rev = rev + (num % 10);
num = num / 10;
}
cout << "The digits are : ";
while (rev!=0)
{
digit = rev % 10;
sum = sum + digit;
cout << digit << " ";
rev = rev / 10;
}
cout << "\n sum : " << sum << endl;
}
8. Write a program that prompts the user to input a positive integer. It
should then output a message indicating whether the number is a
prime number. (Note: An even number is prime if it is 2. An odd integer
is prime if it is not divisible by any odd integer less than or equal to the
square root of the number?
#include<iostream>
#include<math.h>
using namespace std;
void main()
{
int num,sqr;
cout << "Enter the nmuber = ";
cin >> num;
sqr = sqrt(num);
if(num==2)
cout << "number is even prime" << endl;
else if(num/num == 1 && num%sqr!=0)
cout << "number is odd prime" << endl;
else
cout << "number is not prime" << endl;
}
9. Write a program that uses while loops to perform the following
steps:
a. Prompt the user to input two integers: firstNum and secondNum
(firstNum must be less than secondNum).
b. Output all odd numbers between firstNum and secondNum.
c. Output the sum of all even numbers between firstNum and
secondNum.
d. Output the numbers and their squares between 1 and 10.
e. Output the sum of the square of the odd numbers between firstNum
and secondNum.
f. Output all uppercase letters.
#include <iostream>
using namespace std;
void main()
{
int num1, num2, z = 0;
while (z != 1)
{
cout << "PLease enter the first
value ";
cin >> num1;
cout << "Please enter the second
value ";
cin >> num2;
if (num1 < num2)
z = 1;
else
cout << "The value entered is
wrong Kindly enter the first value less than
the second value " << endl;
}
int i = num1;
cout << "Odd numbers are ";
while (i <= num2)
{
if ((i % 2) == 1)
cout << i << " ";
i++;
}
int sum = 0;
int j = num1; cout << "\n Even numbers
are ";
while (j <= num2)
{
if ((j % 2) == 0)
{
cout << j << " ";
sum = sum + j;
}
j++;
}
cout << "\nSum of even numbers are " <<
sum << endl;
i = 1;
cout << "squares of number from 1-10
\n";
while (i <= 10)
{
cout << 1 << " = " << i*i << endl;
i++;
}
cout << "square of odd numbers \n";
i = num1; sum = 0; int a;
while (i <= num2)
{
if ((i % 2) == 1)
{
a = i*i;
cout << i << " = " << a << endl;
sum = sum + a;
}
i++;
}
cout << "The sum of square of the odd
numbers between first valueand second
value " << sum << endl;
cout << "all upercase ";
char abc;
abc = 'A';
while (abc >= 'A' && abc <= 'Z')
{
cout << abc << " ";
abc++;
}
}
Chapter 9
OBJECTIVE
1. Consider the following declaration:
double salary[10];
In this declaration, identify the following:

a. The array name.


salary
b. The array size.
10
c. The data type of each array component.
double
d. The range of values for the index of the array.
10

2. Identify error(s), if any, in the following array declarations.

a. int list[10];
No errror
b. constint size = 100; double list[SIZE];
No error
c. intnumList[0..9];
Error
d. string names[20];
No error
e. scores[50] double;
Error
3. Determine whether the following array declarations are valid. If a
declaration is invaid, explain why.

a. int list75;
Not valid, the size needs to be declare inside [ ]
b. int size; double list[size];
Not valid, SIZE was not given a value
c. int test[-10]; 3
Not Valid, the subscript cannot be negative
d. double sales[40.5];
Valid

4. What would be a valid range for the index of an array of size 50?
0-49

5. Write C++ statements to do the following:

a. Declare an array alpha of 15 components of type int.


int alpha[15];
b. Output the value of the tenth component of the array alpha.
cout<< alpha[9] <<endl;
c. Set the value of the fifth component of the array alpha to 35.
alpha[4] = 35;
d. Set the value of the ninth component of the array alpha to the sum
of the sixth and thirteenth components of the array alpha.
alpha[8] = alpha[5] + alpha[12];
e. Set the value of the fourth component of the array alpha to three
times the value of the eighth component minus 57.
alpha[3] = 3*alpha[7] 57;
f. Output alpha so that five components per line are printed.
for(int i = 0; i <5 ; i++)
{
cout<< alpha[i] << " ";
}
cout<<endl;

6. Determine whether the following array declarations are valid. If a


declaration is invaid, explain why.
a. int list75;
Not valid, the size needs to be declare inside [ ]
b. int size;
double list[size];
Not valid, SIZE was not given a value
c. int test[-10];
Not Valid, the subscript cannot be negative
d. double sales[40.5];
Valid

7. Suppose list is an array of five components of type int. What is


stored in list after the following C++ code executes?
for (int i = 0; i < 5; i++)
{
list[i] = 2 * i + 5;
if (i % 2 == 0)
list[i] = list[i] - 3;
}
2
7
6
11
10

8. Suppose list is an array of six components of type int. What is


stored in list after the following C++ code executes?
list[0] = 5;
for (int i = 1; i < 6; i++)
{
list[i] = i * i + 5;
if (i > 2) list[i] = 2 * list[i] - list[i - 1];
}

There is a error in the first line and should be replaced by


list[6]

9. Correct the following code so that it correctly initializes and outputs


the elements of the array.
myList;
intmyList[10];
for (int i = 1; i <= 10; i++)
cin>>myList;
for (int i = 1; i <= 10; i++)
cout<<myList[i] << " ";
cout<<endl;

Int main()
{
Int mylist [10];
for ( int i = 1; i <=10; i++)
cin >> myList [i];
for (int i =1; i <10; i++)
{
cout <<myList [i]<< endl;
}
Return 0;
}
Chapter 9
SUBJECTIVE
1. Write a C++ program that declares an array alpha of 50 components
of type double. Initialize the array so that the first 25 components are
equal to the square of the index variable, and the last 25 components
are equal to three times the index variable. Output the array so that 10
elements per line are printed.

#include<iostream>
using namespace std;
void main()
{
double num[50];
for (int i = 0; i < 25; i++)
{
num[i] = i*i;
}
for (int i = 25; i < 50; i++)
{
num[i] = i*i*i;
}
for (int i = 0; i < 50; i++)
{
cout << " num[" << i << "]=" << num[i];
if (i == 9)
{
cout << "\n" << endl;
}
else if (i == 19)
{
cout << "\n" << endl;
}
else if (i == 29)
{
cout << "\n" << endl;
}
else if (i == 39)
{
cout << "\n" << endl;
}
}
cout << "\n" << endl;
}

2. Write a program that displays the minimum and maximum value in


an array along with their index. Moreover, it is required to display the
average of that array.

#include<iostream>
using namespace std;
void main()
{
int num[10], min=1000000, max = 0;
int a, z, sum = 0;
float average;
for (int i = 0; i < 10; i++)
{
cin >> num[i];
if (num[i] < min)
{
min = num[i];
a = i;
}
if (num[i] > max)
{
max = num[i];
z = i;
}
}
cout << "the minimum number is=" << min <<
"index is=num[" << a << "]" << endl;
cout << "the maximum number is=" << max << "
index is=num[" << z << "]" << endl;
for (int i = 0; i < 10; i++)
{
sum= sum + num[i];
}
average = sum / 10;
cout << "the average is= " << average << endl;
}

3. Write a program that displays the odd and even values in an array
along with their indices. Moreover, it is required to display the average
of even and odd elements in that array.
#include<iostream>
using namespace std;
void main()
{
int ch[10], a = 0, b = 0;
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0)
{
cout << "ch[" << i << "]=" << "even" <<
endl;
a = a + i;
}
else if (i % 2 != 0)
{
cout << "ch[" << i << "]=" << "odd" <<
endl;
b = b + i;
}
}
cout << "even numbers average = " << a / 5 << endl;
cout << "odd numbers average = " << b / 5 << endl;
}

Vous aimerez peut-être aussi