228k views
5 votes
What is the output of the following program? Assume code is correct. #include using namespace std; void ref(int r, int & s) { r++; s++; } int main() { int i=1, x=5, y=9; while (i<=y) { int j; for (j = 1; j <= y-x; j++) cout<<'a'; ref(y,x); cout<

1 Answer

3 votes

Answer:

Program output:

aaaa

aaa

aa

a

Step-by-step explanation:

Given the codes

  1. #include <iostream>
  2. using namespace std;
  3. void ref(int r, int & s) {
  4. r++; s++;
  5. }
  6. int main() {
  7. int i=1, x=5, y=9;
  8. while (i<=y) {
  9. int j;
  10. for (j = 1; j <= y-x; j++)
  11. cout<<'a';
  12. ref(y,x);
  13. cout<<endl;
  14. i = i+1;
  15. }
  16. return 0;
  17. }

In the main program there are three variables i, x and y with their respective values 1, 5 and 9 (Line 9).

The while loop will run for 9 times and in the loop there is another for loop that will run for y-x times. In the for loop, a single "a" will be printed in every iteration. There will be four "a" printed in the first while loop interation as y-x equal to 4.

The calling of function ref won't change the y value as it is passed by value but x will be incremented by one as it is passed by reference (Line 14). Every subsequent while loop will make y-x less than one from the previous iteration and this is the reason the second line of a string consist only triple a. After completion of while loop, a small triangle shape of a letter is generated.

User Hien Nguyen
by
6.1k points