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);
}
CodePudding user response:
The answer is fairly simple
because of where you decalred i
it is only visable to the for loop.
To make i
visable to the whole function all you need to do is:
int i = 0;
for (; i <=x; i ){
printf("Enter the score : ");
scanf("%i", &score[i]);
}
this makes i
avaliable throughout the function
CodePudding user response:
i
is declared in the initialization section of a for
statement. That means the scope and lifetime of that variable is the expressions in the for
statement itself as well as the block statement it contains. Once the loop is done, the variable no longer exists.
You need to declare i
outside of the loop if you want to use it outside of the loop.
int i;
for(i= 0; i <= x; i )
That being said, you don't actually need to use i
outside of the loop.
CodePudding user response:
There are security issues associated with using scanf so don't use it for anything serious. That said, I tried to re-write your program properly, and it still has pretty rubbish input validation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INPUTTEXTLEN 20
#define MAXINPUTINT 1000
int inputint() {
char inputtext[INPUTTEXTLEN 1] = {0};
long inputval;
while (1) {
fgets(inputtext, INPUTTEXTLEN, stdin);
if (strlen(inputtext) > 0) {
inputval = atoi(inputtext);
if ((inputval < MAXINPUTINT) && (inputval >= 0)) break;
}
}
return (int)inputval;
}
int main(void)
{
int x = 0;
printf("Enter how many numbers in arrays you want to input : ");
//scanf("%i", &x);
while (x <= 0) {
x = inputint();
}
int score[x];
float average = 0;
for(int i= 0; i < x; i )
{
printf("Enter the score : ");
//scanf("%i", &score[i]);
score[i] = inputint();
average = score[i];
}
average /= x;
printf("The average score is : %f\n", average);
}