there while reading the K&R I got stuck at an example problem.
Here the aim of the program is to count the newlines, new words and the number of characters entered in the input. The code given in the book is :
#include <stdio.h>
#define IN 1
#define OUT 0
void main(){
int c, nl, nw, nc, state;
state = OUT;
nl=nw=nc=0;
while ((c = getchar()) != EOF)
{
++nc;
if (c == '\n')
++nl;
if(c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if(state == OUT){
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}
- It might look silly but sorry I'm new to C. I learnt that if the 'if' statement's condition gets true it simply doesn't check any other else if & else statements condition, only executes it's body and thus doesn't execute the bodies of other else & else if statements. But, in the code above (line:16) after checking the input with conditions of new word, it follows with an else if statement. And increments the nw in it's body. But how can else if gets executed if the if statement's condition is true.
Aucun commentaire:
Enregistrer un commentaire