w3resource

C Exercises: Add two numbers

C Pointer : Exercise-4 with Solution

Write a program in C to add two numbers using pointers.

Visual Presentation:

C Exercises: Pictorial: Add two numbers.

Sample Solution:

C Code:

#include <stdio.h>

int main() {
    int fno, sno, *ptr, *qtr, sum;  // Declare integer variables fno, sno, sum, and integer pointers ptr, qtr

    printf("\n\n Pointer : Add two numbers :\n");
    printf("--------------------------------\n");

    printf(" Input the first number : ");
    scanf("%d", &fno);  // Read the first number from the user

    printf(" Input the second number : ");
    scanf("%d", &sno);  // Read the second number from the user

    ptr = &fno;  // Assign the address of fno to the pointer ptr
    qtr = &sno;  // Assign the address of sno to the pointer qtr

    sum = *ptr + *qtr;  // Dereference ptr and qtr to get the values and calculate their sum

    printf(" The sum of the entered numbers is : %d\n\n", sum);  // Print the sum of the entered numbers

    return 0;
}

Sample Output:

 Pointer : Add two numbers :                                                                                  
--------------------------------                                                                              
 Input the first number : 5                                                                                   
 Input the second  number : 6                                                                                 
 The sum of the entered numbers is : 11

Flowchart:

Flowchart: Add two numbers

C Programming Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a program in C to demonstrate the use of &(address of) and *(value at address) operator.
Next: Write a program in C to add numbers using call by reference.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.