0

I'm making a program that, if the user inputs a lowercase character, generates its character in uppercase, and the opposite too. I'm using a function in order convert the character into lowercase or uppercase based on the ASCII table. Lowercase to uppercase is being converted correctly, but uppercase to lowercase is not.

char changeCapitalization(char n) { //uppercase to lowercase if(n>=65 && n<=90) n=n+32; //lowercase to uppercase if(n>= 97 && n<=122) n=n-32; return n; } 
3
  • 6
    It looks like uppercase to lowercase is working... but then you're immediately checking if n is lowercase, which it is, and converting it back to uppercase. Commented Mar 31, 2015 at 18:11
  • it can be done as a one-liner (n>='a' && n<='z' || n>='A' && n<= 'Z' ? n ^ 0x20 : n). Commented Mar 31, 2015 at 18:21
  • 3
    @HuStmpHrrr: Using clever one-liners aren't necessarily a good idea for someone who is just learning the basics of programming. Commented Mar 31, 2015 at 18:27

3 Answers 3

2

What the others are essentially saying is you want something like this ('else if' instead of 'if' on the lower to upper logic):

char changeCapitalization(char n) { if(n>=65 && n<=90) //uppercase to lowercase n=n+32; else if(n>= 97 && n<=122) //lowercase to uppercase n=n-32; return n; } 
Sign up to request clarification or add additional context in comments.

Comments

1

Chang the line

if(n>= 97 && n<=122) 

with

else if(n>= 97 && n<=122) 

Because this condition is the opposite way like you said in the question

Comments

1

Two if statements in sequence are executed - well - in sequence. So if you have an uppercase character, it will first be converted to lowercase, and afterwards, the next if statement will convert it back to lowercase. When you want to check the second condition only if the first one wasn't true, put else in front of the second if.

Also, rather than using the ASCII codes directly, you can compare characters to each other: if (n >= 'A' && n <= 'Z').

Later, when you're more comfortable with programming and start doing bigger projects, you should use the language's built-in functions for working with strings and characters, such as islower() and isupper() - and if you need to support any non-English characters, you should read this great article on the intricacies of encoding international characters.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.