Like Tree1Likes
  • 1 Post By camel-man

Do For --> Do While

This is a discussion on Do For --> Do While within the C Programming forums, part of the General Programming Boards category; Hello I had a basic question that I wanted to make sure I had right. Rewrite the following code using ...

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    28

    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);
    My answer was the following:

    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?

  2. #2
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    612
    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.
    Last edited by camel-man; 02-05-2013 at 09:41 PM.

  3. #3
    Registered User
    Join Date
    Jan 2013
    Posts
    28
    Quote Originally Posted by camel-man View Post
    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);

  4. #4
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    612
    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
    M_A_T_T likes this.

  5. #5
    Registered User
    Join Date
    Jan 2013
    Posts
    28
    That makes sense. Thanks a lot for your help.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21