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.hin the program. - We declare five variables:
aandbof typeintto store the two numbers to be multiplied,pandqof typeint*to store the pointers to the memory addresses ofaandb, andmulof typeintto store the product ofaandb. - We prompt the user to enter the first number
aby printing the string “Enter integer a: ” to the console usingprintf. - We read in the value of
aentered by the user using thescanffunction with%das the format specifier, which tellsscanfto expect an integer input. The value entered by the user is stored in the memory address ofausing the&operator. - We prompt the user to enter the second number
bby printing the string “Enter integer b: ” to the console usingprintf. - We read in the value of
bentered by the user usingscanffunction, just like we did fora. - We use the address-of operator
&to assign the memory address ofato the pointer variablepand the memory address ofbto the pointer variableq. - We use the dereference operator
*to access the values ofaandbthrough the pointerspandq, and multiply them together using the*operator. The result is stored in the variablemul. - We print the result of the multiplication using
printffunction along with the string “Multiplication of the numbers: “. - Finally, we return
0to 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.