SH 3
SH 3
1) Rewrite the following loops as for loops, and then write their outputs, when embedded in a complete
program:
a) int i=1;
while (i<=10)
{
if (i<5 && i!=2)
cout << ’X’;
i++;
}
b) long m=100;
do
{
cout << m << " ";
m = m+100;
}
while (m<1000);
2) What output will be produced by each of the following codes, when embedded in a complete program?
a) int n=8;
while (--n>0)
{
if (n==2)
exit(0);
cout << n << " ";
}
cout << "\nEnd of Loop.";
b) int n=8;
while (--n>0)
{
if (n==2)
break;
cout << n << " ";
}
cout << "\nEnd of Loop.";
3) Assume that you want to generate a table of multiples of any given number. Write a C++ program
that allows the user to enter a number of type int and then generates the table, formatting it into
10 columns and 10 lines. Interaction with the program should look like this (only the first three lines
of the table are shown):
1
Enter a number: 7
7 14 21 28 35 42 49 56 63 70
77 84 91 98 105 112 119 126 133 140
147 154 161 168 175 182 189 196 203 210
4) Create the equivalent of a four-function calculator. The program should ask the user to enter two
numbers of type float and an operator. It should then carry out the specified arithmetical operation:
adding, subtracting, multiplying, or dividing the two numbers. Use a switch statement to select the
operation. Finally, display the result.
When it finishes the calculation, the program should ask whether the user wants to do another
calculation. The response can be ’y’ or ’n’. Some sample interaction with the program might look
like this:
Enter first number, operator, second number: 10 / 3
Answer = 3.333333
Do another (y/n)? y
Enter first number, operator, second number: 12 + 100
Answer = 112
Do another (y/n)? n
5) Write a C++ program that asks the user to enter a number of type int and then prints the sum of
all the digits of this number. Example: if the input is 2145, the output should be 12 (5+4+1+2).
6) Write the nested loops using for statement to display the following outputs:
a) Y
YY
YYY
YYYY
YYYYY
YYYYYY
b) Y Y
Y Y
Y
Y Y
Y Y
c) Y O O O O O
M Y O O O O
M M Y O O O
M M M Y O O
M M M M Y O
M M M M M Y