Next

C Notes

In C character is an integer of size 1byte. (1 byte is 8 bits)

In C character is an integer of 1 byte-8 bits, it takes values from -128 to +127.(since 2^8=128)

Sample Code 1:

Let us print out numbers from 1 to 100

#include<stdio.h>
int main( void)
{
char x;                                  //see char declaration 
for(x=1;x<=100;x=x+1)
{printf("%d",x); }                 //see %d in printf
return 0;

}

Sample Code 2:

In this code i print Ascii value of char and the char itself next to each other

#include<stdio.h>
int main(void)
{
char ch;
for(ch='A';ch<='Z';ch=ch+1)
{printf("\n %d%c",ch,ch);}
return 0;
}

Sample Code 3:

In this sample code i will ask user to enter a single character and check whether it is lower case or upper case or a digit.

#include<stdio.h>
int main(void)
{
char ch;
printf("Enter char:");
scanf("%c",&ch);
printf("char %c=%d\n",ch,ch);
if(ch>='A'&&ch<='Z')
printf("%c is a upper case letter\n",ch);

else if(ch>='a'&&ch<='z')
{printf("%c is a lower case letter\n",ch);
}
else if(ch>='0'&&ch<='9')
{printf("%c is a digit\n",ch);}
else
{printf("its a special character");
}
return 0;
}

Sample Code 4:

In this code I demonstrate how to convert a letter from lowercase to uppercase

#include<stdio.h>
int main(void)
{
char ch;
printf("Enter char:");
scanf("%c",&ch);

if(ch>='a'&&ch<='z')
{
ch=ch+'A'-'a';
}
printf("%c",ch);
return 0;
}

Sample Code 5:

See the usage of format specifier %s for string type data. Here I want you to note the definition of a C type string

Any  contiguous sequence of characters that terminates with a 0 is called a C type string.

#include<stdio.h>
int main(void)
{
char ar[5];
ar[0]='H';
ar[1]='e';
ar[2]='l';
ar[3]='l';
ar[4]='o';
ar[5]=0;
printf("%s",ar);
return 0;
}

Try to understand this fine piece of code 

#include<stdio.h>
int main(void)
{
char ar[10]="Hello";  int i;
for(i=0;i<5;i++){
printf("%c","Hello"[i]);}
return 0;
}

Sample Code 6:

Usage of sprintf, observe that the data is stored in buff and we print from buff.

#include<stdio.h>

int main(void)

{char buff[100];

sprintf(buff,"%d+%d=%d",3,3,6);

printf("%s",buff);

return 0;

}

 

Exercise:

1.Ask user to enter a character in uppercase and convert it to lowercase.

2.Ask the user to enter a string in lower case and print it in  upper case.

 

Hosted by www.Geocities.ws

1