Programs on Pointers
1.Write a program
to read two integers using pointers and perform all arithmetic operations on
them.
#include<stdio.h>
int main()
{
int no1,no2;
int *ptr1,*ptr2;
int sum,sub,mult;
float div;
printf("Enter number1:\n");
scanf("%d",&no1);
printf("Enter number2:\n");
scanf("%d",&no2);
ptr1=&no1;//ptr1 stores address of no1
ptr2=&no2;//ptr2 stores address of no2
sum=(*ptr1) + (*ptr2);
sub=(*ptr1) - (*ptr2);
mult=(*ptr1) * (*ptr2);
div=(*ptr1) / (*ptr2);
printf("sum= %d\n",sum);
printf("subtraction= %d\n",sub);
printf("Multiplication= %d\n",mult);
printf("Division= %f\n",div);
return 0;
}
Output-
Q.2 Write a
program to accept an integer using pointer and check whether it is even or odd.
#include<stdio.h>
int
main()
{
int num;
int *pnum;
printf("Enter number: ");
scanf("%d",&num);
pnum= #
if(*pnum % 2==0)
printf("%d is even.\n", *pnum);
else
printf("%d is odd.\n", *pnum);
return 0;
}
Q.3 Program to
Find Maximum Between Two Numbers Using Pointers:
#include<stdio.h>
int main()
{
int no1,no2;
int *ptr1,*ptr2;
printf("Enter
first number:\n");
scanf("%d",&no1);
printf("Enter
second number:\n");
scanf("%d",&no2);
ptr1=&no1;/*ptr1 stores address of no1*/
ptr2=&no2;/*ptr2
stores address of no2*/
if(*ptr1>*ptr2)
{
printf("Maximum
number is %d",*ptr1);
}
else
{
printf("Maximum
number is %d",*ptr2);
}
return 0;
}
Q.4 Write a
program to interchange two numbers using pointers.
#include
<stdio.h>
int
main() {
int a, b, temp;
int *ptr1, *ptr2;
printf("Enter the value of a and b:
");
scanf("%d %d", &a, &b);
printf("\nBefore swapping a = %d and b
= %d", a, b);
// Assign the memory address of a and b to
*ptr1 and *ptr2
ptr1 = &a;
ptr2 = &b;
// Swap the values a and b
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
printf("\nAfter swapping a = %d and b
= %d", a, b);
return 0;
}
Comments
Post a Comment