You are here

C program to add two numbers using pointers

C program for addition of two numbers using pointers. In our program, we have two integer variables x and y and two pointer variables p and q. Firstly we assign the addresses of x and y to p and q respectively and then assign the sum of x and y to the variable sum. Note that & is the address of operator and * is value at address operator.

C programming code

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.    int first, second, *p, *q, sum;
  6.  
  7.    printf("Enter two integers to add\n");
  8.    scanf("%d%d", &first, &second);
  9.  
  10.    p = &first;
  11.    q = &second;
  12.  
  13.    sum = *p + *q;
  14.  
  15.    printf("Sum of the numbers = %d\n", sum);
  16.  
  17.    return 0;
  18. }

Download Add integers using pointers program.

Output of program:
Add numbers using pointers

C program to add numbers using call by reference

  1. #include <stdio.h>
  2.  
  3. long add(long *, long *);
  4.  
  5. int main()
  6. {
  7.    long first, second, *p, *q, sum;
  8.  
  9.    printf("Input two integers to add\n");
  10.    scanf("%ld%ld", &first, &second);
  11.  
  12.    sum = add(&first, &second);
  13.  
  14.    printf("(%ld) + (%ld) = (%ld)\n", first, second, sum);
  15.  
  16.    return 0;
  17. }
  18.  
  19. long add(long *x, long *y) {
  20.    long sum;
  21.    
  22.    sum = *x + *y;
  23.    
  24.    return sum;
  25. }