Aim: 9.1 Write a program to print address of variable using pointer.
Code:
#include <stdio.h>
int main()
{
int a;
int *pt;
printf("Pointer Example Program : Print Pointer Address\n");
a = 10;
pt = &a;
printf("\n[a ]:Value of A = %d", a);
printf("\n[*pt]:Value of A = %d", *pt);
printf("\n[&a ]:Address of A = %p", &a);
printf("\n[pt ]:Address of A = %p", pt);
printf("\n[&pt]:Address of pt = %p", &pt);
printf("\n[pt ]:Value of pt = %p", pt);
return 0;
}
Output screenshot:
Aim: 9.2 Write a C program to swap the two values using pointers.
Code:
#include <stdio.h>
void swap(int *x,int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
}
int main()
{
int num1,num2;
printf("Enter value of num1 : ");
scanf("%d",&num1);
printf("Enter value of num2 : ");
scanf("%d",&num2);
printf("Before Swapping : num1 is : %d, num2 is : %d\n",num1,num2);
swap(&num1,&num2);
printf("After Swapping : num1 is : %d, num2 is : %d\n",num1,num2);
return 0;
}
Output screenshot:
Aim: 9.3 Write a C program to print the address of character and the character of string using pointer.
Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[]="Hello";
char c='A';
int i;
char *ptr_str[30];
char *ptr_c=&c;
for(i=0;i<strlen(str);i++)
ptr_str[i]=&str[i];
printf("\nString Entered is : %s\nAddress of string :",str);
for(i=0;i<strlen(str);i++)
printf("\n%c's address : %p",str[i],ptr_str[i]);
printf("\nValue of c = %c\nAddress of c = %p",c,ptr_c);
getch();
}
Output screenshot:
Aim: 9.4 Write a program to access elements using pointer.
Code:
#include <stdio.h>
int main()
{
int data[5];
printf("Enter elements : \n");
for (int i = 0; i < 5; ++i)
scanf("%d", data + i);
printf("You entered : \n");
for (int i = 0; i < 5; ++i)
printf("%d\n", *(data + i));
return 0;
}
Output screenshot:
Aim: 9.5 Write a program for sorting using pointer.
Code:
#include <stdio.h>
void sort(int n, int* ptr)
{
int i, j, t;
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (*(ptr + j) < *(ptr + i))
{
t = *(ptr + i);
*(ptr + i) = *(ptr + j);
*(ptr + j) = t;
}
}
}
for (i = 0; i < n; i++)
printf("%d ", *(ptr + i));
}
int main()
{
int n = 5;
int arr[] = { 0,1,2,3,4};
sort(n, arr);
return 0;
}
Output screenshot:
No comments:
Post a Comment
If you have any doubts or suggestions, Please let me know