0

[check the code] : why does code 1 and code 2 prints 13 and 14 characters respectively? Why different? They should have the same

[check the code] : why does code 1 and code 2 prints 13 and 14 characters respectively? Why different? They should have the same value right since both of them takes '\0' input at last. Please Explain. CODE 1 : #include <stdio.h> int countLength(char arr[]); int main() { char name[] = "Anirban Mitra"; // 13 characters clearly printf("the no of characters are : %d", countLength(name)); return 0; } int countLength(char arr[]) { int count = 0; for (int i = 0; arr[i] != '\0'; i++) { count++; } return count; } PRINTS : the no of characters are : 13 CODE 2 : #include <stdio.h> int countLength(char arr[]); int main() { char name[100]; fgets(name, 100, stdin); //INPUT IS SAME AS THE PREV CODE (Anirban Mitra) printf("the no of characters are : %d", countLength(name)); return 0; } int countLength(char arr[]) { int count = 0; for (int i = 0; arr[i] != '\0'; i++) { count++; } return count; } PRINTS : the no of characters are : 14

15th May 2022, 10:49 AM
blueshipswims
blueshipswims - avatar
4 Antworten
+ 3
By using fgets(), the input string will include the newline character that the user typed at the end, before the terminating null, so it will have one more character than the printable characters.
15th May 2022, 11:18 AM
Brian
Brian - avatar
+ 2
Brian thanks brian... understood... i never really thought of 'new line' as a character , stupid me :( but now i know thanks again
15th May 2022, 11:55 AM
blueshipswims
blueshipswims - avatar
0
First code is already defied char array which have total number of characters 13 and in print you calling function countLenght so control will jump to countLenght function here your loop will execute total 13 times till \0 means null character then loop will stop execute and inside loop count will increase each time and return will print 13 Second code will not print 14 it's totally depends on your input size what inputs user trying to enter it will calculate total no of chars
15th May 2022, 11:12 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
0
hmmm Am getting same output as 13 .. Can you check it again.. and give me a clarity, if I am missing anything... It will give same output as you expecting also, I think. edit: difference may in your input way.. in PC, you must press enter to sumit so it reads \n also. but here, you there is submit button so it won't add \n at end. so same output here.
15th May 2022, 11:18 AM
Jayakrishna 🇮🇳