How does this read() function work?

The following read() function receives the integers provided by the user. I especially do not get it how the --n; line prevents the counting of the 0.

1
2
3
4
5
6
7
8
9
void read (int a[], int& n);
cout<< “Enter integers. Terminate with 0: \n”;
n=0;
do{
cout<< “a[“<<n<<“]: “;
cin >> a[n];
}
while (a[n++] !=0 && n<MAXSIZE );
--n; //don't count the 0 


The original code is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

using namespace std;

void read(int [], int&);
void print( int [], int);
long sum (int [], int);
const int MAXSIZE=100;

int main(){
    int a[MAXSIZE]={0}, size;
    read (a,size);
    cout << "The array has " <<size <<" elements: ";
    print (a,size);
}

void read(int a[], int& n){
    cout <<"Enter integers. Terminate with 0: \n";
    n=0;
    do{
        cout << "a ["<<n<<"]: ";
        cin >> a[n];
    }
    while (a[n++] !=0 && n<MAXSIZE);
    --n; //don't count the 0
}
void print (int a[], int n){
    for (int i=0; i<n; i++)
        cout <<a[i]<<" ";
    cout<<endl;
    
}
Last edited on
Well you have to consider what the a[n++] !=0 is doing as well, especially when the loop exits.
you count the zero and then 'uncount' it.
so if you have 1 2 3 0
it counts to 4, subtracts 1, and cooks up the answer of 3.

there is probably a way to write it cleaner.
does it give the correct n if you put in maxsize items? Try it, set maxsize to something small like 5 and test it if you don't see what it will do... if n == maxsize, what does line 22 do? (I am trying to tell you the code is probably bad...)

Last edited on
@jonnin Thanks, I understand it now. So the 0 refers to the same zero the user enters for stopping the loop.
But why is n initially equaled to 0 in the read() function?
there is probably a way to write it cleaner.
does it give the correct n if you put in maxsize items? Try it, set maxsize to something small like 5 and test it if you don't see what it will do... if n == maxsize, what does line 22 do? (I am trying to tell you the code is probably bad...)


As you said the program gives the wrong result when n==maxsize. The example is taken from a book. Thanks for the hint. At present, though, with my current knowledge of cpp coding, I have no clue on how to improve it.
the first thing about improving code is to fix screw ups and make it RIGHT.
making it prettier or faster comes after that.
can you fix it so it does not screw up?
Side note: always question, books have as much bugged up code as anything else.
Topic archived. No new replies allowed.