How to create a loop that user enters?

2020-01-16 2:37 pm
For example:

cout << "How many times?" times
cin >> times ;
cout << "Hello World << endl;

If user inputs 10, it will loop 10 times?

Thanks!

回答 (3)

2020-01-16 5:05 pm
The standard way to write that is with a for loop, and the most common way to do that is something like:

    for (int i=0; i < times; ++i )
    {
        [statements to be repeated]
    }

That declares a variable (i) and sets it two zero; tests that the value of i is less than 10 before each iteration of the loop; and adds 1 to the value of i after each iteration of the loop.  The net effect is that the value of i is 0 during the first iteration, 1 during the second, and so on until i==9 on the tenth iteration.  Notice that the condition (i < 10) is true before each of those iterations.

The tenth iteration, with i==9, is the last iteration that runs because, at the end of that iteration, adding 1 makes i==10 and the loop condition (i < 10) is no longer true.

Declaring the variable in the loop header that way makes the variable local to that loop.  If I coded "for (i=0; i<10; i++)" instead, that would use a previously declared variable named "i".  This is about the only place I'd recommend using such a short, uninformative name like "i".  Feel free to rename that to something longer, if that helps you understand the code better.

The values of i run from 0 to 9, mostly out of habit.  Array index values start at 0 in C++ and most other programming languages.  If you're going to write a loop to look at each element of a ten-element array, these are the index numbers you'll need to generate; from 0 to 9.  Since i isn't being used for that, feel free to also count from 1 to 10 if that helps you understand the code better. 

    for (int loop_counter=1; loop_counter <= 10; loop_counter = loop_counter + 1)
    { [statements to repeat] }

That also spells out the increment operation explicitly.  Any good compiler will generate the same binary code for that loop as the previous one. 
2020-01-19 4:07 am
cout << "How many times? " ;

cin >> times ;
while (times--) 
cout << "Hello World << endl; 
2020-01-16 2:38 pm
>> coo coo 
this class_10 inputs 10 is hard >>
<< loop >> 
times; 

try this. 


收錄日期: 2021-04-24 07:52:16
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20200116063734AAAvDIP

檢視 Wayback Machine 備份