C Program to calculate sum of two number using Pointer
Objective
Write a C program to calculate the sum of two numbers using Pointers.
Algorithm / Approach
- Declare two integers
aandb, and two pointer variables*pand*q. - Read values into
aandb. - Store the memory addresses of the variables into the pointers:
p = &a; q = &b;. - Calculate the sum by explicitly dereferencing the pointers:
sum = *p + *q;.
main.c
#include<stdio.h>
int main( ) {
int a, b, *p, *q, sum;
printf("Enter two number : ");
scanf("%d%d", &a, &b);
p = &a;
q = &b;
sum = *p + *q;
printf("SUM = %d\n",sum);
return 0;
}
Expected Output
Enter two number : 10 20 SUM = 30
Explanation of the Program
- A Pointer is a special variable that stores the physical memory address of another variable.
- The
&(address-of) operator retrieves the memory location. The*(dereference) operator tells the computer "go to the memory address stored in this pointer, and get the actual data inside it".
Complexity
Time Complexity
O(1)
Space Complexity
O(1)