Aug 12, 2020

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





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.





Program:


#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:







Share This:    Facebook Twitter

0 comments:

Post a Comment

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