Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to calculate sum of two number using Pointer

C Code Example — Function Programs

ADVERTISEMENT

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

  1. Declare two integers a and b, and two pointer variables *p and *q.
  2. Read values into a and b.
  3. Store the memory addresses of the variables into the pointers: p = &a; q = &b;.
  4. 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)
ADVERTISEMENT