I need major help with For Loops

I'm having troubles with for loops, I'm completely new to them and very confused. How do I do this for loop correctly? If there's anything else wrong with my code, don't hesitate to tell me! Thanks.


This program should: Ask the user to enter a number (-999 to quit) no greater than 12, and calculate/print the product of the odd intergers starting at 1 until the user inputs -999.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//Ex2_44.cpp

#include <iostream.h>

           
   int main()
           
   
   {
   
      int input, counter, product, x;
      counter=0;
      product=1;
      input=1;
   
      while (input!=-999)
      {
         cout<<"How many odd integers would you like the product of? (-999 to quit) ";
         cin>>input;
      
         if (input>12)
         {
            cout<<"\nSorry, you can only enter a number between 1 and 12";
         }
         else if (input<=12)
         {
            cout<<"The product of ";
            for (x=1;input<=counter;x+=2)
            {
               product=(product*x);
               counter+=1;
               cout<< x << " , ";
            }
            cout<<" is: "<<product;
         }
      
         return 0;
      }
   }
A for loop will not work in this situation because you don't know how many times you want the loop to run. The user decides that. But for learning purposes, if you knew the loop would only run 12 times, a simple for loop would look like this:

1
2
3
4
for(int i=0;i<12;i++){
//do stuff

}


Lets break the header down.

1.) "int i=0" declare a variable i and set it equal to 0.
2.) "i<12" if i is less than 12 (if 0 is less than 12) continue to loop
3.) "i++" increment i by 1 each time the loop runs. Eventually i will become equal to 12 which will break the loop.


But again, that's just an example do NOT use that loop for your program. To do the desired result I would get rid of the for loop inside your while loop and check if the input is odd by using the modulus operator (%). For example:

1
2
3
if(input % 2 != 0){ //if you divide it by 2 and there is a remainder.
//input is odd
}


I would then advise storing input in a variable like you have such as "product". So you would have a line like

 
product *= input //multiples then stores the product in product (updates the value) 


So each time the while loop runs it will first detect if input is odd. If input is odd, it will multiply that odd value by the product of previous odd values and continue until the user enters -999
Topic archived. No new replies allowed.