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

Started by
4 comments, last by Crusable77 11 years, 3 months ago

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

Advertisement

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";
}

sorry java thanks that helped figured it out

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 smile.png

[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.

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.

This topic is closed to new replies.

Advertisement