Sunteți pe pagina 1din 22

EXERCISE QUESTIONS

Problem Solving and Programming


Exercise Questions (Prepare yourself with logically and conceptually)
C++ Expression
1. Write C++ expressions for the following algebraic expressions:
−b−√ b2−4 ac
 ans=
2a
nx n ( n−1 ) x 2
 x=1+ +
n 2n
2
 ans=
√ b −4 ac
π r2
n ( n−1 ) x 2
 ans=
2 xn
n nx n ( n−1 ) x 2
 u=( 1+ x ) +1+ +
2+3 p ( 1+ x )n
 y=x 4
b+12
 g=
4k
Problem Solving Steps and Tools
2. List the six problem solving steps to solve a problem.
3. Create a flow chart to find student status “Fail” or “Pass”, percentage read from user. If percentage is
less than 50 statuses is “Fail” otherwise “Pass”.
4. Write down the difference between Algorithms and Pseudocode. Write example.
5. Create a flow chart to print the table of a number, number is given by user.
6. Write down the six steps to ensure the best decision (Only name).
7. What do you mean by knowledge base? Why it is important in problem solving process.
8. Describe the main objective of learning problem solving concepts in programming.
9. List and explain the six problem solving steps to solve a problem that have an algorithmic solving.
10. What do you mean by knowledge base? Why it is important in problem solving process.
11. Describe the difference between heuristic and algorithmic solutions to problems.
12. Set-up two different algorithms and flowcharts for calculating a student's letter grade given the
following:
13. (do not use straight — through logic).
90 — 100= A
80 — 89 = B
70 — 79 = C
60 — 69 = D
Bellow — 60 = F
14. The area of a rectangle is the rectangle’s length times its width. Draw a flowchart that asks for the
length and width of two rectangles. The program should tell the user which rectangle has the greater
area, or if the areas are the same.
15. Assuming the ocean’s level is currently rising at about 1.5 millimeters per year, draw a flowchart that
displays a table showing the number of millimeters that the ocean will have risen each year for the
next 25 years.
16. Write an algorithm to print odd numbers from 1 to 50.
17. Draw a flow chart to calculate and print the factorial of a number inputted by the user.
18. Draw a flow chart to print the greater number from the three numbers.
19. A number is even if it is completely divisible by 2 otherwise it is an odd number. Write an algorithm
that takes a number from user and print whether it is even or odd.

1
EXERCISE QUESTIONS

20. The following pseudocode algorithm has an error. The program is supposed to ask the user for the
length and width of a rectangular room, and then display the room’s area. The program must multiply
the width by the length in order to determine the area. Find the error.
 area = width *length.
 Display "What is the room's width?".
 Input width.
 Display "What is the room's length?".
 Input length.
 Display area.
21. Make a flowchart to find the larger number from the given four numbers.
POINTERS
22. What are pointers? Describe it uses.
23. What are pointers in C++? Describe its advantages in C++.
24. What math operations are allowed on pointers?
25. Explain the relationship between Arrays and Pointers.
26. There are three different uses for the * operator. What are they?
27. Write a cout statement that uses the ptr variable to display the contents of the value variable.
double value = 29.7;
double *ptr = &value;
28. What will the following statement display?
int numbers[] = { 2, 4, 6, 8, 10 };
cout << *(numbers + 3) << endl;
what is meant by dynamic memory allocation? Explain New and delete operators with the help of C++ code.
29. Define pointers in detail. Discuss different type of operations performed on pointers.
30. Write a program that inputs two integers and pass these values to a function using pointers. The
function exchanges/swaps the values and the program finally displays the values.

LOOPS
31. State two example codes that result in infinite loop.
32. Which loop should you use in situations where you wish the loop to repeat until the test expression is
false, but the loop should execute at least one time and why? Which loop should you use when you
know the number of required iterations and why?
33. Differentiate between while and for loop? Write example.
34. Convert the following while loop to a for loop:
int count = 0;
while (count < 50)
{
cout << "count is " << count << endl;
count++;
}
35. Differentiate Pre-test and Post-test loops with examples:

36. Rewrite the following range based for loop into regular for loop:
int main()
{
int numbers[ ] = { 3, 6, 9, 12};
for (int val : numbers)
cout << val << endl;
Return 0;
}
37. Write a c++ program to print the following pattern using I/O manipulator instead of using loop:
2
EXERCISE QUESTIONS

***
***
***
***
***
38. Convert the following do-while loop in to a for loop:
int count = 0;
do
{
cout<< “count is “ << count << endl;
count ++ ;
} while ( count < 50);
39. Why we should we avoid goto statement in a program? Write example.
40. Differentiate between continue and break statement? Write example.
41. Write a program that uses nested loops to collect data and calculate the average rainfall over a period
of years. The program should first ask for the number of years. The outer loop will iterate once for each
year. The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will
ask the user for the inches of rainfall for that month. After all iterations, the program should display
the number of months, the total inches of rainfall, and the average rainfall per month for the entire
period.
Input Validation: Do not accept a number less than 1 for the number of years. Do not accept negative
numbers for the monthly rainfall.
42. Write a program that calculates the occupancy rate for a hotel. The program should start by asking the
user how many floors the hotel has. A loop should then iterate once for each floor. In each iteration,
the loop should ask the user for the number of rooms on the floor and how many of them are
occupied. After all the iterations, the program should display how many rooms the hotel has, how
many of them are occupied, how many are unoccupied, and the percentage of rooms that are
occupied. The percentage may be calculated by dividing the number of rooms occupied by the number
of rooms.
Input Validation: Do not accept a value less than 1 for the number of floors. Do not accept a number less than
10 for the number of rooms on a floor.
Assuming the ocean’s level is currently rising at about 1.5 millimeters per year, write a program that displays a
table showing the number of millimeters that the ocean will have risen each year for the next 25 years.
43. How many times will the body of the following loop be executed? What is the last value printed?
int n = 4;
while (n <= 32)
{
n = 2 * n;
cout << n << endl;
}
44. Differentiate between while and do-while loop.
45. Write a program that uses a ‘for’ loop structure and displays the following series: (3)
1,2,4,8,16,32,64
46. Write a program which reads N integer values from the keyboard during program execution and
displays the average of N values. Where N is user defined positive integer.

