for loop

Oct 25, 2008 at 2:49am
hello

im having trouble with getting my for loop to work. what it is supposed to do is display all the odd intergers from 1-13 and get the product of all of them.

here is what i have. it displays the number but i dont know how to get it to display the product. the product should be 135135.

http://pastebin.com/f1977ad3b


any help would be cool
Oct 25, 2008 at 3:11am
your code:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()

{
        int product = 1;

        cout << " the odd intergers from 1 to 13 are: " << endl << endl;
        for (int product = 1; product <= 13; product = product + 2)
			cout << product << endl << endl;
	cout << "The product of the odd integers from 1 through 13 is " << product << endl;
        return 0;

}   //end of main function


doesn't calculate the product at all, it just lists the odd integers. You use the variable name product which is probably confusing, because the way it is written, product actually stores the odd integers, not the actual product. You need a variable to store the running product total, something like:

1
2
3
4
5
6
7
8
9
  int odd_integer=1; 
   int total=1;
   cout << "the odd integers between 1 and 13 are: "; 
   for(odd_integer;odd_integer<=13;odd_integer=odd_integer+2)
      {
       total=total*odd_integer;
       cout << odd_integer<< endl;
      }
    cout << "The product is: " << total << endl;


notice that the total multiplies itself by the increased odd_integer each time that the loop runs. The odd integers are displayed each time, but the product isn't displayed until the loop is finished.
Last edited on Oct 25, 2008 at 3:13am
Oct 26, 2008 at 2:49pm
did you test that code?

because that doesnt work for me :(
Oct 26, 2008 at 3:07pm
What error do you get? that code should be fine
Oct 26, 2008 at 4:15pm
The code should:
- Be put in main a main function
- Have iostream included

The for loop should be:
for(odd_integer = 1; odd_integer <= 13; odd_integer += 2)
Last edited on Oct 26, 2008 at 4:16pm
Topic archived. No new replies allowed.