Arithmetic operations on two numbers using pointers

C program to perform all arithmetic operations on two numbers using pointers

Program

#include<stdio.h>
#include<conio.h>
void main()
{
	int num1, num2;
    int *ptr1, *ptr2;
    int sum, diff, mul;
    float div;

    printf("Enter the first number\t:");
    scanf("%d",&num1);
    printf("Enter the second number\t:");
    scanf("%d",&num2);

    ptr1 = &num1;
    ptr2 = &num2;

    sum = *ptr1 + *ptr2;
    diff = *ptr1 - *ptr2;
    mul = *ptr1 * *ptr2;
    div = (float)*ptr1 / *ptr2;

    printf("\nSum = %d",sum);
    printf("\nDifference = %d",diff);
    printf("\nMultiplication = %d",mul);
    printf("\nDivision = %f",div);

    getch();
}

Output

Enter the first number  :9
Enter the second number :5

Sum = 14
Difference = 4
Multiplication = 45
Division = 1.800000

Explanation

In the above program, two variables 'num1' and 'num2' are taken, and two pointer variables '*ptr1' and '*ptr2' are also taken, ptr1 points to num1 and ptr2 points to num2 using the statements
ptr1 = &num1;
ptr2 = &num2;
ptr1 contains the address of variable num1 and ptr2 contains address of variable num2.

Let us consider, 9 and 5 as the first number and second number.
num1 = 9 and num2 = 5

*ptr1 means "value at the address contained in ptr1". ptr1 contains the address of num1. so, *ptr1 means "value at num1" which is the first number entered by the user i.e. 9
Similarly, *ptr2 = 5

sum = *ptr1 + *ptr2; sum = 9 + 5 = 14
diff = *ptr1 - *ptr2; diff = 9 - 5 = 4
mul = *ptr1 * *ptr2; mul = 9 * 5 = 45
div = (float)*ptr1 / *ptr2; div = 9 / 5 = 1.800000

Note that, always use proper spaces and separators between two different programming elements. As *ptr1 /*ptr2 will generate a compile time error.