C Tutorial/Data Type/char Calculation
Содержание
Checking for Upper- and Lowercase
#include <stdio.h>
main(){
char cResponse = "\0";
printf("Enter the letter A: ");
scanf("%c", &cResponse);
if ( cResponse == "A" )
printf("\nCorrect response\n");
else
printf("\nIncorrect response\n");
}
Enter the letter A: 2 Incorrect response
Compare characters to characters in if statement
#include <stdio.h>
main()
{
char cResponse = "\0";
printf("\n\tAC Control Unit\n");
printf("\na\tTurn the AC on\n");
printf("b\tTurn the AC off\n");
printf("\nEnter your selection: ");
scanf("%c", &cResponse);
if (cResponse == "a")
printf("\nAC is now on\n");
if (cResponse == "b")
printf("\nAC is now off\n");
}
AC Control Unit a Turn the AC on b Turn the AC off Enter your selection: 1
Compare char variable in if statement
#include <stdio.h>
int main()
{
char a,b;
printf("Which character is greater?\n");
printf("Type a single character:");
a=getchar();
printf("Type another character:");
b=getchar();
if(a > b)
{
printf(""%c" is greater than "%c"!\n",a,b);
}
else if (b > a)
{
printf(""%c" is greater than "%c"!\n",b,a);
}
else
{
printf("Next time, don"t type the same character twice.");
}
return(0);
}
Which character is greater? Type a single character:1 Type another character:"1" is greater than " "!
Converting uppercase to lowercase
#include <stdio.h>
int main(void)
{
char letter = "B";
if(letter >= "A")
if (letter <= "Z"){
letter = letter - "A"+ "a";
printf("You entered an uppercase %c\n", letter);
}
else
printf("Try using the shift key, Bud! I want a capital letter.\n");
return 0;
}
You entered an uppercase b
Overflow in char and unsigned char data types
Overflow means you are carrying out an operation such that the value either exceeds the maximum value or is less than the minimum value of the data type. (Definition from C & Data Structures by P.S. Deshpande and O.G. Kakde Charles River Media 2004)
#include <stdio.h>
main()
{
char i,j ;
i = 1;
while (i > 0){
j = i;
i++;
}
printf ("the maximum value of char is %d\n",j);
printf ("the value of char after overflow is %d\n",i);
}
the maximum value of char is 127 the value of char after overflow is -128