C++ PROGRAMMING Write a program that performs the following tasks. 1) Declare an
ID: 3761736 • Letter: C
Question
C++ PROGRAMMING
Write a program that performs the following tasks.
1) Declare an int pointer variable ptrA. Use new to make ptrA point to a dynamic int variable.
Store integer 33 in the dynamic variable. Output the address of ptrA, the value of ptrA, and the value
pointed to by ptrA.
2) Double the value stored in the above dynamic variable. Output the new value.
3) Declare an int pointer variable ptrB. Ask the user to enter an integer as the size of a dynamic array
and store it in an int variable size. Create a dynamic int array of that size and store its base address in
ptrB.
4) Use a for loop to input data into the dynamic array from the standard input device.
5) Write a function printArray to output the contents of an array. Call printArray function to
output the above dynamic array. The function has two formal parameters: an int pointer variable that
points to an array and an int variable representing the size of the array.
6) Update the contents of the above array by adding the value of the last element to each element of the
array. Output the new values.
7) Challenge: Ask user to enter an integer and append it to the end of the dynamic array. Output the new
array.
Hint: You can’t simply store the new value in ptr[size] because it is an out-of-bound error. The
right approach is: create a new dynamic array of size+1, copy the old array to the new array and then
store the new value in the last element of the new array.
8) Destroy all dynamic variables in this lab.
Explanation / Answer
#include<iostream>
using namespace std;
void printArray(int *arr, int size) {
cout<<"Array data: ";
for (int i=0; i<size; i++) {
cout<<arr[i]<<", ";
}
cout<<" ";
}
int main() {
int *ptrA = new int(33);
cout<<"Address of ptrA: "<<&ptrA<<" ";
cout<<"Value of ptrA: "<<ptrA<<" ";
cout<<"Value pointed to ptrA: "<<*ptrA<<" ";
*ptrA *= 2;
cout<<"Value after double: "<<*ptrA<<" ";
int *ptrB, size;
cout<<"Enter size: ";
cin>>size;
ptrB = new int[size];
for (int i=0; i<size; i++) {
cout<<"Enter value at "<<(i+1)<<": ";
cin>>ptrB[i];
}
printArray(ptrB, size);
for (int i=0; i<size; i++) {
ptrB[i] += ptrB[size-1];
}
printArray(ptrB, size);
int in;
cout<<"Enter an integer: ";
cin>>in;
int *temp = new int[size+1];
for (int i=0; i<size; i++) {
temp[i] = ptrB[i];
}
delete ptrB;
ptrB=temp;
ptrB[size++] = in;
printArray(ptrB, size);
delete ptrA;
delete ptrB;
cout<<" ";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.