So I'm trying to make an array with multiple values. However, I want the user to be able to not only decide each value, but how many values are in the array itself. The program doesn't seem to work, though.
Issue at hand is that every time I run my code it runs just fine until it gets to the for loop. The code allows me to input one value but then just exits with the following message:
Process returned 5 (0x5) execution time : 2.656 s
I've tried a couple of other methods but none of them seem to work. Here's my latest attempt
// Initiate variable
int iterations;
printf("Input amount of values: ");
scanf("%d",&iterations);
fflush(stdin);
int listOfValues[iterations];
fflush(stdin);
int i;
int tempvar;
printf("Input values in order: ");
for (i = 0; i < iterations; i );
{
scanf("%d",&tempvar);
fflush(stdin);
listOfValues[i] = tempvar;
}
What am I doing wrong here? Please keep in mind I'm still in the stage of learning C and programming in general, so be gentle!
CodePudding user response:
it a small mistake just remove the semicolon after the for loop.
like this:
// Initiate variable
int iterations;
printf("Input amount of values: ");
scanf("%d",&iterations);
fflush(stdin);
int listOfValues[iterations];
fflush(stdin);
int i;
int tempvar;
printf("Input values in order: ");
for (i = 0; i < iterations; i )
{
scanf("%d",&tempvar);
fflush(stdin);
listOfValues[i] = tempvar;
}
if we put a semicolon after the for statement it will run just once hope this helped
CodePudding user response:
I'll admit, I've done a lot of embarrassing stuff in my life, but adding a semicolon after a for loop has definitely broken some kind of new high-score.
I'll be replying to a few comments that piqued my interest;
Some programmer dude:
Please note that
fflush(stdin)
is not standard C, IIRC only one compiler support it as a non-portable extension. And it's not even needed for your case.
I'm only using fflush(stdin)
because I'm writing on Code::Blocks. There's a small issue with the IDE that my professor let me know about, and he also told me to use fflush(stdin)
. Sorry about any confusion.
Haris:
Aside: Don't bounce through
tempvar
andListOfValues
. Input directly into the array and check the return value ofscanf
.
I had done that originally, but when I repeatedly had issues, I thought maybe that was the reason.
Anyway, thanks for the help Muhammad! Code is working perfectly now.
Side note: Apologies if this isn't the correct use of "Answer my question". Do let me know if that is the case.