0

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
5 Years
Discussion Span
Last Post by FrancisLazo
Featured Replies
  • 1

    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 … Read More

  • 1

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

1

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

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.

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

0

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

1

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

0

Thanks bro!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.