fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(void)
  5. {
  6. int i, m, max = 100;
  7.  
  8. //creating a large enough array to store user inputs
  9. int *array = malloc(sizeof(int) * max);
  10.  
  11. //check if memory was allocated or not
  12. if(array == NULL)
  13. {
  14. printf("memory allocation problem!");
  15. exit(1);
  16. }
  17.  
  18. //integer to make note of size of array or you can use the sizeof() function instead
  19. int size_of_array = 0;
  20.  
  21. for (i = 0; i < max; i++)
  22. {
  23. printf("Fill the table with integers: ");
  24.  
  25. if(scanf("%d", &m) != 1) //check for `scanf`
  26. {
  27. char consume;
  28. printf("wrong input, try again\n");
  29. scanf("%c", &consume);
  30. i--;
  31. continue;
  32. }
  33.  
  34. if (m > 0) //if positive number, accept
  35. {
  36. array[i] = m;
  37. printf("a[%d] = %d\n",i,m);
  38. size_of_array++;
  39. }
  40.  
  41. else //else break out of scanning
  42. {
  43. break;
  44. }
  45. }
  46.  
  47. //do the program.....
  48.  
  49. //don't for get to free the memory at the end
  50. free(array);
  51. }
  52.  
Success #stdin #stdout 0s 2304KB
stdin
c
1
2
3
a

f
2
1
-1
stdout
Fill the table with integers: wrong input, try again
Fill the table with integers: a[0] = 1
Fill the table with integers: a[1] = 2
Fill the table with integers: a[2] = 3
Fill the table with integers: wrong input, try again
Fill the table with integers: wrong input, try again
Fill the table with integers: a[3] = 2
Fill the table with integers: a[4] = 1
Fill the table with integers: