-5

I am reading The C Programming Language 2nd Edition. I am doing the 2.10 in a tutorial introduction. I have to write a program about arrays. It is supposed to count digits, white spaces and others. This is the program:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int c, i, nwhite, nother;
int ndigit[10];



nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;

while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
    ++ndigit[c - '0'];
else if (c == ' ' || c == '\n' || c == '\t')
    ++nwhite;
else
    ++nother;

printf("digits =");
for (i = 0; i < 10; ++i)
    printf(" %d ", ndigit[i]);
printf(", white space = %d, other = %d\n", nwhite, nother);
return 0;
}

According to the book, the output of the program by itself is

digits = 9 3 0 0 0 0 0 0 0 1, white space = 123, other = 345

I have 2 questions:

  1. How will the program output by itself without me doing the CTRL+Z?
  2. When I do it manually the output is not right. Please see if I made a mistake in the code.

The output I get is

digits =, white space = 0, other = 0

2 Answers2

4

This:

printf("digits =");
for (i = 0; i < 0; ++i)
    printf(" %d ", ndigit[i]);

has a broken middle part in the for loop's header; i < 0 will not be true (ever!) so the loop will not run.

unwind
  • 391,730
  • 64
  • 469
  • 606
2
for (i = 0; i < 0; ++i)

This is wrong.

ouah
  • 142,963
  • 15
  • 272
  • 331