Member Avatar
FrancisLazo

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

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.

Member Avatar
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.

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

Member Avatar
FrancisLazo

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

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

Member Avatar
FrancisLazo

Thanks bro!