C Program To Add Two Numbers using Pointers

Lets write a C program to add 2 numbers using pointer and function.

In this video tutorial we will show both ways of adding 2 numbers using pointers: 1. Using function 2. Without using function.

Related Read:
Basics of Pointers In C Programming Language
Function / Methods In C Programming Language

Video Tutorial: C Program To Add Two Numbers using Pointers


[youtube https://www.youtube.com/watch?v=0wBPwxsr6-U]

YouTube Link: https://www.youtube.com/watch?v=0wBPwxsr6-U [Watch the Video In Full Screen.]


Source Code: C Program To Add Two Numbers using Pointers and Without using Function

#include<stdio.h>

int main()
{
    int a, b, c, *ptr1, *ptr2;

    ptr1 = &a;
    ptr2 = &b;

    printf("Enter 2 numbers\n");
    scanf("%d%d", &a, &b);

    c = *ptr1 + *ptr2;

    printf("Using *ptr1 + *ptr2 : %d + %d = %d\n", a, b, c);

    c = *(&a) + *(&b);

    printf("Using  *(&a) + *(&b) : %d + %d = %d\n", a, b, c);

    return 0;
}

Output:
Enter 2 numbers
25
25
Using *ptr1 + *ptr2 : 25 + 25 = 50
Using (&a) + *(&b) : 25 + 25 = 50

Logic To Add Two Numbers using Pointers

Here we are storing the address of variable a in pointer variable ptr1 and address of variable b in pointer variable ptr2.

We know that any address preceded by * would fetch the value present at that address. So we use following code to get the addition of 2 numbers result using pointers.

c = *ptr1 + *ptr2;

Source Code: C Program To Add Two Numbers using Pointer and Function

#include<stdio.h>

void addition(int, int, int*);

int main()
{
    int a, b, c;

    printf("Enter 2 numbers\n");
    scanf("%d%d", &a, &b);

    addition(a, b, &c);

    printf("%d + %d = %d\n", a, b, c);

    return 0;
}

void addition(int x, int y, int *z)
{
    *z = x + y;
}

Output:
Enter 2 numbers
10
40
10 + 40 = 50

Logic To Add Two Numbers using Pointers and Function

We ask the user to enter 2 numbers and store it inside address of variables a and b. Next we pass the values of a and b and address of variable c to a function called addition(). And then print the result in main method itself.

The motive is to change the value present at address of variable c. That way we can print the result directly inside main method itself, without our function addition() returning any value back to calling function(main()).

Inside addition() method, we add the values passed in first 2 arguments and then store the result back in the address location sent to addition() function as third argument. Function addition() doesn’t return any value, so it has void as its return type.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert