In this article, we will learn how we can add two numbers using pointers in C programming.
The program takes two integer inputs from the user and prints their sum as a result.
Sample Input:
Enter the first number: 10
Enter the second number: 20
Output:
The sum of the two numbers is: 30
Before we dive into the explanation of the actual program, let’s first have a look at pointers in C language.
In C programming language, a pointer is used to store the memory address of a variable. It is declared by placing an asterisk symbol(*
) before the variable name, eg. *myVar
.
To store the address of a variable in a pointer, we place an ampersand(&
) symbol before the variable. For example:
int a = 10, *myVar; // Store the address of variable a in pointer myVar myVar = &a;
In the above example, the pointer myVar
will store the memory address of the variable a
.
Now, if you want to access the value that the pointer myVar
is pointing to, you can place an asterisk(*
) symbol before it.
For example, if you try to print the value of myVar
and *myVar
, you will find that myVar
prints the memory address of the variable a
whereas *myVar
prints the value of the variable a
.
int a = 10, *myVar; // Store the address of variable a in pointer myVar myVar = &a; printf("%d ", myVar); // 6487572 printf("%d", *myVar); // 10
We can use the above concept to add two numbers using pointers.
You need to simply follow the below steps to add two numbers using C pointers:
- Create two integer variables
a
&b
to take input from the user. Also create two pointer variables*p
and*q
which will hold the addresses ofa
andb
. - Take the inputs from the user using the scanf() function and store them in variables
a
andb
. - Store the memory address of the variable a in pointer p and the memory address of the variable
b
in pointerq
. - Get the sum of the two numbers by dereferencing pointers p and q i.e.
*p + *q
and store the result in thesum
variable. - Print the result stored in the
sum
variable using the printf() function.
Here is the implementation of the above steps:
// C program to add two numbers using pointers #include <stdio.h> int main(){ // Declare the variables and pointers int a, b, *p, *q, sum; // Get the first number printf("Enter the first number: "); scanf("%d", &a); // Get the second number printf("Enter the second number: "); scanf("%d", &b); p = &a; // Store address of a in pointer p q = &b; // Store address of b in pointer q // Get the sum by dereferencing pointers p & q sum = *p + *q; // Print the result printf("The sum of the two numbers is: %d", sum); return 0; }
Output:
Enter the first number: 10 Enter the second number: 20 The sum of the two numbers is: 30
Thanks for reading.