Why it is not showing correct output? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why it is not showing correct output?

I tried to create a program that can count words in a sentence. #include <stdio.h> #include <string.h> int main() { char my_sentence[]= "Hello how are you"; int length; length = strlen(my_sentence); int space = 0; for (int i= 0; (i < length); i++){ if (my_sentence[i] == '\0'){ space += 1; } } int total_word; total_word =space + 1; printf("%d",total_word ); return 0; } Ps: I learned python before learning C. So i tried to adapt my understanding of for loop in C from python knowledge.

3rd Dec 2021, 3:23 PM
Desert_fox
Desert_fox - avatar
5 Answers
+ 7
A whitespace character ' ' differs from the null character '\0'. Use the former for comparison instead. https://stackoverflow.com/questions/3696298/wondering-in-c-strings-null-white-spaces
3rd Dec 2021, 3:29 PM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Guess I confused " " with "\0". Thanks it solved the problem.
3rd Dec 2021, 3:32 PM
Desert_fox
Desert_fox - avatar
+ 2
for (int i= 0; i<length; i++) if (my_sentence[i]==' ') space += 1; // Keep learning & happy coding :D
3rd Dec 2021, 10:13 PM
SoloProg
SoloProg - avatar
+ 2
In C and in C++ single quotes identify a single character, while double quotes create a string literal. 'a' is a single a character literal, while "a" is a string literal containing an 'a' and a null terminator (that is a 2 char array).
3rd Dec 2021, 10:29 PM
SoloProg
SoloProg - avatar
0
temp=int(input()) if temp >= 100: print("boiling") did I miss sam thing her
12th Jul 2022, 8:00 PM
Ferid Abdurahman
Ferid Abdurahman - avatar