I have written two codes for splitting sentences to words, one of which worked while other one didn't. Only difference is in the if condition under for loop. First one gave no output. While second one is giving expected output. Please explain logically, don't teach DeMorgan Laws. I have purely applied my logic in both of them which I think is also correct in first code.
NOT WORKING ONE:
#include <stdio.h>
void main(void){
int i=0, m=0, n=0, j, l=0;
char sen[500], wrd[500][500];
printf("Input a sentence:\n");
gets(sen);
while(sen[i]!='\0'){
l++;
i++;
}
for(i=0;i<=l;i++){
if(sen[i] != ' '||sen[i] != '\0'){ //Here is the difference.
wrd[m][n]=sen[i];
n++;
}
else{
wrd[m][n]='\0';
puts(wrd[m]);
printf("\n");
m++;
n=0;
}
}
}
WORKING ONE:
#include <stdio.h>
void main(void){
int i=0, m=0, n=0, j, l=0;
char sen[500], wrd[500][500];
printf("Input a sentence:\n");
gets(sen);
while(sen[i]!='\0'){
l++;
i++;
}
for(i=0;i<=l;i++){
if(sen[i] == ' '||sen[i] == '\0'){ //Here is the difference.
wrd[m][n]='\0';
puts(wrd[m]);
printf("\n");
m++;
n=0;
}
else{
wrd[m][n]=sen[i];
n++;
}
}
}
Only difference is in the if condition of for
loop.
First one have: if(sen[i] != ' '||sen[i] != '\0')
Second have: if(sen[i] == ' '||sen[i] == '\0')