# Simple Calculator Program in C Using Pointer

## Introduction

In this post, I am going to explain how to write a simple calculator program in c using a pointer. I am saying simple calculator because it will produce results of addition, subtraction, multiplication and division only. But the interesting thing is that we are writing this program using a pointer.

For those who don’t know what is pointer, so let me tell you in short. The pointer is a variable which stores the address of another variable.

Before writing a program of simple calculator in c using pointer, let’s see the expected output first.

### Expected Output

As you can see in the above expected output, we are showing the user to enter his or her choice. After entering his choice, he or she will get another message to enter any two numbers. According to his choice and two numbers, he or she will get the respective result.

Now let us see the actual program for this.

### Simple Calculator Program in C Using Pointer

``````#include<stdio.h>
#include<stdlib.h>
int main()
{
int a,b;
int *p1,*p2;
char ch;
p1=&a;
p2=&b;
printf("Select the Operation\n");
printf("Type - for Subtraction\n");
printf("Type * for Multiplication\n");
printf("Type / for Division\n");
scanf("%c",&ch);
printf("Enter any two numbers\n");
scanf("%d%d",&a,&b);
switch(ch)
{
case '+':
printf("%d + %d = %d",a,b,(*p1+*p2));
break;
case '-':
printf("%d - %d = %d",a,b,(*p1-*p2));
break;
case '*':
printf("%d * %d = %d",a,b,(*p1**p2));
break;
case '/':
if(*p2==0)
{
printf("Sorry, You can not divide a number by 0");
return 0;
}
printf("%d / %d = %0.2f",a,b,(*p1/(float)*p2));
break;
default:
printf("Sorry, Invalid Choice");
}
return 0;
}
``````

### Explanation

In the above program, there are five variables. The variables p1 and p2 pointer variables. The variable p1 will store the address of a and p2 will store the address of b. We are doing this using the statement p1=&a and p2=&b.

Also Read: C Program to Remove Zeros from a number

Variables a and b will store the numbers and we will perform the operations of addition, subtraction, multiplication and division on these numbers. But, in this program, we will not do this directly. That means instead of a+b, we will write *p1+*p2. Why we are doing this?

We are writing a program in c for a simple calculator using a pointer. The value of a is equivalent to *p1 and b is equivalent to *p2. Therefore, instead of a and b, we can directly use *p1 and *p2 directly.

Also Read: The while loop in C Programming

We are using switch case in this program. Whenever we write a program where there is a choice, then we can use switch case statement.

I hope you have understood this program. If you any difficulty regarding this program, then please let me know.

Thank you.