Ex: Write a C program to add two numbers using pointers. How to write C program to add two numbers using pointers. C program to add two numbers using pointers.
Input from user:
Enter Number1: 10
Enter Number2: 20
Expected output:
Sum= 30
Step by step logic of the given program:
1. Accept input (numbers) from user.
2. Store address of no1 in pointer variable ptr1 and store address of no2 in variable ptr2 using reference operator (&):
ptr1=&no1;
ptr2=&no2;
3. After that add two numbers using dereference operator(*):
sum=*ptr1+*ptr2;
4. Last print sum on the output screen.
Program to Add Two Numbers using Pointers:
#include<stdio.h>
int main()
{
int no1,no2,sum;
int *ptr1,*ptr2;
printf("Enter number1:\n");
scanf("%d",&no1);
printf("Enter number2:\n");
scanf("%d",&no2);
ptr1=&no1;// it stores address of no1
ptr2=&no2;// it stores address of no2
sum=*ptr1+*ptr2;// it adds values at address no1 & no2
printf("Sum= %d",sum);
return 0;
}
Above program shows the following output:
No comments:
Post a Comment
If you have any doubts, please discuss here...👇