1. (Basic Pointers and Pointer Arithmetic) Write a C program that will do the fo
ID: 3761936 • Letter: 1
Question
1. (Basic Pointers and Pointer Arithmetic) Write a C program that will do the following:
a. Create two integer variables x and y, and an integer array z[5]
b. Set the variable x equal to 5, and the variable y equal to 10
c. Save the following values in the array: 1, 2, 4, 8, 16
d. Print to screen the address of each of the variables, x, y, and the start of the array z
e. Create a pointer named testPtr and point it to the variable x
f. Print to screen the value stored in variable x using only your pointer testPtr
g. Add six to the value stored in x using only your pointer testPtr
h. Print to screen the value stored in variable x using only your pointer testPtr
i. Test to see if the value stored in variable x is larger than y, using only the variable y and the testPtr. If it is, print to screen "x > y", otherwise print "y < x"
j. Now, change testPtr to Point to the first entry of the array z
k. Using only testPtr, use a counter and for loop to print all the value in the array (do not use the array).
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
//a.
int x,y,z[5];
//b.
x = 5;
y = 10;
//c.
z[0] = 1;
z[1] = 2;
z[2] = 4;
z[3] = 8;
z[4] = 16;
//d.
printf("Address of x = %d, y= %d, z = %d",&x,&y,&z[0]);
//e.
int *testPtr = &x;
//f.
printf("Value of x is : %d",*testPtr);
//g.
*testPtr = *testPtr+6;
//h.
printf("Value of x is : %d",*testPtr);
//i.
if(y>(*testPtr))
printf("y>x");
else
printf("y<x");
//j.
testPtr = &z[0];
//k.
for(int i=0;i<5;i++)
printf("Value at %d is %d ",i+1,*(testPtr+i));
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.