Home > OS >  Why does an error occur when I modulus the value in array?
Why does an error occur when I modulus the value in array?

Time:11-20

may i know what exactly have gone wrong in this code? cause the output of the even number is not what i expected if i input the value in the comment

//int number[10]={0, 2, 5, 8, -2, 0, 6, 4, 3, 1};
int number[10], divided_number[10], total_odd_numbers, total_even_numbers, a;
for(int i=0;i<=9;i  ){
    a=i 1;
    cout<<"Number "<<a<<": ";
    cin>>number[i];
    
}
for(int i =0; i<=9; i  ){
    cout<<*(number i)<<"  ";
}
cout<<endl;
for(int i=0;i<=9; i  ){
    divided_number[i]=number[i]%2;
    if(divided_number[i]!=0){
        total_odd_numbers  =1;
    }
    else if (divided_number[i]==0){
        total_even_numbers  ;
    }
}
for(int i=0;i<=9; i  ){
    cout<<*(divided_number i)<<"  ";
}
cout<<"\n Total odd number: "<<total_odd_numbers<<endl;
cout<<"\n Total even number: "<<total_even_numbers<<endl;

CodePudding user response:

The problem is that total_odd_numbers and total_even_numbers are not initialized before being accessed. This is called undefined behavior. In this case, the program will take whichever trash data is already in the memory assigned to those variables and just use it as-is (and so, of course, the output may or may not be correct, depends on what's in that memory at the time of assignment).

It should be noted that :

Using an unitialized value is, by itself, not undefined behavior, but the value is simply indeterminate. Accessing this then is UB if the value happens to be a trap representation for the type. Unsigned types rarely have trap representations, so you would be relatively safe on that side.

Modified program:

#include <iostream>
using namespace std;

int main()
{
    int number[10]={0, 2, 5, 8, -2, 0, 6, 4, 3, 1};
    int divided_number[10], total_odd_numbers = 0, total_even_numbers = 0, a;

    for(int i =0; i<=9; i  ){
        cout<<*(number i)<<"  ";
    }
    cout<<endl;
    for(int i=0;i<=9; i  ){
        divided_number[i]=number[i]%2;
        if(divided_number[i]!=0){
            total_odd_numbers  =1;
        }
        else if (divided_number[i]==0){
            total_even_numbers  ;
        }
    }
    for(int i=0;i<=9; i  ){
        cout<<*(divided_number i)<<"  ";
    }
    cout<<"\n Total odd number: "<<total_odd_numbers<<endl;
    cout<<"\n Total even number: "<<total_even_numbers<<endl;
}

Output:

0  2  5  8  -2  0  6  4  3  1
0  0  1  0  0  0  0  0  1  1
 Total odd number: 3

 Total even number: 7

And, of course, the code could be cleaned up much further:

int number[10]={0, 2, 5, 8, -2, 0, 6, 4, 3, 1};
int odds = 0, evens = 0;

for(int i=0;i<=9; i  )
{
    int left = number[i] % 2; cout << left << " ";
    if (left != 0) {odds  ;} else {evens  ;}
}

cout<<"\nTotal odd number: "<<odds<<'\n'<<"Total even number: "<<evens;

Further reading:

And also:

  • Related