954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

I'm confused with multiplication of numbers using addition

Hey there guys I need your help as I do not fully understand the program source code below. This program will multiply two numbers without using the multiplication sign (*). I am confused with the highlighted part, the for loop part. Here it is:

#include <iostream>
#include <string>

using namespace std;


double productOf(double first, double second)
{
       double product(0); 
       
       for (int i = 1; i <= second; i++)
       product = product + first;
       
      
       return product;
}

int main()
{
    int first;
    int second;
    
    cin >> first;
    cin >> second;
    cout << productOf(first,second);
    
     system("pause");
     
    return 0;
    
}


I do not understand the use of the i variable in that for loop. Can someone please explain to me how it works? Thanks in advance to those who will help. :)

francis25
Newbie Poster
18 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

Hello francis25,
consider a set {2,2,2,2,2,2,2}, to find the sum of all elements in the set, you would count the number of 2's and multiply it with 2. You can also add all the 2's instead of multiplying and that's what is done in the code you posted. Variable i is used in the for loop so that the element is added up to the number of times it occurs.

Arbus
Practically a Master Poster
615 posts since Dec 2010
Reputation Points: 45
Solved Threads: 31
 
Hello francis25, consider a set {2,2,2,2,2,2,2}, to find the sum of all elements in the set, you would count the number of 2's and multiply it with 2. You can also add all the 2's instead of multiplying and that's what is done in the code you posted. Variable i is used in the for loop so that the element is added up to the number of times it occurs.

Now it makes sense! So that's how it works. Thank you very much Arbus! :)

francis25
Newbie Poster
18 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

So the variable i makes the second number inputted repeat based on how many times the i incremented? Am I correct?

francis25
Newbie Poster
18 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

yes it repeats adding the number to itself(to variable product)several times.

Arbus
Practically a Master Poster
615 posts since Dec 2010
Reputation Points: 45
Solved Threads: 31
 

Thanks bro!

francis25
Newbie Poster
18 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: