Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
2.33/5 (2 votes)
See more:
for(k = 0; k < 2500; k++)
x[k] = 2500-k;
Posted
Comments
[no name] 15-Dec-15 18:39pm    
Think about this, in the hope x[] is compatible:

const int numLoop= 2500;
int k= 0;
while (k < numLoop)
{
x[k]= numLoop - k;
k++;
}
Sergey Alexandrovich Kryukov 15-Dec-15 18:51pm    
5! I happened to answer a bit later, probably you posted your comment when I was typing.
I think must important illustration here is "const int" — please see my answer.
—SA
Sergey Alexandrovich Kryukov 15-Dec-15 18:54pm    
Anyway, I added a credit to your comment in my answer.
Cheers,
—SA
[no name] 15-Dec-15 19:00pm    
A lot of parallel processes without synch today :-)
Thank you, Bruno
Sergey Alexandrovich Kryukov 15-Dec-15 19:28pm    
:-)

It's up to you, entirely. I personally would leave it as a "for" loop. Please see the while variant by Bruno (0x01AA) in his comment to the question — the code is longer, without apparent benefits of performance of anything else. He also illustrated the point I'll make below.

I would change another thing, which I consider simply unacceptable. Take a look: you use immediate constant 2500. You could write an explicit constant declaration. But do you understand what's the worst thing here? You have 2500 written twice, and it's very likely that you need this value elsewhere. Imagine you have to change this value, what will you do? Change it in N places?! God forbid…

There is not any reason to have such constant. It only reduce level of abstraction of your algorithm. Of course, it should be a variable, possibly a parameter of some function. And where it should be taken originally? Well, it could be a part of input data, anything. Even a constant, but that constant should be an explicitly defined constant, probably grouped with other constants, and so on. Why? For maintainability and reuse.

—SA
 
Share this answer
 
v2
Comments
[no name] 15-Dec-15 18:57pm    
But the question was, how to convert a "for" to a "while".... Anyway your objections are helpful, a 5.
Sergey Alexandrovich Kryukov 15-Dec-15 19:28pm    
Thank you, Bruno.
I know, but the inquirer formally accepted my answer. :-)
Again, you can post your own answer.
—SA
Simple, open your C++ class book and look up Loops. No one here is going to do your homework for you.
 
Share this answer
 
Comments
[no name] 15-Dec-15 19:10pm    
No, not doing the homework. But give some hints I think is ok. I did not vote!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900