Terryn Terryn - 3 months ago 20
C Question

How to select multiple elements in an array with C?

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!

Answer

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");
}