This blog is under construction

Sunday 21 July 2013

C program to add two numbers using pointers

Write a C program to add two numbers using pointers.


  #include <stdio.h>

  /* adds given two numbers and stores the result in res */
  void add(int *n1, int *n2, int *res) {
        *res = *n1 + *n2;
        return;
  }

  int main() {
        int num1, num2, res;

        /* get the first input from the user */
        printf("Enter your first input:");
        scanf("%d", &num1);

        /* get the second input from the user */
        printf("Enter your second input:");
        scanf("%d", &num2);

        /* finds the sum of num1 and num2 and stores result in res */
        add(&num1, &num2, &res);

        /* print the result */
        printf("Sum of %d and %d is %d\n", num1, num2, res);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first input:10
  Enter your second input:20 
  Sum of 10 and 20 is 30


No comments:

Post a Comment