Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C++ FUNCTION which counts the number of non-zero numbers in a list and t

ID: 3771392 • Letter: W

Question

Write a C++ FUNCTION which counts the number of non-zero numbers in a list and the number of zeros in the list, and returns true if there are more non-zero numbers than zeros and false otherwise. If the list contains no numbers, then the function should return false.

The function has two parameters, an array of type double and an integer representing the number of elements in the array. The function should return a value of type bool.

the solution is:

bool moreNonZeros(double list[], int size)
{
bool nzMore = false;
if (size > 0)
{
int nzcount = 0;
for (int i = 0; i < size; i++)
{
if (list[i] != 0)
{
nzcount++;
}
}
if (nzcount > (size – nzcount))
{
nzMore = true;
}
}
return nzMore;
}

i dont understand why it is this or how it works, could someone please explain it? thanks

Explanation / Answer

bool moreNonZeros(double list[], int size)
{
bool nzMore = false; // non_zero_more is set false
if (size > 0) // Checking whether the list contains any element , else return nzMore which is false.
{
int nzcount = 0; //non zero count set to 0
for (int i = 0; i < size; i++) // for loop to check the entire elemnts in the list
{
if (list[i] != 0) // if the element is not zero , non-zero count incremented
{
nzcount++;
}
}
if (nzcount > (size – nzcount)) // zero count = size - non zero count , here checking non zero count > zero count.
{
nzMore = true; // if yes then non zero more is set true.
}
}
return nzMore; // non zero more value is returned.
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote