Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

2. Consider the following C++ program: 1. #include <iostream> 2. using namespace

ID: 3771056 • Letter: 2

Question

2. Consider the following C++ program:

1. #include <iostream>

2. using namespace std;

3. 4. int main()

5. {

6. int *ptrA, *ptrB, *ptrTmp;

7. int a(16), b(22), tmp;

8.

9. ptrA = &a;

10. ptrB = &b;

11. cout << *ptrA << " " << *ptrB << " " << a << " " << b << endl;

12.

13. tmp = a;

14. a = b;

15. b = tmp;

16.

17. cout << *ptrA << " " << *ptrB << " " << a << " " << b << endl;

18.

19. ptrTmp = ptrA;

20. ptrA = ptrB;

21. ptrB = ptrTmp;

22.

23. cout << *ptrA << " " << *ptrB << " " << a << " " << b << endl;

24.

25. return 0;

26. }

(a) Show exactly what will be printed to the screen from the execution of line 11.

(b) Show exactly what will be printed to the screen from the execution of line 17.

(c) Show exactly what will be printed to the screen from the execution of line 23.

please tell why, im not sure what the * and & symbols do

Explanation / Answer

Execution of line 11 prints : 16 22 16 22
Execution of line 17 prints : 22 16 22 16
Execution of line 23 prints : 16 22 22 16

*ptrA , *ptrB , *ptrTmp are pointers.
Pointers can be used to store memory addresses.

& is a reference operator. It is used to get memory address of a variable.
Ex: int a=5;
Variable "a" contains 5.
now we can get memory address in which 5 is stored by using "&a".

1) int *ptrA,*ptrB,*ptrTmp;// defined three pointers

2)int a(16),b(22),tmp;//varible and set to a value. a is set to 16 and b is set to 22. tmp is defined but not set(default value is 0).

3) ptrA=&a;//pointer ptrA stores memory address of a.
4) ptrB=&b;//pointer ptrB stores memory address of b.

"value from the pointer accessed as *ptrA".
cout<<(*ptrA)<<endl;//ptrA is memory address and *ptrA is value in the memory address.i.e *ptrA prints 16 and *ptrB prints 22.
This prints the value in the memory address ptrA
i.e 16 because ptrA stores memory address of a.
similarly ptrB.

cout << *ptrA << " " << *ptrB << " " << a << " " << b << endl;
This prints 16 22 16 22


5)tmp = a;
a = b;
b = tmp;
//This part swaps a and b.
means now a contains 22 and b contains 16
as ptrA contain memory address of a and a contain 22 (*ptrA prints 22)
(*ptrB prints 16).

cout << *ptrA << " " << *ptrB << " " << a << " " << b << endl;

therefore this prints 22 16 22 16

ptrTmp = ptrA;
ptrA = ptrB;
ptrB = ptrTmp;

This part of code swaps pointers.
Now ptrA points to memory address of b and ptr B points to memory address of a.
(we know a contains 22 and b contains 16)
*ptrA prints value in the memory address of b and *ptrB prints value stored in the memory address of a.


cout << *ptrA << " " << *ptrB << " " << a << " " << b << endl;
This prints 16 22 16 22