Hello guys! I have some trouble with that "Do you want to continue" thing in C. I am begginer. Well my problem is to fix this one:
.....

int sum_count_arithmeticaverage()
{
    int n = 0;
    char answer;
    int array[1024];
    int sum = 0, count = 0, arithmeticaverage;
    int i = 0;
    int z = 0;

    do{
        printf("Write element: ");
        scanf_s("%d", &array[i]);
        printf("Do you want to continue adding elements of the array? <Y/N> ");
        scanf_s("%ch", &answer);
        fflush(stdin);
        array[n];
        } while ((answer == 'y') || (answer == 'Y'));
    for (i = 0; i < n; i++)
    {
        sum = sum + array[i];
        count++;
        arithmeticaverage = sum / n;
    }
    printf("| Sum=%d | Count=%d | Arithmetic average=%d |\n\n", sum, count, arithmeticaverage);
    printf("->Even numbers in array are<-\n\n");
    for (i = 0; i < n; i++)
    {
        if (array[i] % 2 == 0)
        {
            z = array[i];
            printf("array[%d]=%d\n\n", i, z);
        }
    }
    printf("->Odd numbers in array are<-\n\n");
    for (i = 0; i < n; i++)
    {
        if (array[i] % 2 != 0)
        {
            z = array[i];
            printf("array[%d]=%d\n\n", i, z);
        }
    }
    return 0;
}

My idea is to make the array sum = "n" then the program to ask us do you want to continue, after we say "y" or "Y" to enter the next member of the array and so on... When we enter a word that is not "y" or "Y" the program stops.

scanf_s("%ch", &answer);

Should be just "%c", not "%ch".

fflush(stdin);

Nonstandard. fflush() is guarenteed to work only with stdout and other output streams. Some compilers support stdin, but that won't work with all compilers. When learning to program it's best to stay with standard C functions and not compiler-implementations.

line 12: you need to increment the value of i so that it will point to the next element of the array. You can do that in the same line as line 12 or on another line before the end of the loop, either is correct
scanf_s("%d", &array[i++]);

line 16: array[n];

That is a do-nothing statement. You might as well delete it.

line 18: What's the value of n at that point? Answer: 0, as initialized on line 3. I think you need to set n = i just before line 18 and after line 17.

lines 18-23: Too much work going on there. Think how you would calculate the average of several numbers with pencil & paper -- you don't calculate the average every time you add a value to the sum so why are you doing that in this loop?

You might as well delete variable count because it's final value is the same as n. Then move line 22 down so that it's outside the loop.

Edited 3 Years Ago by Ancient Dragon

scanf_s("%ch", &answer); this statement at line 14 has problem because it should be either %c or %s.

This article has been dead for over six months. Start a new discussion instead.