How to select multiple elements in an array with C?

17,765

There's nothing built-in that does it, you need to write a loop. Don't forget that array indexes start at 0.

int all_positive = 1;
int i;
for (i = 0; i < 10; i++) {
    if (myArray[i] <= 0) {
        all_positive = 0;
        break;
    }
}
if (all_positive) {
    printf("Thank you for providing positive numbers!\n");
}
Share:
17,765
Terryn
Author by

Terryn

Updated on June 04, 2022

Comments

  • Terryn
    Terryn about 2 years

    Is there a way to select multiple elements in array using one line of code in C? For instance, say I had the following code (assuming I already asked the user for twenty numbers, the first ten I asked to be positive and the last ten I asked to be negative):

    if (myArray[0 through 9] > 0)
    {
      printf("Thank you for providing positive numbers!");
    }
    else
    {
      printf("Sorry, please try again!");
    }
    
    if (myArray[10 through 19] < 0)
    {
      printf("Thank you for providing negative numbers!");
    }
    else
    {
      printf("Sorry, please try again!");
    }
    

    What code could I substitute for "through"? I am fairly new to this language, and have never heard of a way of doing so. I know that with this particular code I could make two arrays, one for the positive numbers and one for the negative numbers, but I am curious to know for other programming projects.

    Thank you for reading and answering!

  • Terryn
    Terryn almost 10 years
    Okay thank you I wasn't sure if there was or not, so I will use loops instead. And thank you for pointing out that I wrote one instead of zero! I will fix that.
  • David Ranieri
    David Ranieri almost 8 years
    It seems that you are answering another question.