2014-02-10 27 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"); 
}`