# Do For --> Do While

• 02-05-2013
M_A_T_T
Do For --> Do While
Hello I had a basic question that I wanted to make sure I had right.

Rewrite the following code using a do-while statement with no decisions in the loop body:

Code:

```sum = 0; for (odd = 1; odd < n; odd = odd + 2)     sum = sum + odd; printf("Sum of the positive odd numbers less than %d is %d\n", n, sum);```

Code:

```sum = 0; odd = 1; while(odd < n){ sum = sum + odd printf("Sum of the positive odd numbers less than %d is %d\n", n, sum); odd = odd + 2; }```
My question is did I correctly format the statement from a for to a do-while and did I do it correctly with no decisions in the loop body?
• 02-05-2013
camel-man
That is just a while loop,
Code:

```do { //code }while(condition);```
is a do while (pay attention to the semicolon after the while condition).

EDIT: Also, the printf statement should be out of the do while loop, Notice that the for loop has no braces, therefore it only executes the line underneath it, not both of the lines.
• 02-05-2013
M_A_T_T
Quote:

Originally Posted by camel-man
That is just a while loop,
Code:

```do { //code }while(condition);```
is a do while (pay attention to the semicolon after the while condition).

EDIT: Also, the printf statement should be out of the do while loop, Notice that the for loop has no braces, therefore it only executes the line underneath it, not both of the lines.

Gotcha. Thanks!

With a little bit of revision, I have the following now:

Code:

```sum = 0; odd = 1; Do { sum = sum + odd odd = odd + 2 } while(odd < n); printf("Sum of the positive odd numbers less than %d is %d\n", n, sum);```
• 02-05-2013
camel-man
Looks good, aside from the missing semicolons on line 6,7, and the Do in the do while is a lowercase 'd' in case you were getting errors :)
• 02-05-2013
M_A_T_T
That makes sense. Thanks a lot for your help.