问题
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