Menu
×
Tutorials Ms Word Tutorial Ms Excel Tutorial Ms PowerPoint Tutorial C Language Tutorial C++ Tutorial C Sharp Tutorial Visual Basic Tutorial HTML Tutorial CSS Tutorial JavaScript Tutorial WordPress Tutorial
     ❯   

ADVERTISEMENT

Multiplication By Addition

This code performs integer multiplication using repeated addition and subtraction. It handles both positive and negative values of ‘a’ and ‘b, ensuring that the result is accurate.

#include<stdio.h>
main()
{
 int a,b,i,multiplication=0;
 printf("Enter 1st value: ");
 scanf("%d",&a);
 printf("Enter 2nd value: ");
 scanf("%d",&b);
 if(b<0)
 {
  a=a+b;
  b=a-b;
  a=a-b;
 }
 if(a>=0)
 {
      for(i=1;i<=a;i++)
     multiplication+=b;
 }
 if(a<0)
 {
  for(i=a;i<=-1;i++)
  multiplication-=b;
 }
 printf("Multiplication=%d\n",multiplication);
}
C Programming Examples

OUTPUT
Enter 1st value: 6
Enter 2nd value: 4
Multiplication=24
C Programming Examples

Explanation:

This C program calculates the product of two integers, ‘a’ and ‘b’, using repeated addition (for positive values of ‘a’) and repeated subtraction (for negative values of ‘a’). Here’s a step-by-step explanation of the code:

Header File:

  • The program includes the standard C library header <stdio.h>. This header is required for input and output operations.

Main Function:

  • The main function is the entry point of the program, where the execution begins.

Variable Declaration:

  • The program declares the following integer variables:
  • ‘a’ to store the first integer value.
  • ‘b’ to store the second integer value.
  • ‘i’ as a loop control variable.
  • ‘multiplication’ to store the result of the multiplication.

User Input:

  • The program prompts the user to enter two integer values ‘a’ and ‘b’ using printf and reads the input using scanf.

Adjustment for Negative ‘b’:

  • The code checks if ‘b’ is negative (b < 0).
  • If ‘b’ is negative, it performs a swap operation using simple addition and subtraction to ensure that ‘b’ is positive. This is done to simplify the multiplication calculation logic.

Multiplication Calculation:

  • The program uses conditional statements to handle different cases:
  • If ‘a’ is greater than or equal to 0, it enters a loop that runs ‘a’ times. In each iteration, ‘b’ is added to the ‘multiplication’ variable.
  • If ‘a’ is less than 0, it enters a loop that runs from ‘a’ to -1. In each iteration, ‘b’ is subtracted from the ‘multiplication’ variable. This is essentially repeated subtraction.
  • If ‘a’ is 0, the loop is not entered, and ‘multiplication’ remains 0.

Output:

  • After calculating the product of ‘a’ and ‘b’, the program uses printf to display the result with the message “Multiplication=”.

End of Program:

  • Once the result is printed, the program reaches the end of the main function, concluding the program’s execution.
Spread the love
Scroll to Top
Scroll to Top