FUNCTIONS/Built-in Library Functions


47. Write a prototype for a function named f1 that takes two integers and returns an integer.
48. Mention any two pre-define functions along with their purpose and syntax.
49. What is function overloading in C++? Highlight its uses and advantages.

3
EXERCISE QUESTIONS

50. Write a short description of each of the following functions:


 pow
 sqrt
51. Define Function overloading.
52. Write a detailed note on any 6 C-string handling functions. Describe their purpose and usage with the
help of example C++ statement.
53. Describe the purpose and syntax of write and read member functions in binary file processing.
54. What is function? Briefly explain the use of any two built-in functions with concise examples?
55. Using string functions find length of string, copy one string to another string and concatenate two
strings also print results.
56. Write a function named iseven having one parameter type integer to find even or odd number, If even
return true else return false. Use iseven function in main() to demonstrate.
57. Write a function named isprime having one parameter type integer to find prime or not prime, If prime
return true else return false. Use isprime function in main() to demonstrate.
58. A positive integer n is said to be prime if and only if n is greater than 1 and is divisible only by 1 and n.
Write a function named “is_prime” that takes a positive integer argument and returns true if the
argument is prime and false otherwise. Write a main function that inputs an integer and demonstrate
the “is_prime” function.
59. Write a program that asks the user to enter an item’s wholesale cost and its markup percentage. It
should then display the item’s retail price. For example:
If an item’s wholesale cost is 5.00 and its markup percentage is 100%, then the item’s retail price is
10.00.
If an item’s wholesale cost is 5.00 and its markup percentage is 50%, then the item’s retail price is 7.50.
The program should have a function named calculateRetail that receives the wholesale cost and the
markup percentage as arguments, and returns the retail price of the item.
Input Validation: Do not accept negative values for either the wholesale cost of the item or the markup
percentage.
60. Write a function named Factorialfun to find the factorial of a number, number should be pass to
function. Use Factorialfun function in main() to demonstrate.
61. Write a function that calculates the size of the population for a year. The formula is
N = P + BP - DP
where N is the new population size, P is the previous population size, B is the birth rate, and D is the death
rate.
Input Validation: Do not accept numbers less than 2 for the starting size. Do not accept negative numbers for
birth rate or death rate. Do not accept numbers less than 1 for the number of years.
62. Write a program that take strings from the keyboard. Using string functions, the program should find
length of strings, copy one string to another string and concatenate two strings also print results.
63. Write a program that take strings from the keyboard. Using string functions, the program should find
length of strings, copy one string to another string and concatenate two strings also print results.
64. Write a program that asks the user to enter a character. The program should perform case conversion
(i.e. from upper case to lower/ from lower case to upper) using built-in functions.
65. Write a C++ program that take an integer from keyboard and calculate its factorial using recursive
function.

66. Write a program that determines which of a company’s four divisions (Northeast, Southeast,
Northwest, and Southwest) had the greatest sales for a quarter. It should include the following two
functions, which are called by main.
 double getSales() is passed the name of a division. It asks the user for a division’s quarterly
sales figure, validates the input, then returns it. It should be called once for each division.
 void findHighest() is passed the four sales totals. It determines which is the largest and
prints the name of the high grossing division, along with its sales figure.
Input Validation: Do not accept dollar amounts less than $0.00.
4
EXERCISE QUESTIONS

67. Differentiate between strcat() and strncat () function.


68. Convert the following for loop to a while loop:
for( int x = 50; x > 0; x--)
{ cout<< x << “second to go.\n”; }
69. Differentiate between formal parameters and actual parameters.
70. The following statement calls a function named half. The half function returns a value that is half that
of the argument. Write the function.
result = half(number);
71. Write a program that input two integers in the main() function. It uses two functions: first function
calculates the square of first integer and second function calculates the cube of second integer. The
result of these two functions should return to the main ( ) function. The main ( ) function should add
both these results or returned values and display on the screen.

OPERATORS
72. If originally x=10 and y=5, what is the value of each of the expressions:
a. + + x + y
b. - - x + y
c. - - x(+ + y)
d. - - x + y - -
73. Evaluate the following equations, given A=False, B=True, C=False, D=True
a. (A AND B) OR (C AND D) c. NOT (A AND B) OR NOT (D AND C)
b. (A OR B) AND (D OR C) d. NOT (A) AND NOT(B)
74. Assuming x is 5, y is 6, and z is 8, indicate by circling the T or F whether each of the following relational
expressions is true or false:
A) x == 5 T F B) 7 <= (x + 2) T F C) z < 4 T F D) (2 + x) != y T F E) x <= (y * 2)
75. How operator precedence assists in solving an expression?
76. If originally x=10 and y=5 what is the value of each of the expressions:
a. ++x*y
b. –x-y
c. –x-(++y)
d. + + x*x-y - -
77. Assume the following variable definitions:
int a = 5, b = 12;
double x = 3.4, z = 9.1;
What are the values of the following expressions?
 b/a
 x*a
 static_cast<double>(b / a)
 b / static_cast<int>(x)
