Вопрос

Basically what I'm trying to ask is, is there anyway to read ahead in an array so that you could create a 'case' for it.

For ex: you array has only integers such as: 0 0 0 0 4 0 1 0 0 0 0 0 0 0 0 0 0 0 0 3

and what you want to try to do is create a coutdown till the next non zero number. Basically display the countdown. Is there any way to do this?

Это было полезно?

Решение

This code:

#include <stdio.h>

int main(void)
{
    int array[] = { 0, 0, 0, 0, 4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, };

    int a_size  = sizeof(array) / sizeof(array[0]);

    int i = 0;
    while (i < a_size)
    {
        if (array[i] == 0)
        {
            int j;
            for (j = i; j < a_size; j++)
                if (array[j] != 0)
                    break;
            printf("%d\n", j - i);
            i = j;
        }
        else
            i++;
    }
    return 0;
}

produces this output:

4
1
12

If that's what you want, that's roughly what you need. If it is not what you want, you need to explain more clearly what it is that you want.


Revised code for revised expected output:

#include <stdio.h>

int main(void)
{
    int array[] = { 0, 0, 0, 0, 4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, };

    int a_size  = sizeof(array) / sizeof(array[0]);

    int i = 0;
    while (i < a_size)
    {
        if (array[i] == 0)
        {
            int j;
            for (j = i; j < a_size; j++)
                if (array[j] != 0)
                    break;
            int k = j - i;
            while (k > 0)
                printf(" %d", k--);
            i = j;
        }
        else
        {
            printf(" '");
            i++;
        }
    }
    putchar('\n');
    return 0;
}

Revised output:

 4 3 2 1 ' 1 ' 12 11 10 9 8 7 6 5 4 3 2 1 '
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top