Is this the correct basic code for a for-loop?

  • Thread starter Thread starter tandoorichicken
  • Start date Start date
  • Tags Tags
    Code
AI Thread Summary
The discussion centers around the correct syntax for a for-loop in programming. Participants emphasize the importance of using semicolons instead of commas in the loop declaration. There is also a preference for placing the opening brace on the same line as the for statement for a cleaner look. Additionally, a coding challenge is presented where the user seeks to print a name ten times with a blank line at the end, with suggestions to either use a conditional statement within the loop or simply add a separate print statement after the loop. The consensus is to keep the code neat and functional.
tandoorichicken
Messages
245
Reaction score
0
Is this the correct basic code for a for-loop?

for (n=1, n<=10, n++) {
/* statements */
}

If not what am I doing wrong?
 
Physics news on Phys.org
Use semi-colons rather than commas!


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

}

(I cannot bring myself to put that first "{" up on the previous line! It looks so unbalanced.)
 
I think you want semicolons separating items in the "for" satement"

for (i = 1; n <= 0; n++)
 
thank you very, very much. :biggrin:
 
HallsofIvy said:
Use semi-colons rather than commas!


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

}

(I cannot bring myself to put that first "{" up on the previous line! It looks so unbalanced.)

Same thoughts here!
i don't know why many of the books promote that style!
I always had it ur way because as u put it , it looks balanced not to mention neat!

-- AI
 
Okay one more problem. For a programming homework I had to print my name ten times and leave a blank line at the end. My code looked like this:

for (k=1; k<=10; k++) {
printf("%2d Joe Schmoe\n", k);
}

That prints my name ten times but doesn't leave a blank line at the end. If I put two \n's then that leaves a blank line in between each printing. Is there a way to print a blank line at the end within the structure of the for-loop or do I have to just use printf("\n"); after the whole thing?
 
You could use something like

if (k==10) printf("\n");

but that would be silly. Just put the printf("\n"); at the end, after the for loop.

- Warren
 
Back
Top