Can you help me please?
I don't know how to do this. How can I declare an array with an unsigned value? The only way I know is to specify the size first then the user can input his values. How to do this? Please.

Member Avatar for cayman

You seem to have 2 different questions here.
The first in your title asks how to accept numbers then cease if the input number is negative (below 0).

This can be done with a do while loop:

int main (void) {
    int usernumber = 0;
    do {
        printf("Please enter a positive number to continue or a negative number to exit\n");
        scanf("%d", &usernumber);
    } while (usernumber >= 0);
    return 0;
}

In your post text you ask how to declare an array with an unsigned value. Im not sure what you mean here, but if you mean an arry of unsigned integer type, then the declaration would be as follows:

unsigned int myarray[ARRAY_SIZE];

Is it possible he means an array with a size not known at compile-time?
If so, one typically uses malloc() or similar.
See following snippet:

#include <stdint.h>
#include <stdlib.h>

void main() {
  // this can be set at run time
  // for example by the user
  size_t n, size = 5;

  // we declare as pointer
  // pointers can be accessed as an array
  char *array;
  // now we allocate some memory
  array = malloc(size);

  // we can now access this like a regular array
  for(n = 0; n < 5; n++) {
    array[n] = rand();
  }

  // but we must not forget to free this dynamically
  // allocated memory or we will have a "memory leak"
  free(array);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.