C Program to Perform All Arithmetic Operations using Pointers

Ex: Write a C program to perform all arithmetic operations using pointers. How to write a C program to perform all arithmetic operations using pointers. C program to perform all arithmetic operations using pointers.


Input from user:

Enter Number1: 20

Enter Number2: 10


Expected output:

Sum=30

Subtraction=10

Multiplication=200

Division=2.0000


Before learning how to write a C program to perform all arithmetic operations we need to know what is arithmetic operators means.


  What is Arithmetic Operators:

Arithmetic Operators are the operators which are used to perform various mathematical operations such as addition, subtraction, division, multiplication etc.

For Examples: 

1. Plus (+): is used for addition like 5 + 5 = 10, 35 + 35 = 70, 10 + 13 + 25 = 48  etc.

2. Minus Operator (-): is used for subtract one number from another number like 23 - 8 = 15, 65 - 25 = 40.

3. Multiplication Operator (*) : is represented as an asterisk (*) symbol and it returns product of  given numbers like 5 * 5 = 25, 7 * 12 = 84 etc.

4. Division Operator (/) : is denoted by  forward slash (/)  symbol and it divides first number by the second number like 35 / 5 = 7.


5. Modulus Operator (%) : is denoted by percentage (%) symbol and it returns remainder. for ex: 25 / 5 = 0, 45 / 6 = 3 etc.


In below example we have performed addition, subtraction, multiplication and division operations using pointers in C. 


  Quick Links:


  Step by step logic of the given program:


1. Accept two numbers from user store it in variable say no1 and no2.

2. Store address of no1 in pointer variable ptr1 and store address of no2 in variable ptr2 using reference operator (&):

ptr1=&no1;

ptr2=&no2;

3. After that calculate addition, subtraction, multiplication and division using dereference operator(*):

sum=(*ptr1) + (*ptr2);

sub=(*ptr1) - (*ptr2);

mult=(*ptr1) * (*ptr2);

div=(*ptr1) / (*ptr2);

4. Last print sum, sub, mult and div on the output screen.



  C Program to Perform All Arithmetic Operations using Pointers:

#include<stdio.h>

int main()

{

int no1,no2;

int *ptr1,*ptr2;

        int sum,sub,mult;

        float div;   

    printf("Enter number1:\n");

    scanf("%d",&no1);

    printf("Enter number2:\n");

    scanf("%d",&no2);

    

    ptr1=&no1;//ptr1 stores address of no1

    ptr2=&no2;//ptr2 stores address of no2

    

    sum=(*ptr1) + (*ptr2);

    sub=(*ptr1) - (*ptr2);

    mult=(*ptr1) * (*ptr2);

    div=(*ptr1) / (*ptr2);

    

    printf("sum= %d\n",sum);

    printf("subtraction= %d\n",sub);

    printf("Multiplication= %d\n",mult);

    printf("Division= %f\n",div);


    return 0;

}



Above program shows the following output:


C Program to Perform All Arithmetic Operations using Pointers



Feel free to Share your thoughts below in the comment sections.


    You May Also Like:

No comments:

Post a Comment

If you have any doubts, please discuss here...👇