Write a C program to take input of two numbers from user and perform arithmetic operations using pointer. How to add, subtract, multiply, and divide of two numbers using pointer in C.
Required knowledge:
Step by step logic to write code for performing arithmetic operations using pointer
- Declare required variables like n1, n2, sum, sub, mult, div and two pointer variables *p and *q;
- Store the address of n1 and n2 in pointers p and q like this: p = &n1 and q = &n2
- Read the value sorted at p and q form user using scanf() function (Note: p is pointing to n1 and q is pointing to n2)
- Perform all arithmetic operations like below:
- At last print result of all arithmetic operations using pointer
/*Performing arithmetic operations*/ sum = p + q; sub = p - q; mult = p * q; div = p / q;
/*C program to perform arithmetic operations using pointer*/
#include <stdio.h>
int main(){
int n1, n2, sum, sub, mult, div; / / Declaration of normal variables
int *p, *q; / /Declaration of pointer variables
/* storing address of var in pointer variables
* (or can say initialization of pointers)*/
p = &n1;
q = &n2;
/* Taking n1 and n2 as input from user */
printf("Enter two numbers: ");
scanf("%d%d", p, q);
/*Performing arithmetic operations*/
sum = p + q;
sub = p - q;
mult = p * q;
div = p / q;
printf("Sum = %d\n", sum);
printf("Difference s = %d\n", sub);
printf("Multiplication = %d\n", mult);
printf("Division = %d\n", div);
return 0;
}
Address of (&) operator: When prefix address of & operator with any variable gives the address of that variable. For example: &n1 give the address of n1.
Indirection operator (*): Also known as dereference operator. When * operator prefix with pointer variable give the value of that variable to which pointer is pointing to. For example: p = &n1 will give the whatever value of n1 will be.
Output
Input:
Enter two numbers: 10
5
Output:
Sum = 15
Differences = 5
Multiplication = 50
Division = 2
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.