Yesterday we had an exam in a C language course and question was something like that:
- Write a function called toLowercase which takes a character as a parameter and returns uppercase letters to lowercase. If the character is not upper case, the function should return it unchanged.
write a program that takes arbitrarily many characters from user (until s/he enter "!") and then outputs first and last entered uppercase letters in lowercase form.
a. If the user enters only one uppercase letter, program should output that uppercase letter twice in lowercase form.
b. We can assume that user always enters at least one uppercase letter.
Example Inputs and Desired Outputs
lskdjfSFFKAFfkafafkKFAFkaKfgRORELKkjfks!
====> sk
Mdsfisjf98948*3jkfHf9059,353953,^+%^+%!
====> mh
sjfhsfR'^^''jfi2jpfj99ejfsdfs
====> rr
Here is my code:
#include <stdlib.h>
#include <stdio.h>
char toLower(char n){
char m=' ';
if(n>='A'&&n<='Z'){
m=n-'A'+'a';
return m;
}
else
return n;
}
int main(){
int i=0;
char ch,chmod,chFirst=' ',chLast=' ';
scanf("%c",&ch);
while(ch!='!'){
chmod=toLower(ch);
if(chmod!=ch){
chLast=chmod;
i++;
}
if(i==1)
chFirst=chmod;
scanf("%c",&ch);
}
if(i==1)
chFirst=chLast;
printf("%c%c",chFirst,chLast);
return 0;
}
I tried this code with three different compilers and it outputs wrong results. There are some strange things. It results the first letter wrong but the second letter correct. If the input contains only one uppercase letter, the output is correct again. Lastly, I checked this code over and over again.
What's wrong with this code?