-4
#include <iostream>
using namespace std;
int main()
{
int i,t,x[20], even, odd, prime; 
cout << "Enter 20 integer numbers from 0 to 99: "<<endl;
for (i=1;i<=20;i++)
{
    cout << "Input " << i <<":";
    cin >> x[i];
}
cout << "\nPrime numbers are: " << endl ; 
prime=1;
for (i=2; i<=20 ; i++)
{
    for(t=2;t<x[i];t++)
    {
        if(x[i]%t==0)
        {
            prime=0;
        }
    }
    if(prime==1)
    {
        cout << x[i] << endl;
    }
    prime=1;
 }
 for(i=1; i<=20; i++) // this is where i have problem.
 {
    if(x[i]% 2 == 0)
    {
        even++;
    }
    else 
    {
        odd++;
    }
 }
 cout << "Number of odd numbers: " << odd << "\n";
 cout << "Number of even numbers: " << even << "\n";
 return 0 ;  
 }

When i compile it shows even (40) and odd (10) for input of 0 till 19. Where it should show even 10(including the 0) and odd (10). Im not sure where am i doing it wrongly. I hope someone can help me improve the code.

1 Answers1

0

Variables even and odd are never set to a known value, so you are not formally allowed to read from them. Doing so invokes that most infamous Standardese concept: undefined behaviour. So the values of these variables could be right or could be wrong; the variables and all code trying to read them could be optimised entirely out of your program; or anything can happen. You cannot rely on these variables doing anything right. All attempts to read them make your program ill-formed, so now it can do anything, including things you would never have imagined.

You should search for the abundant background info about these concepts, but I like to think I made a fairly decent summary here: https://stackoverflow.com/a/38150162/2757035

Also, as Thomas points out in the comments, you appear not to understand how array indexing works: Indexes are 0-based. So, int i[20] declares 20 elements numbered from 0 to 19. You try to access index 20, which is not part of the array and hence is more undefined behaviour.

Community
  • 1
  • 1
underscore_d
  • 5,331
  • 3
  • 29
  • 56