Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

arrays 1

Status
Not open for further replies.

welshspoon

Technical User
Dec 14, 2002
34
0
0
GB
hi
i'm writing a program so that a user can enter a sequence of values at the command prompt which are then manipulated. These values are stored in an array of size 1000.
The problem im having is that I want the program to stop asking the user for values once a zero has been entered and then proceed to manipulate the entered values.

I've written the same thing in Java and that works fine but as I'm new to C i'm not sure what to do.

Thanks in advance for your help
 
Code:
#include <stdio.h>

int array[1000];

int main(void)
{
   size_t count, i = 0;
   while ( i < sizeof array / sizeof *array )
   {
      int value;
      printf("Enter value #%lu: ", (long unsigned)(i + 1));
      fflush(stdout);
      if ( scanf("%d", &value) == 1 )
      {
         if ( value == 0 )
         {
            break;
         }
         array[i++] = value;
      }
   }
   for ( count = i, i = 0; i < count; ++i )
   {
      printf("array[%lu] = %d\n", (long unsigned)i, array[i]);
   }
   return 0;
}

/* my output
Enter value #1: 9
Enter value #2: 16
Enter value #3: 42
Enter value #4: 0
array[0] = 9
array[1] = 16
array[2] = 42
*/
 
Another way to do this, which works even in languages without "break" (e.g. the late lamented pascal) is to use code exactly as DaveSinkula, but when value==0, set i to sizeof array. This stops the loop next time round. The downside is that i is no longer a measure of how many numbers were entered, so you either have to use another variable for that, or you have to look for the zero when you're processing the array.
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top