lundi 2 novembre 2020

Else clause with for loop in C?

Unlike Python, C doesn't seem to support the else clause for loops, So, how does one achieve this functionality with C (Without using continue or ternary operator)? (Else clause shouldn't be executed multiple times).

So my question is, In the second example, else will be executed every time until 6 is found, how to avoid this multiple executions on else clause?

#include <stdio.h>

int main(int argc, char const *argv[])
{

    int arr[] = {1, 3, 5, 6, 7, 9};

    for (int i = 0; i < 5; i++){

        if (arr[i] % 2 != 0)
        {
            //do something
            continue;
        }

        else
        {
            //do else part 
        }

}
// do something

    return 0;
}

{

    int arr[] = {1, 3, 5, 6, 7, 9};

    for (int i = 0; i < 5; i++){

        if (arr[i] % 2 == 0)
        {
           //do somthing
           break;
        }

        else
        {
            //do else part
            
        }
}
//do something
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire