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. :)

2
Contributors
5
Replies
7
Views
7 Years
Discussion Span
Last Post by FrancisLazo

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.

Edited by Arbus: n/a

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! :)

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

Edited by FrancisLazo: n/a

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

Thanks bro!