detect zero in array and print it out

Hi guys! I'm having problem with my code as it does not print out the correct number of zeroes. Stuck with this for like 2 days! :( I have to use a recursive function and dynamic arrays. Below is my code. I think my problem is in traversing through the array. Thanks in advance for any help. (Btw pls ignore the switch case in my main function. the other functions are not shown here)

#include<iostream>

using namespace std;

int detectZero (int *a, int zero, int index, int cols) {
// base case
if (index == cols - 1) { // if index is at end of array
cout << "Number of Zero's in the array is: " << zero <<endl;
return 0; // to end the fuction
}

// general case
else {
if (a[index] == 0){ // i think this is my problem but i cant seem to find the solution. i tried a[0][index] but
// it doesnt work too. error list says i need a pointer or something
zero += 1; // to update the variabl zero and keep track the numbers of zero's
return detectZero (a, zero, index += 1, cols); // function calls itself but with updated zero and index
}
else {
return detectZero (a, zero, index += 1, cols); // function calls itself but with updated index
}
}
}


void q4 () {
int * a[1]; // half dynamic array
int cols, iNum;
int index = 0; // to traverse in the array
int zero = 0; // number of zeroes

cout << "How many numbers do you want to enter?" <<endl;
cin >> cols; // array size i guess

a[0] = new int[cols]; // creates the new cols of array

// this for loop is for inputting numbers
for (int i = 0; i < cols; i++) {
cout << "Enter number: " <<endl;
cin >> iNum;
a[0][i] = iNum;
}

// print out the inputted numbers
for (int i = 0; i < cols; i++){
cout << a[0][i] << ", ";
}

cout <<endl;
detectZero (*a, zero, index, cols); // recursive function
}
// end of q4

void main (void) {
int choice;

cout << "Hata's Data Struct and Algorithm Assignment 1" <<endl
<< "Choose a question (1, 2, 3, 4, 5, 6)" <<endl;

cin >> choice;

switch (choice) {
case 1:
q1 ();
break;
case 2:
q2 ();
break;
case 3:
q3 ();
break;
case 4:
q4 ();
break;
}
}
Last edited on
Looks like the number of zeros would be off by 1 if the last value entered was 0. You not checking the last element in the array for zero

In detectZero Change
1
2
3
if (index == cols - 1) { // if index is at end of array
to
if (index == cols ) { // if index is at end of array 
Oh thank you it works! But I'm a little bit confused. If i declare that an array has size 6 for example, if i want to access the array shouldn't it be array[0], array[1] and all the way to array[5] but not array[6]?
Yes. 0 through 5.
Your if block is not accessing the array, only the else block is so you are ok.
You want the else block executed for every element in the array, the if block is what terminates it.
oh..i get it now! Thank you so much for your help! :D Much appreciated :)
Topic archived. No new replies allowed.