78. Solve the following using operator precedence and associativity:
(i) 5 + 19 % 3 – 1 (ii) 9 + 12 * (8 - 3) (iii) (6 + 17) % 2 - 1 (iv) (9 - 3) * (6 + 9) / 3
79. Let x is 5 and y is 6, indicate the truth value(True or False) of each of the following compound
conditional expressions:
 (x = 3 && y<=6)
 !(x<=1 || y= =6)
80. Write a program that determine size of integer, float, and character datatypes using sizeof operator.
81. Find the result of the following operations:
a) 20 MOD 3
b) 5<8
c) 25 MOD 70
d) “A” < “H”

5
EXERCISE QUESTIONS

e) 20 * 0.5
f) 4.0 ^ 3
g) True OR False
h) 10/2
82. If X=2 then find the value of X in the expression X* = ++X;
83. What will be the value of Y after executing the following code?
Y=2;
if(Y!=10) Y++;
if(Y==3) Y--;
if(Y!= 3) Y+=5;
cout<< Y;
84. Explain different logical operators used in C++.

Arrays
85. Write difference between arrays and structures? Write example.
Look at the following array definition. int values[10];
a. How many elements does the array have?
b. What is the subscript of the first element in the array?
c. What is the subscript of the last element in the array?
d. Assuming that an int uses four bytes of memory, how much memory does the array use?
86. What do you know about multi-dimensional array? How can we access each element of a 2x2
multidimensional array?
87. Both arrays and structures are capable of storing multiple values. What is the difference between an
array and a structure?
88. Define a two-dimensional array to hold three strings. Initialize the array with your first, middle, and last
names.
89. Define Off-by-one error in Arrays
90. Write a program that creates an integer array of size 10 and assigns random numbers to each element
of the array in such a way that each time the program is executed, different set of random numbers are
assigned to array elements. The program then reverses the elements in the array.

91. We know that when an array is defined a constant pointer is created which stores the starting address
of an array. A constant pointer, with the name of 'arr' , is created as given below:
Base Address of arr
100
100 Array
10 20 30 40 50 60
Array [0] Array [1] Array [2] Array [3] Array [4] Array [5]

Consider the above diagram to solve the following:


a) double array[6] = {10,20,30,40,50,60}; calculate (i) (arr+4) (ii) *(arr+4)
b) int array[6] = {10,20,30,40,50,60}; calculate (i) (arr+3) (ii) *(arr+3)
92. Write a program that transposes a two dimensional square array of integers and display the
transposed array. For example, it would transform the array
1 1
22 33 44 77
1 1
4 2
55 66 In to the array 55 88
4 2
7 3
88 99 66 99
7 3

6
EXERCISE QUESTIONS

93. The local Driver’s License Office has asked you to write a program that grades the written portion of
the driver’s license exam. The exam has 20 multiple choice questions.
Here are the correct answers:
1. B 2. A 3. C 4. B 5. C 6. D
7. B 8. C 9. C 10. A 11. A 12. D
13. B 14. A 15. A 16. D 17. D 18. D
19. D 20. A
Your program should store the correct answers shown above in an array. It should ask the user to enter the
student’s answers for each of the 20 questions, and the answers should be stored in another array. After the
student’s answers have been entered, the program should display a message indicating whether the student
passed or failed the exam. (A student must correctly answer 15 of the 20 questions to pass the exam.)
It should then display the total number of correctly answered questions, the total number of incorrectly
answered questions, and a list showing the question numbers of the incorrectly answered questions.
94. Write a program that uses nested for loops to fill the two dimensional array 5x5 with the
multiplication table as shown below using nested loop, print the array in the following format:
1 2 3 4 5
2 4 6 8 10
1
3 6 9 15
2
1
4 8 12 20
6
2
5 10 15 25
0
95. Write a program that lets the user enter the total rainfall for each of 12 months into an array of
doubles. The program should calculate and display the total rainfall for the year, the average monthly
rainfall, and the months with the highest and lowest amounts.
Input Validation: Do not accept negative numbers for monthly rainfall figures.
96. A magic square matrix is a square matrix (i.e. with same number of rows and columns) of positive
integers such that the sum of each row, column and both diagonals is same. For example, the following
matrix is a magic square with sum=34:
97. Write a program that lets the user enter a string into a character array. The program should then
convert all the lowercase letters to uppercase. (If a character is already uppercase, or is not a letter, it
should be left alone.)
Hint: Notice that the lowercase letters are represented by the ASCII codes 97 through 122. If you subtract 32
from any lowercase character’s ASCII code, it will yield the ASCII code of the uppercase equivalent.

16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
98. Write a function that takes a matrix and its size as parameters and returns true if the matrix is a magic
square, otherwise returns false.
Take 20 integer input from user in an array and print the following:
 No of positive number
 No of negative numbers
 No of odd numbers
 No of even numbers.
99. Write a function named "number_of_matches" that compares the two character arrays to see how
many corresponding elements of the two arrays match with each other before a difference occurs. For
example, if the arrays are Error! And Errer! then the function should return the value 3 because only
the first three pain of elements in the arrays match. Each character array is null terminated and make

7
EXERCISE QUESTIONS

