F
F
Firetheestle2015-09-30 21:18:26
C++ / C#
Firetheestle, 2015-09-30 21:18:26

How to find the last null element in an array?

Good day! I am trying to solve a problem with arrays (find the average of all positive array elements after the last zero array.)
There was a problem with finding the last zero element in the array

for (i=30;i!=0;i--)
    {
      if (A[i]==0)
      {
        n1=i;
        n2=i;
        break;
             }
    }

variable n2 entered for verification, but it is always equal to 30
Tell me what's wrong? I would like hints and not a ready-made solution.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
abcd0x00, 2015-10-01
@Firetheestle

You have to search from the end. (There may be no elements at all after the last null.)
If there are 30 elements in the array, then the
Zero index is considered because all elements of the array can be non-zero.

V
Vladimir Martyanov, 2015-09-30
@vilgeforce

Use a debugger if your religion doesn't forbid...

A
abs0lut, 2015-09-30
@abs0lut

avg. arith-something of all positive array elements after the last null array

Do you have a 2D array?

X
Xavius, 2015-09-30
​​@Xavius

Do you just need the arithmetic mean? Do you know the size of the array? If yes, make 2 variables: an accumulator and a counter, run through the array and add all elements greater than zero to the accumulator, and increase the counter by 1, then divide the resulting value in the accumulator by the value in the counter. Don't forget to divide by 0.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question