[英]How do I print multiple strings based on user input using for loop in C
I am confused on how I should format the for loop.我对如何格式化 for 循环感到困惑。 I want to print "Happy Birthday" as many times as the user inputs.
我想根据用户输入的次数打印“生日快乐”。
enter code here在此处输入代码
#include <stdio.h>
int main(){
int age;
int bdays;
printf("What is your age?");
scanf("%d", age);
for(age = 0; **`age ????`**; age++){
printf("Happy Birthday\n");
} } } }
You have to iterate over a loop control variable您必须遍历循环控制变量
#include <stdio.h>
int main()
{
int age;
int bdays;
printf("What is your age?\n");
scanf("%d", &age);
for (int i = 0; i < age; i++) {
printf("Happy Birthday\n");
}
}
And do not forget to use pointer in scanf()
并且不要忘记在
scanf()
使用指针
you don't know how many times the user will input an age, so instead of a for loop consider a while condition?你不知道用户会输入多少次年龄,所以而不是 for 循环考虑一个 while 条件? I will use age 0 as an exit, you can do it in different ways, I doubt you want to print happy birthday every single time so I think you need some sort of condition to meet?
我将使用年龄 0 作为退出,你可以用不同的方式来做,我怀疑你每次都想打印生日快乐,所以我认为你需要某种条件来满足?
also small nitpick, you want to give scanf the pointer to the variable so it can modify it, so in scanf you want &age instead of age也是小吹毛求疵,你想给 scanf 指向变量的指针,以便它可以修改它,所以在 scanf 你想要 &age 而不是 age
put the whole thing把整个事情
while(age!=0){
printf("What is your age?");
scanf("%d", &age);
printf("Happy Birthday\n");
}
return 0;
this way you can do it over and over again, if you input 0 you can exit the program at any time这样你可以一遍又一遍地重复,如果你输入0你可以随时退出程序
edit: seems I misunderstood, I thought you meant as many times as the user gives an input not as many times as the age... so the above answer is correct and I am wrong in that case.编辑:似乎我误解了,我认为您的意思是用户输入的次数与年龄的次数相同……所以上述答案是正确的,在这种情况下我错了。
#include<stdio.h>
main()
{
int n,i;
printf("Enter how many time you want to print happy birthday");
scanf("%d",&n);
for(i=0;i<n;i++)
printf("\nHAPPY BIRTHDAY");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.