Call us at 0700-922-6559 or Click here

Write a program to multiply two numbers using pointers.

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.

  1. We start by including the standard input/output library stdio.h in the program.
  2. We declare five variables: a and b of type int to store the two numbers to be multiplied, p and q of type int* to store the pointers to the memory addresses of a and b, and mul of type int to store the product of a and b.
  3. We prompt the user to enter the first number a by printing the string “Enter integer a: ” to the console using printf.
  4. We read in the value of a entered by the user using the scanf function with %d as the format specifier, which tells scanf to expect an integer input. The value entered by the user is stored in the memory address of a using the & operator.
  5. We prompt the user to enter the second number b by printing the string “Enter integer b: ” to the console using printf.
  6. We read in the value of b entered by the user using scanf function, just like we did for a.
  7. We use the address-of operator & to assign the memory address of a to the pointer variable p and the memory address of b to the pointer variable q.
  8. We use the dereference operator * to access the values of a and b through the pointers p and q, and multiply them together using the * operator. The result is stored in the variable mul.
  9. We print the result of the multiplication using printf function along with the string “Multiplication of the numbers: “.
  10. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *