want to create diamond shape using while in C

回眸只為那壹抹淺笑 提交于 2020-01-14 07:11:27

问题


i have created the diamond using for loop but i am not able to convert it into While.

can you please help me to acheive the same goal using While loop. i tried while loop few times but it's running infinite time.

#include<stdio.h>
#include<conio.h>

int main() {
    clrscr();
    int i, j, k;

    for(i=1;i<=2;i++) {
        for(j=i;j<5;j++) {
            printf(" ");
        }

        for(k=1;k<(i*2);k++){
            printf("*");
        }

        printf("\n");
    }

    for(i=3;i>=1;i--){
        for(j=5;j>i;j--) {
            printf(" ");
        }

        for(k=1;k<(i*2);k++) {
            printf("*");
        }
        printf("\n");
    }
    getch();
}

回答1:


It would help to see your code for your implementation of the while loop to see what's wrong, but the general solution for converting a for loop to a while loop is this:

for(i=1;i<=2;i++)
{ 
  /*your code*/ 
}

becomes

i = 1;
while(i<=2)
{
  /*your code*/
  i++;
}

Make sure your iterators and decrementors are in the right places.




回答2:


You might try with placing the initialisation in front of the loop, the incrementation/decrementation at the end of the loop and leaving the condition as is. For example

for(k=1;k<(i*2);k++)
{
    printf("*");
}

translates to

k=1;
while(k<(i*2)){
    printf("*");
    k++;
}


来源:https://stackoverflow.com/questions/22332781/want-to-create-diamond-shape-using-while-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!