Reputation: 90
Enter number of integers to be stored : 5
Enter 5 integers:
1 2 3 4 5
There are 2 even numbers in the set. There are 3 odd numbers in the set.
Even numbers:
2
4
Odd numbers:
1
3
5
Output:
Sum of Odd Numbers is 51
Sum of Even Numbers is 6
--------------------------------
Process exited after 3.389 seconds with return value 0
Press any key to continue . . .
This is the code:
#include <stdio.h>
int main()
{
int N, n;
printf("Enter number of integers to be stored : ");
scanf("%d", &N);
int count[N];
printf("\nEnter %d integers: \n", N);
for(int n=0;n<N;n++)
{
scanf("%d", &count[n]);
}
//Even and Odd Counter
int even_counter=0, odd_counter=0;
for(n=0;n<N;n++)
{
//even_counter
if(count[n]%2==0)
{
even_counter++;
}
//odd_counter
else
{
odd_counter++;
}
}
printf("\nThere are %d even numbers in the set.", even_counter);
printf("\nThere are %d odd numbers in the set.\n", odd_counter);
//Sorting of Even and Odd
int i=0;
printf("\nEven numbers: \n");
for(n=0;n<N;n++)
{
if(count[n]%2==0)
{
printf("%d\n", count[n]);
}
}
printf("\nOdd numbers: \n");
for(n=0;n<N;n++)
{
if(count[n]%2==1)
{
printf("%d\n", count[n]);
}
}
//Sum of Odd and Even Values
//EvenSummation
int even_lister[i], sumEven, odd_lister[i], sumOdd;
for(n=0;n<N;n++)
{
if(count[n]%2==0)
{
even_lister[i]=count[n];
sumEven+=even_lister[i];
}
else //OddSummation
{
int odd_lister[i], sumOdd, i=0;
odd_lister[i]=count[n];
sumOdd+=odd_lister[i];
}
}
printf("\nSum of Odd Numbers is %d", sumOdd);
printf("\nSum of Even Numbers is %d", sumEven);
}
What's wrong with my program? I've tried everything I knew :( The odd value is giving strange results.
Upvotes: 1
Views: 294
Reputation: 385144
Here's the part where you calculate the sum of even numbers, which works:
if(count[n]%2==0)
{
even_lister[i]=count[n];
sumEven+=even_lister[i];
}
Now here's the part where you calculate the sum of odd numbers, which doesn't:
else //OddSummation
{
int odd_lister[i], sumOdd, i=0;
odd_lister[i]=count[n];
sumOdd+=odd_lister[i];
}
Do you see the difference? There's an extra line in the second one. In the version that doesn't work, you re-declared some local variables and assigned your values to those local variables. That's why it doesn't work. You didn't do anything with the "original" variables in a higher-up scope that you later print to the screen.
Furthermore, both parts are actually broken because you never initialised either sumEven
or sumOdd
to 0
, so their values are unspecified, and you're adding to unspecified values to create other unspecified values. Whether this bug creates an observable symptom or not is undefined.
Another problem is that you declare your arrays like this:
int even_lister[i];
but i
is a variable that you set to 0
and never changed. So those arrays have zero length and every single access to them is illegal. Perhaps you meant to use n
instead?
You really need to turn on your compiler warnings and read your code more carefully.
Upvotes: 7