# for loop that will repeat the number of times the user wants.

This topic is 1835 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

How do i write a for loop that will repeat the number of times the user wants it too when asked by the console?

##### Share on other sites

It would be nice to know what language you're using.

I'll assume C++:

#include <iostream>

void main() {
int repeat;
std::cin >> repeat;
std::cout << std::endl;

for(int i = 0; i < repeat; i++)
std::cout << "repeat\n";
}

##### Share on other sites

sorry java thanks that helped figured it out

Edited by SmallTallGiant

##### Share on other sites

The code for the for loop will be the same but here:


//imported crap and other code

Scanner scan = new Scanner(System.in);

int numLoops;

System.out.print("How many loops?");
numLoops = scan.nextInt();

for(int i = 0; i < numLoops; ++i){

//do whatever you need to and loop as many times as the user entered for numLoops
}


you can do the same thing with a while loop (or do while), but the for loop has everything working in one line, where the while loops will take a couple.

Hope this helps

Edited by Mathew Bergen

##### Share on other sites

[quote name='Mathew Bergen' timestamp='1357979039' post='5020618']
where the while loops will take a couple
[/quote]

Remember C/C++ and as far as I know Java too, don't use line endings a seperators.

You can happily write your whole application in one line, as long as the compiler supports it and you don't miss any semicolons.

##### Share on other sites

where the while loops will take a couple

Remember C/C++ and as far as I know Java too, don't use line endings a seperators.

You can happily write your whole application in one line, as long as the compiler supports it and you don't miss any semicolons.

I understand his, however i said this because the only time i put more than one  "line" of code on one line, is in simple switch statements,

  switch(choice){        case 1: /*goto function*/ break;        ... }  

and in the code that other people write, i have never seen more that one "line" of code on a  single line. And if you where to write a whole application on one line, it would be very confusing, unless it was a hello world program.