How can I use for loop to scan unknown number of inputs in c using an array. I don't know what to put in the for loop
I tried this
#include <stdio.h>
int main() {
int in[100];
for (int i = 0;; i ) {
scanf("%d", &in[i]);
if (in[i] == -1) {
break;
}
}
}
CodePudding user response:
You need to be able to tell when the input is done. You can either read all input until stdin
is at EOF
or let the user enter a specific value that means "stop, I have no more input". It seems you've chosen -1
to mean "stop".
In your case, the loop should have been:
int i; // declare i before the loop to be able to use it after the loop
for (i = 0; i < 100; i ) { // note: check the boundary 100
// check that scanf succeeds too:
if(scanf(" %d", &in[i]) != 1 || in[i] == -1) {
break;
}
}
printf("you entered %d number of values\n", i); // i used after the loop
You may also want to allocate the memory dynamically. Using an array of, say int[100]
, will not be enough if the unknown amount turns out to be 101
.
Here's an example where the user is asked to enter any number of integers. Entering -1
will exit the loop.
#include <stdio.h>
#include <stdlib.h>
int main() {
puts("Enter integers (-1 to stop): ");
int *in = malloc(sizeof *in); // allocate space for 1 int
unsigned count = 0;
while(scanf(" %d", &in[count])==1 && in[count] != -1) {
count;
// allocate space for one more int:
int *np = realloc(in, (count 1) * sizeof *np);
if(np == NULL) {
puts("Can't allocate more memory. What you entered so far will have to do");
break;
}
in = np;
}
printf("you entered %d number of values\n", count);
for(unsigned i = 0; i < count; i) {
printf("%d\n", in[i]);
}
free(in);
}
CodePudding user response:
I tried this `
#include <stdio.h>
int main()
{
int in[100];
for (int i=0;;i ) {
scanf("%d", &in[i]);
if (in[i] == -1) {
break;
}
}
}`