In: Computer Science
Declare two pointers p and q capable of pointing to int
Make p point to y
Make q point to x
Assign 3 and 6 to x and y without mentioning x and y
Redirect p to point to the same location q points to (two ways)
Make q point to y
Swap the values of x and y without mentioning x and y
Declare two pointers p and q capable of pointing to int
Make p point to x
Make q point to y
Assign 3 to x and the same value plus one to y without mentioning y
Swap p and q
Make q point to y
Swap the values of p and q point to.
3, Declare three int: x,y and z
Declare two pointers p,q and r capable of pointing to int
Make p point to y.
Make q point to x.
Make r point to z.
Assign 5, 10 and 20 to x, y and z respectively without mentioning x ,y and z
Swap the values of x,y and z without mentioning x , y and z in the following way: x gets the value of z, y gets the previous value of x and z gets the previous value of y.
Swap their values.
5. Please, write a loop to print an array a with pointers. You can use a variable “size” for array size
Please write the code in C
1.
Code:
#include<stdio.h>
int main()
{
int x,y,*p,*q,temp;
/*Declaring the variables*/
p=&y;/*p points to y*/
q=&x;/*q points to x*/
*p=6;/*y=6*/
*q=3;/*x=3*/
temp=p;
p=q;
q=temp;
/*changing the pointers*/
printf("*p=%d\n",*p);
printf("*q=%d",*q);
/*Printing the poiters*/
}
Output:
2.
Code:
#include<stdio.h>
int main()
{
int x,y,*p,*q,temp;
/*Declaring the variables*/
p=&x;/*p points to x*/
q=&y;/*q points to y*/
*p=3;/*x=3*/
*q=*p+1;/*y=x+1*/
temp=p;
p=q;
q=temp;
/*interchanging the pointer references*/
printf("*p=%d\n",*p);
printf("*q=%d",*q);
/*Printintg the values*/
}
Output:
3.
Code:
#include<stdio.h>
int main()
{
int x,y,z,*p,*q,*r,temp,temp1;/*Declarig the
variables*/
p=&y;/*p points to y*/
q=&x;/*q points to x*/
r=&z;/*r points to z*/
*q=5;/*x=5*/
*p=10;/*y=10*/
*r=20;/*z=20*/
temp=*q;
*q=*r;/*x get the z value*/
temp1=*p;
*p=temp;/*y get the x previous value*/
*r=temp1;/*z get the y value*/
printf("x=%d\ny=%d\nz=%d",x,y,z);
/*Printing x y z */
}
Output:
4.
Code:
#include<stdio.h>
int main()
{
int *a=(int*) malloc(sizeof(int));
int *b=(int*) malloc(sizeof(int));
/*Dynamically alocaing 2 integers*/
int temp;
*a=5;
*b=10;
/*assigning values*/
temp=*a;
*a=*b;
*b=temp;
/*swapping*/
printf("*a=%d \n*b=%d",*a,*b);
/*printing the *a and *b*/
}
Output:
5.
Code:
#include<stdio.h>
main()
{
int a[5]={1,2,3,4,5};
int i,size=5;
/*Declaring the vriables*/
printf("Priting the array: ");
for(i=0;i<size;i++)
{
printf("%d ",*(a+i));
/*Printing the array*/
}
printf("\nPrinting elements in backword direction:
");
for(i=size-1;i>=0;i--)
{
printf("%d ",*(a+i));
/*printing in reverse order*/
}
}
Output: