Below is the program to multiply two numbers using pointers in C programming with step-by-step explanation.
#include<stdio.h>
int main()
{
int a, b, *p, *q, mul;
printf(“Enter integer a: “);
scanf(“%d”, &a);
printf(“Enter integer b: “);
scanf(” %d”, &b);
p = &a;
q = &b;
mul = *p * *q;
printf(“\nMultiplication of the numbers: %d”, mul);
return 0;
}
Output-
Enter integer a:2
Enter integer b:4
Multiplication of the numbers: 8
Below is a explanation of a program.
- We start by including the standard input/output library
stdio.h
in the program. - We declare five variables:
a
andb
of typeint
to store the two numbers to be multiplied,p
andq
of typeint*
to store the pointers to the memory addresses ofa
andb
, andmul
of typeint
to store the product ofa
andb
. - We prompt the user to enter the first number
a
by printing the string “Enter integer a: ” to the console usingprintf
. - We read in the value of
a
entered by the user using thescanf
function with%d
as the format specifier, which tellsscanf
to expect an integer input. The value entered by the user is stored in the memory address ofa
using the&
operator. - We prompt the user to enter the second number
b
by printing the string “Enter integer b: ” to the console usingprintf
. - We read in the value of
b
entered by the user usingscanf
function, just like we did fora
. - We use the address-of operator
&
to assign the memory address ofa
to the pointer variablep
and the memory address ofb
to the pointer variableq
. - We use the dereference operator
*
to access the values ofa
andb
through the pointersp
andq
, and multiply them together using the*
operator. The result is stored in the variablemul
. - We print the result of the multiplication using
printf
function along with the string “Multiplication of the numbers: “. - Finally, we return
0
to indicate that the program has completed successfully.
Once you have written the code, you can compile and run it using a C compiler, such as GCC, on your computer. The program will then display output on the screen when executed.
If you want to learn more about C programming, then join our course.