codescracker
c

C Program to Add two Numbers using Pointer



« Previous Program Next Program »

In this article, you will learn and get code about adding of two numbers in C using pointer. So the question is, Write a program in C that adds any two number entered by user (at run-time) using pointer.

Here we will only discuss about brief explanation of pointer while adding any two number in C. To learn Pointer in detail, then refer to Pointer in C tutorial. Let's take a look at the program first, then will explain it further.

Addition using Pointer in C

To add two numbers using pointer in C programming, you have to ask from user to enter any two number, then perform the operation using pointer as shown here in the following program:

#include<stdio.h>
#include<conio.h>
int main()
{
    int num1, num2, sum;
    int *ptr1, *ptr2;
    printf("Enter any two Number: ");
    scanf("%d%d", &num1, &num2);
    ptr1 = &num1;
    ptr2 = &num2;
    sum = *ptr1 + *ptr2;
    printf("\nSum of %d and %d is %d", *ptr1, *ptr2, sum);
    getch();
    return 0;
}

This program was written under Code::Blocks IDE. Here is the initial snapshot of sample run:

c program to add two numbers using pointer

Now supply any two number as input say 10 and 20 and press ENTER key to see the output as shown here in the snapshot given below:

add two numbers using pointer c

In above program, there are two important operators. The & (ampersand) and * (star) operator. The & is called as address of operator, and * is called as value at address operator.

Program Explained

Here we have initialized the address of first number to first pointer and the address of second number to second pointer, using address of (&) operator. And then, we have added the two number using value at address (*) operator, and initialized it to the variable sum. Finally printed value of sum as addition result.

Here is another program, that provides you the full understanding about pointer after watching its output carefully. Let's take a look at the program:

#include<stdio.h>
#include<conio.h>
int main()
{
    int num1, num2, sum;
    int *ptr1, *ptr2;
    printf("Enter any two Number: ");
    scanf("%d%d", &num1, &num2);
    printf("\nAddress of %d is %p", num1, &num1);
    printf("\nAddress of %d is %p", num2, &num2);
    ptr1 = &num1;
    ptr2 = &num2;
    printf("\n\nptr1 = %p", ptr1);
    printf("\nptr2 = %p", ptr2);
    printf("\n\nValue at %p is %d", ptr1, *ptr1);
    printf("\nValue at %p is %d", ptr2, *ptr2);
    sum = *ptr1 + *ptr2;
    printf("\n\nSum of %d and %d is %d", *ptr1, *ptr2, sum);
    getch();
    return 0;
}

The output of above program is shown in the snapshot given below:

c add two number using pointer

The format specifier %p is used for the standard notation of memory's address.

Same Program in Other Languages

C Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker