In: Computer Science
What is the output from each of the following segments of C++ code? Record the output after the “Answer” prompt at the end of each program fragment. Assume all variables have been suitably declared. (Each problem is worth 3 points.)
1. for (int j = 8; j > 3; j -= 2)
cout << setw(5) << j;
Answer:
2. int sum = 5;
for (int k = -4; k <= 1; k++)
sum = sum + k;
cout << sum;
Answer:
3. for (int k = 2; k < 5; k++)
{
for (int j = 6; j < 9; j++)
cout << setw(4) << (k + j) << " ";
cout << endl;
}
Answer:
int sum = 0;
int a = 3;
while (a < 6)
{
for (int k = a; k < 6; k++)
sum = sum + k;
a = a + 1;
}
cout << sum << endl;
Answer:
5. int k = 0;
for (k = 1; k <= 1; k++)
{
for (int counter = 1; counter <= 1; counter--)
cout << counter << endl;
cout << " " << endl;
}
cout << k << endl;
Answer:
int k = 0;
for (k = 10; k < 1; k++)
{
for (int counter = 1; counter <= 10; counter++)
cout << setw(5) << counter;
cout << endl;
}
cout << k << endl;
Answer:
Assuming all variables have been properly declared and all source code has been properly setup in a compiler, what is the output from each of the following fragments of C++ code? Record the output after the “Answer” prompt at the end of each program fragment. (2 points each)
a. int answer = 6;
int number = 16;
number = number + ++answer;
cout << answer << " " << number;
//Answer:
b. int answer = 16;
int number = 6;
number = number + answer--;
cout << answer << " " << number;
//Answer:
ANSWER :
1. OUTPUT :
8 6 4
explaination :
Here setw() funtion in used to add width in the outptut. So setw(5) specifies the spaces between the output when it is printed
2. OUTPUT :
-4
explaination : In the for loop k is iterated from -4 to 1 untill condition is met it is incremented.
3. OUTPUT :
8 9 10
9 10 11
10 11 12
explaination : Here there are two for loops first loop runs from 2 to 5 and 2nd loop runs from 6 to 9. In the second for loop there is print statement which returns the width of 4 units and k + j value
4. OUTPUT :
26
explaination : Here there is a while loop where a=3 < 6 loop runs untill condition is met. and inside while loop there is for loop runs from k = a to 6 and returns sum of the loop
5. OUTPUT :
returns garbage value and the loop runs for infinite turns
6. OUTPUT :
10
explaination : Here the for loop is not compiled because the condition in the for loop doesnot satisfy so in the for loop k is assigned to 10 so the final output is 10
a. OUTPUT :
7 23
explaination : Here the answer = 6 and number = 16
number = number + ++answer
here ++answer is a preincrement so first the ++answer is incremented and the following statement is evaluated so solution becomes answer = 7 and number = 23
b. OUTPUT :
15 22
explaination : Here answer = 16 and number = 6
number = number + answer--
whre answer-- is a post drecement so the expression is evaluated first and answer value is decremented. So the solution becomes answer = 15 number = 22