2014-02-10 29 views
1

對於我的編程任務,我必須創建3個程序,根據用戶的輸入在c中打印出一個基於星號的三角形。 3個程序之間的區別是一個將用於循環,另一個將使用while循環,最後一個將使用goto。我有for循環程序以及goto程序,但對於while循環程序,我不確定如何將它合併到我的程序中。這是我用for循環的程序,第二個程序是我在while循環版本上的嘗試。如何改變我的程序使用while循環而不是for循環。星號三角形c

#include <stdio.h> 

int main() { 
int lines, a, b; 

//prompt user to input integer 
do{ 
    printf("Input a value from 1 to 15: "); 
    scanf("%d", &lines); 

//Check if inputed value is valid 
if(lines < 1 || lines > 15) { 
    printf("Error: Please Enter a Valid number!!!\n"); 
    continue; 
} 
/*create triangle based on inputed value */ 
    for(a = 1; a <= lines; a++) { 
     for(b=1; b<= a; b++) { 
      printf("*"); 
     } 
     printf("\n"); 
    } 
} while(1); 
system("pause"); 
} 

課程校#2:

#include <stdio.h> 

int main() { 
int lines, a = 1, b = 1; 

//prompt user to input integer 
do{ 
    printf("Input a value from 1 to 15: "); 
    scanf("%d", &lines); 

//Check if inputed value is valid 
if(lines < 1 || lines > 15) { 
    printf("Error: Please Enter a Valid number!!!\n"); 
    continue; 
} 
    while(a <= lines) { 
     a++; 
     while (b <= a) { 
      b++; 
      printf("*"); 
     } 
     printf("\n"); 
    }  
} while(1); 
system("pause"); 
} 

回答

0

這裏是你如何轉換爲while環路for循環像下面

for (stat1; stat2; stat3) { 
    stat4; 
} 

stat1; 
while (stat2) { 
    stat4; 
    stat3; 
} 

因此,這裏是while你想要的迴路:

a = 1; 
while(a <= lines) { 
    b = 1; 
    while (b <= a) { 
     printf("*"); 
     b++; 
    } 
    printf("\n"); 
    a++; 
}  
0

b=1之前第二while

while(a <= lines) { 
     a++; 
     b=1; //you want to start b from 1 for each inner loop 
     while (b <= a) { 
      b++; 
      printf("*"); 
     } 
     printf("\n"); 
    } 
0

該程序2可以如下改變。下面的代碼結果等於program1.`

#include <stdio.h> 

int main() { 
int lines, a = 1, b = 1; 

//prompt user to input integer 
do{ 
printf("Input a value from 1 to 15: "); 
scanf("%d", &lines); 

//Check if inputed value is valid 
if(lines < 1 || lines > 15) { 
printf("Error: Please Enter a Valid number!!!\n"); 
continue; 
} 
while(a <= lines) { 
    //a++; 
    while (b <= a) { 
     b++; 
     printf("*"); 
    } 
    b =1; 
    a++1; 
    printf("\n"); 
}  
} while(1); 
system("pause"); 
}`