0

I have an array (nchar[12]) and I wrote this code to print it as vertical columns composed of "X"'s.

I first wrote a version with an accumulator and a while-loop and it worked fine, but it only could print colums as long as a given limit.

Then I tried to write it as a state machine, but the output is just an endless series of blank spaces.

I declared status as an int and assigned a value of 1 to it, then:

while (status = 1) {
    for (i = 1; i <= 12; ++i) {
        status = 0;
        if (nchar[i] > 0) {
            printf("  X");
            --nchar[i];
            status = 1;
        }
        else
            printf("   ");
    }

It should stop when it doesn't find any value to print for the last processed line, but it just goes on forever and I don't understand why.

maja
  • 697
  • 5
  • 18
  • 1
    if you declare nchar[12] then you must loop from 0 to 11, not from 1 to 12. – Giacomo Degli Esposti Jan 30 '15 at 15:41
  • 1
    I'm a little worried about the loop and the index variable `i` starting at `1` and going up to *and including* `12`. I'm worried about that because arrays are indexed, as you should know, from zero to size minus one. So if `nchar` is an array of size 12 the indexes goes from `0` to `11`. – Some programmer dude Jan 30 '15 at 15:42
  • As for how to solve your problem, learn to use a debugger, because then you can use it to step through your code line by line to see what happens. – Some programmer dude Jan 30 '15 at 15:42
  • I'm sorry, the array goes up to 13, then Ihave it read from 1 to 12 that's the span I need my output from (the array is written by storing the number of words of a certain length, thus excluding words woth zero letters. – maja Jan 30 '15 at 16:06

1 Answers1

3

The loop never ends because = is the assignment operator not == which is the comparision operator. You probably want

while (status == 1)

Or simply

while (status)

instead of

while (status = 1)

Also if you have an array declared as

type nchar[12];

then the valid indices for it start from 0 and end at 11. So, your loop should start with i=0 and should loop until i<12 becomes false.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
  • 1
    To never again fail because of such an annoying mistake, you might like to go for Yoda-Conditions: http://en.wikipedia.org/wiki/Yoda_conditions @maja – alk Jan 30 '15 at 16:08
  • thank you, it really was as simple as that. || as for the array, I wrote 12 but the array is really set to 13, then I use the last 12 entries because of the nature of the prgram. – maja Jan 30 '15 at 16:09