Alex Alex - 2 months ago 6
C Question

printing unsigned array and exiting the loop

I want to be able to write a function that can let me store 10 values. I should be able to exit the loop with "0" without storing 0 to the array. I should be able to reenter the array and keep storing until i get 10 values. I'm quite new to this stuff so i hope i've followed the rules correctly here.

I started to write something simple but when i store like 5 values it will print out the 5 values and then some random numbers. Why is that? And how can i exit the loop without the array storing the 0?

#include <stdio.h>

int main(void)
{
int arrayTable[9] = {0};
int i;

for (i=0; i<10; i++)
{
printf("Enter Measurement #%i (or 0): ", i+1);
scanf("%d", &arrayTable[i]);
if (arrayTable[i] == 0)
{
break;
}
}

for (int i=0; i<10; i++)
{
printf("%d\n", arrayTable[i]);
}

return 0;
}

Answer

You probbaly want this:

  ...
  int arrayTable[10] = {0};   // <<< [10] instead of [9]

  ...

  for (i=0; i<10; i++)
  {
      if (arrayTable[i] == 0) // <<< add this
        break;                // <<<

      printf("%d\n", arrayTable[i]);
  }
  ...