I just started learning C language. So, I am running into a lot of problems. I thought declaring i under for loop is enough, and I can use the value of i for outside too. But I think, that was not the case. Can someone explain the situation, please.
# include <stdio.h>
int main(void)
{
int x;
printf("Enter how many numbers in arrays you want to input : ");
scanf("%i", &x);
int score[x];
for(int i= 0; i <= x; i++)
{
printf("Enter the score : ");
scanf("%i", &score[i]);
}
// in the below line the output said "i" is undeclared.
float average = score[i] / x;
printf("The average score is : %f", average);
}
iis declared in the initialization section of aforstatement. That means the scope and lifetime of that variable is the expressions in theforstatement itself as well as the block statement it contains. Once the loop is done, the variable no longer exists.You need to declare
ioutside of the loop if you want to use it outside of the loop.That being said, you don't actually need to use
ioutside of the loop.