
153 views
Add two numbers using Pointer in C
To add two numbers using pointers in C, you can create two integer variables, obtain their addresses, and then perform the addition through pointer arithmetic. Here’s a simple example:
C
#include <stdio.h>
int main() {
int num1, num2, sum;
int *ptr1, *ptr2;
// Input two numbers
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
// Obtain addresses of the numbers
ptr1 = &num1;
ptr2 = &num2;
// Add the numbers using pointers
sum = *ptr1 + *ptr2;
// Display the result
printf("Sum of %d and %d is %d\n", *ptr1, *ptr2, sum);
return 0;
}
In this program:
- We declare two integer variables,
num1
andnum2
, to store the two numbers. - We declare two integer pointers,
ptr1
andptr2
, which will hold the addresses ofnum1
andnum2
, respectively. - We use
scanf
to input the two numbers. - We obtain the addresses of the numbers using the address-of operator (
&
) and assign them to the pointersptr1
andptr2
. - We add the numbers using pointer dereferencing (
*ptr1
and*ptr2
) and store the result in thesum
variable. - Finally, we display the sum of the two numbers.
This program demonstrates the use of pointers to perform addition. The values of num1
and num2
are accessed through the pointers ptr1
and ptr2
, and their sum is calculated and displayed.