[英]C Program triangle
I need to prompt a user to enter a number 'n' then print print stars in separate lines, for exanple if the user enters 5 the following should be printed (Using a while loop) 我需要提示用户输入数字“ n”,然后在单独的行中打印打印星,例如,如果用户输入5,则应打印以下内容(使用while循环)
*
**
***
****
*****
****
***
**
*
The code i have doesn't output that 我的代码没有输出
int n, x = 1, y = 1;
printf("enter a number : ");
scanf_s("%d", &n);
while (x <= n){
x++;
while (y <= x){
while (y >= n){
y--;
printf("*");
}
printf("\n");
}
system("pause");
}
} }
This should work for you: 这应该为您工作:
#include <stdio.h>
int main() {
int number, count, characterCount;
printf("Please enter a number:\n>");
scanf("%d", &number);
for(count = 1; count <= number; count++) {
for(characterCount = 1; characterCount <= count; characterCount++)
printf("*");
printf("\n");
}
for(count = 1; count < number; count++) {
for(characterCount = number-1; characterCount >= count; characterCount--)
printf("*");
printf("\n");
}
return 0;
}
Edit after comment: 评论后编辑:
Solution with while loop: while循环的解决方案:
#include <stdio.h>
int main() {
int number, count = 1, characterCount;
printf("Please enter a number:\n>");
scanf("%d", &number);
while(count <= number) {
characterCount = 1;
while(characterCount <= count) {
printf("*");
characterCount++;
}
printf("\n");
count++;
}
count = 1;
while(count < number) {
characterCount = number-1;
while( characterCount >= count) {
printf("*");
characterCount--;
}
printf("\n");
count++;
}
return 0;
}
You can make it using only 2 for
loops like this: 您可以仅使用2个for
循环来实现,例如:
int i,k,n,flag=0;
printf("Enter Number of Rows :");
scanf("%d",&n);
for(i=-n;i<=n;i++)
{
if(i < 0)
{
i = -i;
flag=1;
}
for(k=(n-i)+1;k>0;k--)
{
printf("*");
}
if(flag==1)
{
i=-i;flag=0;
}
printf("\n");
}
For example if user enter value 2
it will print 例如,如果用户输入值2
,它将打印
*
**
***
**
*
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.