sure the pairwise cell comparisons should not go beyond the end of either array. The function should
take only two parameters, namely the two character arrays to be compared.
100. Multiply two matrices using multidimensional array and print the resultant matrix.
101. Write a Program in C++ that displays the Transpose of a Matrix(2D Array).
102. Write a function that uses an array parameter to accept a string as its argument. It should
convert the first letter of each word in the string to uppercase. If any of the letters are already
uppercase, they should be left alone. (See the hint in Problem 7 for help on converting lowercase
characters to uppercase.
103. Hint: Notice that the lowercase letters are represented by the ASCII codes 97 through 122. If
you subtract 32 from any lowercase character’s ASCII code, it will yield the ASCII code of the uppercase
equivalent.
104. Declare an array named arr that has 3 rows and 5 columns and assign it values from 6 to 20 in
declaration statement.
105. What are arrays? Discuss different ways to initialize one dimensional and two dimensional
arrays, give suitable examples.
106. Write a program that lets the user enter ten values into an array. The program should then
display the largest and smallest values stored in the array?
107. Write a program to enter data into one dimensional array. Find out the maximum value and its
location in the array and print the result on the screen.
108. Write a program that initializes a string to a string variable and computes the total number of
characters of that string.
DATA TYPE/VARIABLE
109. Name the data type for each of the following values:
a. 5.344
b. Quaid-e-Azam University
c. True
d. 001,103,19,56,76
How may the int variables months, days, and years be defined in one statement, with months initialized to 2
and years initialized to 3?
110. Which of the following are illegal variable names, and why?
 99bottles
 july97
 p+9
 grade_report
111. Examine the following program.
#include <iostream>
using namespace std;
int main()
{
int little;
int big;
little = 2;
big = 2000;
cout << "The little number is " << little << endl;
cout << "The big number is " << big << endl;
return 0;
}
List all the variables and literals that appear in the program.
112. Write detailed notes on the following with concise example (C++ program).
 Scope and life time of local, global and static variables.
 Rules for naming identifiers in C++

8
EXERCISE QUESTIONS

113. Convert the following pseudocode to C++ code. Be sure to define the appropriate variables.
 Store 172.5 in the force variable.
 Store 27.5 in the area variable.
 Divide area by force and store the result in the pressure variable.
 Display the contents of the pressure variable.
114. Mark the following as legal or illegal variable, justify each of your choice in single line.
 dayOfmonth
 2Dmatrix
 Roll.no
 VaR2
115. List the variables, literals, strings, and operators in the following C++ statements:
{
int totalSeconds = 125;
int minutes = totalSeconds / 60, seconds = totalSeconds % 60;
cout<< totalSeconds << “ Seconds is equivalent to : \n”;
cout << “minutes : “ <<minutes << endle;
cout << “seconds : “ << seconds << endle;
}
116. How static local variable differs from local variable and similar with global variable?
117. What is type casting? Differentiate explicit and implicit type casting. Explain with example code.
118. Why Type Casting is useful, define with an example.
119. What is a primitive data type?

Decision Control Structure


120. Compare different options available in C++ for decision making. Give example.
121. Which one is good if-else or switch-case and also define these limitations in C?
122. Rewrite the following if/else statement as conditional expression (ternary operator):
if (N%2==0)
cout<<N << " is Even";
else
cout<<N << " is Odd";
123. Convert the following segment of code (if else ... ) to equivalent Switch.
int main()
{
int x;
cin >> x;
if (x == 2)
cout << "x=2";
else if (x= =3 || x= =5)
{
cout << "x=3 or 5";
x++;
}
else if (x= =4)
cout << "x=4";
else
cout << "Else.";
return 0;
}

9
EXERCISE QUESTIONS

124. Write a program that asks the user to enter a number within the range of 1 through 10. Use a
switch statement to display the Roman numeral version of that number. Input Validation: Do not
accept a number less than 1 or greater than
Write a program that displays the following menu:
Geometry Calculator
1. Calculate the Area of a Circle
2. Calculate the Area of a Rectangle
3. Calculate the Area of a Triangle
4. Quit
Enter your choice (1-4): __
If the user enters 1, the program should ask for the radius of the circle and then display its area. Use the
formula:
area = πr2 Use 3.14159 for π and the radius of the circle for r.
If the user enters 2, the program should ask for the length and width of the rectangle and then display the
rectangle’s area. Use the formula: area = length * width.
If the user enters 3 the program should ask for the length of the triangle’s base and its height, and then display
its area. Use the formula: area = base * height * .5
If the user enters 4, the program should end.
Input Validation: Display an error message if the user enters a number outside the range of 1 through 4 when
selecting an item from the menu. Do not accept negative values for the circle’s radius, the rectangle’s length
or width, or the triangle’s base or height.
Write a C++ program that find odd or even number using conditional operators.
125. Write a program in C++ that inputs a number of month of the year and displays the number of
days of the corresponding using if…else…if statement. (e.g if user enters 2, it will display 28 or 29).
126. 121. Write a program that converts ASCII number to character or character to ASCII number.
The program should display the menu for conversion options. Interaction with the program should be
as follows: (4)
Convert ASCII to character
Convert character to ASCII
Enter your option? 1
Enter a number? 65
The corresponding character is: A
127. Differentiate between “switch” and “nested if-else ” structures.

FORMATTING / COMMENTS/Sequential Control Structure


128. Briefly comment each of the following lines of code. The first line is done for you. Make sure
you describe the difference between statements.
int x = 2; //Creates integer variable named x and assigns it a value 2.
int *p;
p = &x;
*p = 4;
cout << p;.
cout << *p;
int fun(int *, int*);
129. What header files must be included in the following program?
int main(){
double amount = 89.7;
cout << showpoint << fixed;
cout << setw(8) << amount << endl;
return 0;}
130. Modify the following program so it prints two blank lines between each line of text.

10
EXERCISE QUESTIONS

#include <iostream>
using namespace std;
int main()
{
cout << "Two mandolins like creatures in the";
cout << "dark";
cout << "Creating the agony of ecstasy.";
return 0;
}
131. In a population, the birth rate is the percentage increase of the population due to births and the
death rate is the percentage decrease of the population due to deaths. Write a program that displays
the size of a population for any number of years. The program should ask for the following data:
• The starting size of a population
• The annual birth rate
• The annual death rate
• The number of years to display
132. The area of a rectangle is the rectangle’s length times its width. Write a program that asks for
the length and width of two rectangles. The program should tell the user which rectangle has the
greater area, or if the areas are the same.
133. Write a program to calculate the net pay of an employee. Input the basic pay and calculate the
gross and net pay as follow:
 House rent is 45% of the basic pay
 Medical allowance is 5% of basic if the basic is greater than Rs. 30,000. It is 10% if the basic is less
than Rs. 30,000.
 conveyance allowance is Rs. 5000, if basic is less than or equal to Rs. 25000. It is 7000 if basic is
more than Rs. 25000.
 Gross pay is calculated by adding basic pay, medical allowance, conveyance allowance and house
rent.
Net pay is calculated by deducting G P Fund Rs. 4000 and tax of 2% on Gross pay.
134. What will be the value of each expression in C++?
(i) 6 + 17 % 3 – 2 (ii) 14 / (10-6) – 1
135. Write a C++ program with two functions area and perimeter to find the area and perimeter of a
square.
A software company sells a package that retails for $99. Quantity discounts are given according to the
following table.

Quantity Discount
10-19 20%
20-49 30%
50-99 40%
100 or more 50%
136. Write a program that asks for the number of units sold and computes the total cost of the
purchase.
Input Validation: Make sure the number of units is greater than 0.
Write a program that swaps (exchanges) two values by passing pointers as arguments to the function.
FILING
137. Explain six different modes of opening file.
138. what do you understand by the opening a file?
139. Explain the file access flags with the help of example codes.
140. Explain Read position in file processing
141. Define some basic operations that are performed on data file.
11
EXERCISE QUESTIONS

142. Explain the three basic operations of file handling with general syntax.
143. In the d: (D Drive) you will find a file named “text.txt”. And make its copy with name
“copytext.txt”.
144. In the d: (D Drive) you will find a file named “text.txt”. Write a program that reads the file’s
contents and determines the following:
• The number of uppercase letters in the file
• The number of lowercase letters in the file
• The number of digits in the file
• The number of whitespace characters in the file
145. In the d: (D Drive) you will find a file named “text.txt”. Write a program that reads integer
contents in file and print their sum.
146. File encryption is the science of writing the contents of a file in a secret code. Your encryption
program should work like a filter, reading the contents of one file named “input.txt”, modifying the
data into a code, and then writing the coded contents out to a second file named “output.txt”. The
second file will be a version of the first file, but written in a secret code. Although there are complex
encryption techniques, you should come up with a simple one of your own. For example, you could
read the first file one character at a time, and add 10 to the ASCII code of each character before it is
written to the second file.
147. Write a program that read integers form a file and print their sum.
148. Write a C++ program to write the multiples of 5 excluding the numbers divisible by 3 and 7
from 1 to 1000 in a file.
149. Write a program that ask the user to enter the full names (first-name second-name) of his three
friends, write them in to a file (myFriends.txt) and close the file, then reopen the same file after closing
and append his own name.
150. Write a program that opens a file (d:\numbers.txt) in reading mode. Assume “numbers.txt”
contains unknown number of integer values. The program should test for file opening error, then reads
all values from the file till end and display them.
151. Write code that does the following: Opens an output file with the file name Numbers.txt, uses a
loop to write numbers 1 through 100 to the file, and then closes the file.
152. Discuss the seekp() function according to the file handling in C++.
153. Define file pointers.
Introduction to Programming
154. What is a run-time error?
155. What is the difference between a syntax error and a logical error? Write example.
156. Explain what is stored in an object file.
157. Explain what is stored in an executable file.
158. What header file must be
included in programs using cin?
159. What are the three primary
activities of a program?
160. What kind of file is produced when a CPP file with no syntax error is compiled?
161. What is the difference between sequential file access and random file access methods?
162. What is the difference between expression and equation?
163. Differentiate between C++ statements and preprocessor directives.
164. Define logical errors and why logical errors are most difficult to find and remove?

Structure
165. Write a program that creates an employee structure with ID(integer), Name(char array of size
30), DateofBirth (Date structure with day month and year as integers), and Salary(floating-point) and
uses this structure to create an array of 10 employees. Write a function to input the values of all the
12
EXERCISE QUESTIONS

fields of each employee in the array. Then write another function that displays only those records of
employees for which salary is between 8000.0 to 15000.0.
166. Write a program that creates a student structure with ID(integer), Name(char array of size 30),
DateofBirth (Date structure with day month and year as integers), semester(integer), Marks of 5
subjects(integer array of size 5) and Averagemarks(floating-point) and uses this structure to create an
array of 10 students. Write a function to input the values of all the fields of each student in the array
and set the Averagemarks of each student according to the marks obtained in 5 subjects. Then write
another function that displays only those records of students who got an A grade (i.e. with
Averagemarks>=80).
167. Write a program that stores data about a Circle in a structure. Circle have radius, diameter,
and area, and uses this structure to create an array of 10 circle. Write a function to input the radius of
each circle in the array and set the diameter and area of each circle according to the radius. Then write
another function that displays all the fields of each Circle.
168. Write a program that uses a structure to store the following data about a customer account:
Name
Address
City, State, and ZIP
Telephone Number
Account Balance
Date of Last Payment
The program should use an array of at least 20 structures. It should let the user enter data into the array,
change the contents of any element, and display all the data stored in the array. The program should have a
menu-driven user interface.
Input Validation: When the data for a new account is entered, be sure the user enters data for all the fields.
No negative account balances should be entered.
169. Create a structure named Student to specify data of students as given below:

Roll number, Name, Department, Course, Year of joining


Assume that there are not more than 450 students in the college.
(a) Write a function to input and store data of all the students in the array of structure.
(b) Write a function to print names of all students who joined in a particular year.
(c) Write a function to print the data of a student whose roll number is given.
170. Write a program that simulates a soft drink machine. The program should use a structure that
stores the following data:
 Drink Name
 Drink Cost
 Number of Drinks in Machine
The program should create an array of five structures. The elements should be initialized with the following
data:
Drink Name Cost Number in Machine
7up 50 20
Cola 50 20
Lemonade 55 20
Mint-Margarita 60 20
Miranda 50 20

Each time the program runs, it should enter a loop that performs the following steps: A list of drinks is
displayed on the screen. The user should be allowed to either quit the program or pick a drink. If the user
selects a drink, he or she will next enter the amount of money that is to be inserted into the drink machine.
The program should display the amount of change that would be returned and subtract one from the number
of that drink left in the machine. If the user selects a drink that has sold out, a message should be displayed.

13
EXERCISE QUESTIONS

The loop then repeats. When the user chooses to quit the program it should display the total amount of
money the machine earned.
171. What is the difference between declaring and defining a structure?
172. Define array of structure.
173. Write the code to declare a struct type person with two fields, name and age and a pointer
called aPointer to a struct type variable.
174. Write a program that declares a structure to store marks and grade of a student. It defines two
structure variables. It inputs the values in one variable and assigns that variable to the second variable.
It finally displays the value of both variables.
Write a program that uses a structure PayRoll to store the following information about an employee:
employee number, name,
hours ( Number of hours worked by the employee)
payRate ( hourly rate)

The program should declare two structure variable emp1 and emp2, and stores values in their members and
then calculates gross pay as
gross pay = hours * payRate
175.Finally display both employees’ data on screen. Also display the employee name with greater gross
pay.
Write a program that defines a structure to store the distance covered by a player and the time taken in
minutes and seconds to cover the distance. The program should input the records of three players and then
display the record of the winner.

(Predict the Output as display on console or file)


#include <iostream>
using namespace std; #include <iostream>
main() using namespace std;
{ int main(){
int i,j; char p[][12]={“Please”,“Solve”,“It”, “care”};
for(i=1;i<=5;i++) cout<<p[1]<<endl;
1 2
{ cout<<(char)(p[0][1]-32)<<endl;
for(j=1;j<=i;j++) cout<< --p[2][1]<<endl;
cout<<”@”; cout<<*p[3]<<endl;
cout<<”\n”; return 0;
} }
}
3 #include <iostream> 4 #include <iostream>
using namespace std; #include <fstream>
void test(int = 10,int=20,int =30); using namespace std;
int main() int main()
{ {
test(); const int SIZE = 5;
test(6); ofstream outFile("out.txt");
test(3,9); double nums[SIZE] = {100.279, 1.719, 8.602, 7.777,
test(1,5,7); 5.099};
return 0;
} for (int count = 0; count < 5; count++)
void test(int f, int s, int t) {
{ outFile<<count<<" count: ";
cout<<f<<s<<t<<endl; outFile << nums[count];

14
EXERCISE QUESTIONS

outFile<<"\n";
}
} outFile.close();
return 0;
}
5 #include <iostream> 6 #include <iostream>
using namespace std; using namespace std;
int f(int n) int main()
{ for(int i=0;i<n+2;i++) {
cout<<"f"; for(int i=0;i<8;i++)
cout<<endl; {
return (n-1);} if(i%2==0) cout<<i+1<<endl;
void h(int m) else if(i%3==0) continue;
{ cout<<"h"; else if(i%5==0) break;
f(m-1); cout<<”end of program \n”;
cout<<"h"<<endl; }
return;} cout<<”end of program \n”;
int main(){ }
h(f(3));
f(3)+f(2);
h(f(5)+5);
return 0;
}

7 #include <iostream> 8 #include <iostream>


using namespace std; using namespace std;

int main() int main()


{ {
int x = 25, y = 50, z = 75; int numberArray1[]={12,34,67,89,23,12};
int *ptr; int numberArray2[]={12,34,67,89,23,12};
cout << " values of x, y, and z:\n"; int total = 0;
cout << x << " " << y << " " << z; int count;
ptr = &x; *ptr += 100; ptr = &y; for (count = 0; count < 6; count++)
*ptr += 100; total += numberArray1[count]-count;
ptr = &z; cout << total << endl;
*ptr += 100; for (count = 0; count < 6; count++)
cout << "\n values of x, y, and z:\n"; total += numberArray2[count]+count;
cout << x << " " << y << " " << z ; cout << total << endl;
return 0;
} return 0;
}
9 #include <iostream> 10 #include <iostream>
using namespace std; using namespace std;
int func(int x, int y) int main()
{ {
if(x<y) int count = 1, total=25;
return func(x+5,y-5)+func(x+8,y-2); while (count <= 10)
else {
return (x*y);
15
EXERCISE QUESTIONS

} total += count;
int main(){ count=count+2;
int n=func(2,20); }
cout<<n; cout << "The sum of the numbers is ";
return 0; cout << total << endl;
} return 0;
}

11 #include <iostream> 12 #include <iostream>


using namespace std; using namespace std;

int main() void displayValues(const int *, int);


{
const int NUM_LETTERS = 05; int main()
char letters[NUM_LETTERS] = {
{'C','D','E','J','Z'}; const int SIZE = 6;
cout<<"Character"<<"\t"<<"ASCII int array1[SIZE] = { 1, 2, 3, 4, 5, 6 };
Code\n"; int array2[SIZE] = { 2, 4, 6, 8, 10, 12 };
cout<<"---------"<<"\t"<<"----------\n"; displayValues(array1, SIZE);
for (int count = 0; count < NUM_LETTERS; displayValues(array2, SIZE);
count++) return 0;
{ }
cout <<letters[count]<< "\t\t"; void displayValues(const int *numbers, int size)
cout << static_cast<int>(letters[count]) << {
endl; for (int count = 0; count < size; count++)
} {
return 0; cout << *(numbers + count) << " ";
} }
cout << endl;
}
13 #include <iostream> 1 #include <iostream>
using namespace std; 4 using namespace std;
main() int main()
{ {
int num1=23, num2=66; char string1[]=”Hello I am a student”;
do{ char string2[]=”Hello i am a student”;
cout << "Their sum is " << (num1 + num2) if (string1 == string2)
<< endl; cout << "The strings are the same.\n";
num1=num1+100; else
num2=num2+100; cout << "The strings are not the same.\n";
} while (num2<500); return 0;
} }

15 #include <iostream> 1 #include <iostream>


using namespace std; 6 using namespace std;
int test(int n1,int n2) main()
{ {
cout<<n2<<n1<<endl; int i,j;
return n2*n1; for(i=1;i<=5;i++)
} {
main(){ for(j=1;j<=i;j++)
16
EXERCISE QUESTIONS

int n1=2, n2=3, n3=4; cout<<j;


n2=test(test(n1,n3),n2); cout<<”\n”;
cout<<n1<<endl<<n3<<endl<<n2<<endl; }
} }
17 #include <iostream> 1 #include <iostream>
using namespace std; 8 using namespace std;
int main() int main(){
{ const int NUM_MONTHS = 12;
long seconds; double minutes, hours, const int STRING_SIZE = 10;
days, months, years; char months[NUM_MONTHS][STRING_SIZE] =
cout << "Enter the number of seconds that { "January", "February", "March","April", "May",
have\n"; cout << "elapsed since some "June","July",
time in the past and\n"; "August", "September","October", "November",
cout << "I will tell you how many minutes, "December" };
hours,\n"; cout << "days, months, and int days[NUM_MONTHS] = {31, 28, 31, 30,31, 30,
years have passed: "; 31, 31,30, 31, 30, 31};
seconds=3600; for (int count = 0; count < NUM_MONTHS; count++)
minutes = seconds / 60; hours = minutes / {
60; cout << months[count] << " has ";
days = hours / 24; years = days / 365; cout << days[count] << " days.\n";
months = years * 12; }
cout << "Minutes: " << minutes << return 0;}
endl;cout << "Hours: " << hours << endl;
cout << "Days: ”<< days << endl; cout <<
"Months: ” << months << endl;
cout << "Years:” << years << endl; return
0;
}
19 #include <iostream> 2 #include <iostream>
using namespace std; 0 using namespace std;
int main()
int main( ) {
{ for (int i =0;i<40; i++) short numbers[] = {10, 20, 30, 40, 50};
{ cout << "Answer ";
if (i % 4==0) cout << *numbers << endl;
cout<<i + i<<endl; return 0;
else if (i %2 ==0) continue; }
else if (i % 7==0) break;
}
}
21 #include <iostream> 2 int main()
using namespace std; 2 { for (int i=0 ;i<100; i++)
const int LENGTH = 25; {
struct EmployeePay if (i<5)
{ continue;
char name[LENGTH]; int empNum; double cout<< i << “,” ;
payRate; double hours; double grossPay; }
}; return 0;
int main() }
{
EmployeePay employee1 = {"Betty Ross",
141, 18.75};
17
EXERCISE QUESTIONS

cout << "Name: " << employee1.name <<


endl;
cout << "Employee Number: " <<
employee1.empNum << endl;
employee1.hours=100;
employee1.grossPay = employee1.hours *
employee1.payRate;
cout << "Gross Pay: " <<
employee1.grossPay << endl << endl;
return 0;}
23 void fun(){ 2 int x = 7;
static int n=5; 4 int y = 3;
cout<<"n = "<< ++n<<endl; cout << x/y << " , " << x%y<<" and "<<++x*y--;
}
int main() { fun();
fun();
fun();
return 0; }
25 #include <iostream> 2 #include <iostream>
6 using namespace std;
include <iomanip>
void showValues(int [], int);
using namespace std;
int main()
int main()
{
{
const int ARRAY_SIZE = 8;
const int NUM_COINS = 5;
int numbers[ARRAY_SIZE] = {5, 10, 15, 20, 25, 30, 35,
double coins[NUM_COINS] = {0.05, 0.1,
40};
0.25, 0.5, 1.0};
showValues(numbers, ARRAY_SIZE);
double *doublePtr;
return 0;
int count;
}
for (count = 0; count < NUM_COINS;
void showValues(int nums[], int size)
count++)
{
{doublePtr = &coins[count];
for (int index = 0; index < size; index++)
cout << *doublePtr << " ";}
cout << nums[index] << " ";
cout << endl;
cout << endl;
return 0;
}
}
27 #include <iostream> 2 int funny = 7, serious = 15;
using namespace std; 8 funny = serious % 2;

int main() if (funny != 1 )


{ {
int x = 25; funny = 0;
int *ptr; serious = 0;
}
ptr = &x; else if ( funny == 2)
cout << "The value in x is " << x << endl; {
cout << "The address of x is " << ptr << funny = 10;
endl; serious = 10;
return 0; }
} else
{
funny = 1;
18
EXERCISE QUESTIONS

serious = 1;
}
cout << funny << “ “ << serious <<endl;
29 int x = 50, y = 60, z = 70; 3 int x=0;
int *ptr; 0 while(++x<5);
cout<< x << “ ” << y << “ “<< z <<endl; {
ptr = &x; x++;
*ptr *= 10; x=x*2;
ptr = &y; }
*ptr *= 5; cout<< x;
ptr = &z;
*ptr *= 2;
cout<< x << “ ” << y << “ “<< z <<endl;

31 # include<iostream> 3 for (int row = 1; row <= 3; row++)


using namespace std; 2 { cout << "\n$";
void test( int = 2, int = 4, int = 6); for (int digit = 1; digit <= 4; digit++)
int main() cout << '9';
{ }
test();
test(6);
test(3, 9);
test(1, 5, 7);
return 0;
}
void test(int first, int second, int third)
{
first += 3;
second += 6;
third += 9;
cout<< first << “ ” << second << “ “<< third
<< endl;
}

33 int c = 1; 3 int test(int n1 , int n2)


while (c % 3 > 0) 4 {
{ cout<< n2 <<n1<<endl;
c +=4; return n2 * n1;
cout<< c << “x”; }
} void main()
{
int n1 = 2, n2 =3, n3 =4;
n2 = test ((test(n1, n3), n2);
cout << n1 << n3 << n2 <<endl;
}
35 int num[5] = {3, 4, 6, 2, 1};
. int *p = num;
int *q = num + 2;
int *r = &num[1];
cout<<num[2]<<” “<<*(num+2)<<endl;
cout<<*p <<” “<< *(p + 1) << endl;
19
EXERCISE QUESTIONS

cout<<*q <<” “<< *(q + 1) << endl;


cout<<*r <<” “<< *(r + 1) << endl;

Find the Errors


#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
int main ()
struct TwoVals(int a, b;)
{
int main ()
area(10,'C');
1 2 {
return 0;
TwoVals A;
}
A.a=10;A.b=12;
void area(int length , int width);
return 0;
{
}
cout<<length<<width;}
#include <iostream>
using namespace std;
#include <iostream>
main()
using namespace std;
{
int main ()
int num1, num2;
{
char again;
3 int values[20], *iptr; 4
while (again == 'y' || again == 'Y')
iptr = values;
cin >> num1;
iptr *= 2;
cin >> num2;
return 0;
cout << "heir sum is<< (num1 + num2) << endl;
}
cout << "Do you want to do this again? ";
cin >> again;}
#include <iostream>
using namespace std; #include <iostream>
void area(int length = 30, int width) using namespace std;
{ struct TwoVals{int a, b;};
return length * width; int main ()
5 } 6 {
int main () twovals A;
{ A>>a=10;
area(10,10); return 0;
return 0; }
}
#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
int main ()
int main ()
{
{
7 8 char string1[] = "Billy";
int array1[4], array2[4] = {3, 6, 9, 12};
char string2[] = " Bob Jones";
array1[i] = array2[2];
strcat(string1, string2);
return 0;
return 0;
}
}
9 #include <iostream> 10 #include <iostream>
using namespace std; using namespace std;
void showValues(int nums)
{ struct TwoVals{int a, b;};
for (int count = 0; count < 8; count++) int main ()

20
EXERCISE QUESTIONS

cout << nums[count];


{
}
TwoVals.a = 10;
int main (){
TwoVals.b = 20;
showValues(A);
return 0;
return 0;
}
}
#include <iostream>
using namespace std;
#include <iostream>
#include <cstring>
using namespace std;
int main (){
int main (){
11 12 char string1[] = "Billy";
int array1[4], array2[4] = {3, 6, 9, 12};
char string2[] = " Bob Jones";
array1 = array2;
int a=strlen(string1, string2);
return 0;}
return 0;
}
1 void total(int value1, value2, value3) 14 double average(int value1, int value2, int value3)
3 { {
return value1 + value2 + value3; double average;
} average = value1 + value2 + value3 / 3;
}
1 #include <iostream> 16 #include <iostream>
5 using namespace std; using namespace std;
main() main()
{ {
int num, bigNum, power, count; int choice;
cout << "Enter an integer: "; do
cin >> num; {
cout << "What power do you want it raised cout << "Do you want to do this again?\n";
to "; cout << "1 = yes, 0 = no\n";
cin >> power; cin >> choice;
bigNum = num; } while (choice == 1)
while (count++ < power); }
bigNum *= num;
cout << "The result is << bigNum << endl;
}
1 The following statement should determine 18 #include <iostream>;
7 if count is within the range of 0 through using namespace std;
100. What is wrong with it? main{
int number1, number2;
if (count >= 0 || count <= 100) cin >> number1 >> number2;
cout << number1 << " " << number2;
}
1 #include<iostream> 20 int main(){
9 using namespace std; int m;
void square(int a){ cout<<"Enter marks";
cout<<"Square of "<<a <<" is" <<a=*a; cin>>m;
} if (m>80)
int square(int a){ cout<<"Grade is A+ "<<endl;
return a=*a; if (m>70)
} cout<<"Grade is A "<<endl;
int main(){ if(m>60)
cout<<fun(5)<<endl; cout<<"Grade is B "<<endl;
21
EXERCISE QUESTIONS

cout<<fun(6)<<endl; if (m>50)
return 0; cout<<"Grade is C "<<endl;
} if(m<50)
cout<<" Failed "<<endl;
return 0;
}
2 int N = 8; int factorial = 1; 22 #include <iostream>
1 while ( N >= 1 ) using namespace std;
factorial = factorial * N; int main (){
N-- area(10,'C');
cout << "8! = " << factorial << "\n"; return 0;
}
void area(int length , int width);
{
cout<<length<<width;return 0; }
2 double average( int value1, int value2, 24 struct TwoVals
3 value3) {
{ int a, b;
double average
average = value1 + value2 + value3 / 3; }

} int main()
{
TwoVals.a = 10;
TwoVals.b = 20;

return 0;
}

2 #include <iostream.h>
5 main ( )
{
int X [2][2]= {2,3,4} , {3, 6, 15};
for( i=0; i<=1; i++) ;
cout << X [0][i] << endl;
}

22

S-ar putea să vă placă și