-1

The question goes as follows:

Using a for loop ended with writing 0, compute sum of even numbers, sum of odd numbers,

I have no idea why my code isn't working:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int i = 0, num[i], sum, even, odd;
        
    for (;;) {
        printf("Write a number: ");
        scanf("%d", &num[i]);
        if (num[i] == 0) {
            break;
        }
        if (num[i] % 2 == 0) {
            even += num[i];
        } else
            odd += num[i];
            i++;
        }
       
        printf("Sum of even is: %d\n", even);
        printf("Sum of odd is: %d", odd);
        return 0;
    }
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Younis
  • 13
  • 1
  • 6
    `int i=0,num[i]` is not going to end well. – Fred Larson Jun 02 '22 at 18:06
  • 1
    How big is this array? `int i=0,num[i]` `sum`, `even`, and `odd` are not initialized. You should set them to 0. You don't even need an array for this if you don't need the numbers later. Just use a single `int` to read the data and calculate it as you go. – Retired Ninja Jun 02 '22 at 18:07
  • I fixed your indenting – Hogan Jun 02 '22 at 18:08
  • "i have no idea why my code isn't working" -- Have you tried running your code line by line in a debugger while monitoring the values of all variables, in order to determine in which line your program stops behaving as intended? If you did not try this, then you may want to read this: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/12149471) You may also want to read this: [How to debug small programs?](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Andreas Wenzel Jun 02 '22 at 18:16

1 Answers1

6

This declaration of an array with zero elements

int i=0,num[i],sum,even,odd;

invokes undefined behavior.

Actually there is no any reason to use an array for this task.

Also you need to initialize the variables even and odd. Also the variable sum is not used.

The program can look for example the following way

#include <stdio.h>

int main( void ) 
{
    int even = 0, odd = 0;

    while ( 1 )
    {
        printf( "Enter a number (0 - stop): " );

        int num;

        if ( scanf( "%d", &num ) != 1 || num == 0 ) break;

        if (num % 2 == 0)
        {
            even += num;
        }
        else 
        {
            odd += num;
        }
    }

    printf( "Sum of even is: %d\n", even );
    printf( "Sum of odd is: %d", odd );
}

If you are going to use an array then you need either to declare an array with a fixed number of elements and restrict the number of inputs. Or you need to allocate and reallocate a dynamically allocated array. But this makes your program more complicated with a redundant code.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335