-1

this code is an exercise in array

int L;
int P=0;
int N=0;
int zero=0;
cout<<"Enter The Size of Array : "<<"                   'Note that it has to be bigger than 0'\n";
cin>>N;

here I determine the size of the array

int z[N];
int n=sizeof(z)/sizeof(z[0]);
cout<<"The Number of elements in this array is : "<<n<<"\n";

I put the value of each elements

for(int i=0;i<N;i++){
    cout<<"chose the "<<i<<" element : ";
    cin>>z[i];
}

this loop for looking in the array and check if its positive, negative or zero

for(int i=0;i<N;i++){
    if (z[i] > 0){
        P=P+1;
    }
    else if (z[i] < 0){
        N=N+1;
    }
    else{
            zero=zero+1;
    }

}

here to print the result

cout<<"The Number of Positive elements is : "<<P<<"\n";
cout<<"The Number of Negative elements is : "<<N<<"\n";
cout<<"The Number of zero elements is : "<<zero<<"\n";

the issue is that program ran without errors but it gives wrong results

adham R
  • 1
  • 1
  • 2
    Note that [VLAs are not part of the C++ standard](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard). The length of an array must be a compile-time-constant, for dynamic arrays `std::vector` is usually the best solution. – Lukas-T Apr 03 '21 at 16:09
  • Have you tried running your code line by line in a debugger while monitoring the values of all variables, in order to determine at which point your program stops behaving as intended? If you did not try this, then you probably 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 Apr 03 '21 at 16:25
  • *the issue is that program ran without errors but it gives wrong results* -- Then that means the program ran with errors. Just because a program runs doesn't mean what you coded is correct. Then this: `int z[N]; int n=sizeof(z)/sizeof(z[0]);` -- since `int z[N]` is not standard C++, how do you know that the `sizeof` trick will work? The `sizeof` is a compile-time constant, so how will it know at runtime what `z[N]`'s size is? Forget about this and simply use `std::vector` (as already mentioned). Then the size is simply the `size()` member function of vector. – PaulMcKenzie Apr 03 '21 at 16:29
  • Calculating the size at all is silly, it's explicitly entered. – sweenish Apr 03 '21 at 16:35

1 Answers1

1

You seem to be using your variable N for both the size of the array and the amount of negative numbers. That's confusing and bound to give you wrong results.

Create an extra variable for your array size. Maybe name it array_size or something similar, so you know what the value means.

nvoigt
  • 75,013
  • 26
  • 93
  • 142