Hello all,
I'm starting C++ and wan't to learn for loop. I want the Loop to count down the rotate and print its value until when it equals to value where it terminates. Here is code

int value;
    int rotate = 4;
    for (value = 0; rotate>value; rotate--; ){
        cout<<"Now rotate value is:"<<rotate<<endl;

Recommended Answers

All 5 Replies

first, remove the ; after rotate--
second, you can't have an opening { without a closing } (for loop), so add a brace.
third, using rotate > value will for loop until rotate is no longer greater than value, but likely won't loop the final iteration. So if value is 0, then it would loop probably 4 3 2 1, not 4 3 2 1 0 (0 being the value of value). If that's what you want, cool. If not... replace the > with a !=

int value;
int rotate = 4;
for (value = 0; rotate>value; rotate--){
     cout<<"Now rotate value is:"<<rotate<<endl;
}

Here is code

It's wrong. Click here for some tuts

int value;
int rotate = 4;
for (value = 0; rotate>value; rotate--; ){ // remove that semicolon
        cout<<"Now rotate value is:"<<rotate<<endl;
//missing closing brace

How I would do it is like this:

for (int rotate = 4; rotate>0; rotate--)
        cout<<"Now rotate value is:"<<rotate<<'\n';

as you can see, I'm not using braces at all, but if you have only one line of code in you statement block, braces aren't required.
You can also see how the variable "value" has become obsolete and how it is now easier to read what the for-loop is actually doing :)

One final personal touch: I always use "\n" instead of endl . It makes more sence to me because \n is always a newline no matter what OS, or programming language.

[edit]
damn, too slow...

One final personal touch: I always use "\n" instead of endl . It makes more sence to me because \n is always a newline no matter what OS, or programming language.

endl isn't always newline? :icon_eek:

endl isn't always newline? :icon_eek:

Well, it is in C++, but not in other program languages it isn't. That's what I meant. "\n" is always a newline in C++ because it is interpreted by the stream class to convert it to your OS' needs.
Also endl can make calls to flush() that you might not want (not to mention the overhead), so that's why I use "\n"

Thanks alot all of you guys!
I have learned alot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.