For Loop (Help Needed)

Write a for loop that print out the multiples of 3 up through 39, separated by a blank space.
3 6 9 12 15 18 21 24 27 3
33 36 39
 
  For ( 
closed account (48T7M4Gy)
http://www.cplusplus.com/doc/tutorial/control/

Scroll down to for loop section with sample program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
        // initialize int "multiplesOf3" to 3 and increment by 3 until 39

        for (int multiplesOf3 = 3; multiplesOf3 != 42; multiplesOf3 += 3)
        {
                // print current value of "multiplesOf3"
                // flush stream so it is printed

                std::cout << multiplesOf3 << ' ' << std::flush;
        }

        std::cin.get(); // pause

        return 0;
}
Last edited on
View link to see the details of the loop http://www.cplusplus.com/doc/tutorial/control/

1
2
3
4
5
6
7
8
#include <iostream>

int main(){
for(int i = 3; i <= 39; i+=3){
          std::cout << i << " ";
}
return 0;
}

Last edited on
For loops are most often used to create bits of code that will run a specific number of times. for instance, if you want to count up from 0 to 5 you could use the code below.

1
2
3
4
5
6
7
int mail()
{
     for (x=0; x<6; x++)
             {
                    cout << x << endl;
              }
}


all this code does is enter the for loop. in the for loop it creates a variable (called x) and sets it to 0. Than it checks if x is less than 6 (setting an exit point for the loop). and finaly if x is less than 6 will run the code (cout << x << endl;) and increase x by 1.

Knowing this you can write your own code to count by 3 by changing the x++ to x+=3.
Topic archived. No new replies allowed.