How to code for cascading multiplexers?
It becomes much easier if you start thinking in binary.

If you have an 8 bit multiplexer connected to four 8 bit multiplexers that gives you 32 inputs. Four of the inputs on the "master" multiplexer are unused and can be ignored.

You have 32 inputs. That's inputs numbered 0 to 31. In binary that equates to, in full,

0 = 000000   8 = 001000  16 = 010000  24 = 011000
1 = 000001   9 = 001001  17 = 010001  25 = 011001
2 = 000010  10 = 001010  18 = 010010  26 = 011010
3 = 000011  11 = 001011  19 = 010011  27 = 011011
4 = 000100  12 = 001100  20 = 010100  28 = 011100
5 = 000101  13 = 001101  21 = 010101  29 = 011101
6 = 000110  14 = 001110  22 = 010110  30 = 011110
7 = 000111  15 = 001111  23 = 010111  31 = 011111


I have laid it out like that especially so that you see a pattern occurring. Four columns with 8 rows. Four slave multiplexers with 8 inputs. A perfect match. Each column has bits that are distinct to that column. Each row has bits that are unique to that row.  So you could split those bits up and know that the left-hand three bits indicate the column, and the right-hand three bits indicate the row. Between the two it's a unique location in the table.

The same applies to the multiplexers.  The left-hand three bits indicate which slave multiplexer to use, the right-hand three bits which input to use on the selected multiplexer.

So you can loop through each of the 32 inputs with a single loop and examine the individual bits of the input number and apply those bits directly to the select outputs to control the multiplexers - the left-hand bits to the master to select which slave to use, and the right-hand bits to the slaves to select which input to use.

So you have:

for (int i = 0; i &lt; 32; i++) {
    digitalWrite(M_S2, i &amp; 0b100000);
    digitalWrite(M_S1, i &amp; 0b010000);
    digitalWrite(M_S0, i &amp; 0b001000);
    digitalWrite(S_S2, i &amp; 0b000100);
    digitalWrite(S_S1, i &amp; 0b000010);
    digitalWrite(S_S0, i &amp; 0b000001);

    delay(1);

    int reading = analogRead(Z);
    Serial.print("Input ");
    Serial.print(i);
    Serial.print(": ");
    Serial.println(reading);
}


The i &amp; 0b000001 etc performs the same function as bitRead() but is more explicit using a mask that is far more visual as to what it achieves.

I also include a tiny delay after setting the multiplexers up so as to ensure they have settled into their new settings properly before reading. It shouldn't be needed, but it doesn't hurt.