Which cycle is better?

Start new to C here; I would like to ask which of the following 2 codes is best for printing odd integers between 1 and a given number?

// Precond: n > 0
void print_odd_integers(int n)  {
    int i;
    for (i=1; i<=n; i+=2)
        printf("%d ", i);
    printf("\n");
}

// Precond: n > 0
void print_odd_integers(int n)  {
    int i;
    for (i=1; i<=n; i++)
        if (i%2 != 0)
            printf("%d ", i);
    printf("\n");
}

If this cannot be said to be clearly “better,” what are the different trade-offs between versions?

+4
source share
5 answers

Use First Loop if nit is not an extreme case of the type INT_MAX, and also when it istarts with an odd integer, since it already skips half iterations of the number.

Else use Second Loop because the first will become an infinite loop if n = INT_MAX.

+3
source

.
:

-

- (, , ,...) , .

- O (n). , . , , , .

  • , undefined, . . , . i INT_MAX, i==INT_MAX-1 i==INT_MAX
+2

, , .

, if, . .

0

undefined, n == INT_MAX - .

  • ( ) , , .

    for, :

    void print_odd_integers(int n)  {
        int i;
        for (i = 1; i <= n; i++) {
            if (i % 2 != 0)
                printf("%d ", i);
        }
        printf("\n");
    }
    

Note that both loops will output a space after the last number before the new line, which may be incorrect.

You can solve both problems with one additional test:

void print_odd_integers(int n)  {
    for (int i = 1; i <= n; i += 2) {
        printf("%d", i);
        if (i == n)
           break;
    }
    printf("\n");
}
0
source

The second solution is the "professional" way.

One thing you could change is Layout:

void print_odd_integers(int n)  
{
    int i;
    for (i=1; i<=n; i++)
    {
        if (i%2 != 0)
        {
            printf("%d\n", i);
         }
    }
    printf("End.\n");
    system("Pause"); //So you can see what you did :)
}

Good luck :)!

-3
source

Source: https://habr.com/ru/post/1684934/


All Articles