don't understand why this code outputs 3. Why doesn't it output 32??
#include <stdio.h>
#include <ctype.h>
int main()
{
printf("%d\n", parseint("32"));
return 0;
}
int parseint(char *str) {
int i=0;
while(str[i] != '\0'){
return (str[i] - '0');
i++;
}
return 1;
}
your code is:
#include <stdio.h>
#include <ctype.h>
int main()
{
printf("%d\n", parseint("32"));
return 0;
}
int parseint(char *str) {
int i=0;
while(str[i] != '\0'){
return (str[i] - '0');
i++;
}
return 1;
}
return breaks a loop and returns from function.return statement must be last statement to be executed,code after return statement never be executed.
It gives output 3,because first i=0 and it enters while loop and see return statement so it breaks a loop and returns with first letter of string '3' and prints in main method.it never come back.
Modified code is:
#include <stdio.h>
#include <ctype.h>
int
i;
//global variable.
int main()
{ char
s[]="32"; //here
any string
i=0;
while(s[i]!='\0'){
printf("%d\n", parseint(s));
i++;
}
return 0;
}
int parseint(char *str) {
return (str[i] - '0');
return 1;
}
Output:
3
2
Get Answers For Free
Most questions answered within 1 hours.