[英]How do I assign values to an array using scanf within a for loop?
int main (void)
{
int i = 1;
int arrayOfNumbers[4];
for(i = 1; i >= 4; i++)
{
printf("Enter a Number");
scanf("%d", &arrayOfNumbers[i]);
}
return 0;
}
My compiler compiles the program, however the for loop just doesnt happen.我的编译器编译了程序,但是 for 循环没有发生。 This program is simply a dud.
这个程序简直是个哑巴。 How do I create a loop designed to assign all the values of an array?
如何创建一个旨在分配数组所有值的循环?
Change:改变:
for(i = 1; i >= 4; i++)
{
printf("Enter a Number");
scanf("%d", &arrayOfNumbers[i]);
}
return 0;
to:到:
for(i = 1; i <= 4; i++)
{
printf("Enter a Number");
scanf("%d", &arrayOfNumbers[i]);
}
return 0;
Since 1 is not bigger than 4 it will not go through the for-loop.由于 1 不大于 4,因此不会通过 for 循环。
This is the right declaration for for
loop:这是
for
循环的正确声明:
for ( init-expression ; cond-expression ; loop-expression )
In your code, you set your initial value of i
as 1 & in condition-expression
your code fails in the first condition itself where 1
is not greater than 4
.在您的代码中,您将
i
的初始值设置为 1 & 在condition-expression
您的代码在第一个条件本身失败,其中1
不大于4
。
Your for
loop declaration should be你的
for
循环声明应该是
for(i = 1; i <= 4; i++)
{
//code to be executed
}
Complete code for your program :程序的完整代码:
#include<stdio.h>
int main (void)
{
int i = 1;
int arrayOfNumbers[4];
for(i = 1; i <= 4; i++)
{
printf("Enter a Number \n");
scanf("%d", &arrayOfNumbers[i]);
}
printf("Your Entered number is.. \n");
for(i = 1; i <= 4; i++)
{
printf(" %d",arrayOfNumbers[i]);
printf("\t");
}
return 0;
}
The following code gives us output as,以下代码为我们提供了输出,
Enter a Number
1
Enter a Number
2
Enter a Number
3
Enter a Number
4
Your Entered number is..
1 2 3 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.