简体   繁体   中英

converting a FOR loop to a DO WHILE loop in C++

im trying to convert this into a do-while; it is supposed to show a pyramid based on a number that you have entered:

    int size,a,b,c;
    printf("Enter a Number: ");
    scanf("%d",&size);
    printf("\n");

    // for loop starts here
    for(a=1; a<=size; a++)
    {

     for(b=1; b<=size-a; b++)
     {
      printf(" ");
     }

     for(c=1; c<=(2*a)-1; c++)
     {
      printf("*");
     }

      printf("\n");
    }
     getch();
   }

this is what i have done so far:

    int size;
    int a=1;
    int b=1;
    int c=1;

    do {

     a++;

      do {
       c++;
       printf("*");
      } while(c<=((2*a)-1));

        do {
       printf(" ");
          b++;
      } while(b<=(size-a));

      printf("\n");

    } while(a<=size);

    getch();
   }

Aaaaand its not showing the same output, any suggestion guys? TIA :)

A for loop

for (BEGIN; COND; INC)
{
    WORK;
}

Is equivalent to the while loop

{
    BEGIN;
    while (COND)
    {
        WORK;
        INC;
    }
}

… except for the effect of a continue statement in the WORK part (with a for loop the continue jumps to the INC ), and except that names declared in the for loop's BEGIN are in the same declarative region as those declared in the COND .

It doesn't make an elegant do-while loop, however.

{
    BEGIN;
    do
    {
        if (! COND) break;
        WORK;
        INC;
    } while (true)
}

Alternatively (although it repeats code)

{
    BEGIN;
    if (COND)
    {
        do
        {
            WORK;
            INC;
        } while (COND)
    }
}

Compilers actually tend to convert for-loops to the code equivalent of do-while loops. The result looks like this (using Neil Kirk's metavariables):

BEGIN;
if(COND) {
    do {
        WORK;
        INC;
    } while(COND);
}

Note that COND appears in two different places. If you examine the generated assembly for a for-loop, you'll usually see that effect, unless the optimizer is clever enough to figure out (or told by the programmer using __assume ) that COND will never be false the first time through.

#include <stdio.h>
void main()
{
    int size;
    int i=1;
    int j;
    int k;
    printf("Enter the number:\n");
    scanf("%d",&size);
    do
    {
        j=i;
        do
        {
            printf(" ");  
            j++;
        }while(j<=size);
        k=1;
        do
        {
            printf("*");
            k++;
        }while(k<=(2*i)-1);
        printf("\n");
        i++;
    }while(i<=size);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM