C program to add two numbers using pointers
Write a C program using pointers to add two numbers efficiently. Understand how pointers enable direct memory manipulation.
In C programming, pointers are a powerful tool that allows direct memory manipulation and efficient data handling. Here, we present a simple C program that adds two numbers using pointers, showcasing the practical application of pointers in basic arithmetic operations.
#include <stdio.h>
void main() {
int num1 = 5, num2 = 10;
int *ptr1, *ptr2, sum;
ptr1 = &num1;
ptr2 = &num2;
sum = *ptr1 + *ptr2;
printf("First number: %d\n", *ptr1);
printf("Second number: %d\n", *ptr2);
printf("Sum of the numbers: %d\n", sum);
}
Output
First number: 5
Second number: 10
Sum of the numbers: 15
- We declare two integer variables
num1
andnum2
and initialize them with the values 5 and 10, respectively. - Two integer pointers
ptr1
andptr2
are declared to store the memory addresses ofnum1
andnum2
. - We assign the addresses of
num1
andnum2
toptr1
andptr2
, respectively. - The program adds the values stored at the memory addresses pointed to by
ptr1
andptr2
and stores the result in thesum
variable. - Finally, the program prints the values of the two numbers and their sum.
By utilizing pointers, this C program efficiently adds two numbers, showcasing how pointers can facilitate direct memory manipulation and aid in performing basic arithmetic operations in C.