Home | About | Comments | Lectures | Notice | Registration
C Programming Main Page
Review Lesson One
About C Datatypes
You Will Learn About :
The material provided on this site is part of a complete course in Mastering C Programming. C programming at introductory level is FREE.
The C language has four main datatypes : character, integer, float and double
A complete list will be introduced later:
char 1 byte character data int 2 bytes integer data float 4 bytes floating point number double 8 bytes double precision float
A character is any letter, number or symbol : eg 1, t, W, &, #
It is necessary to assign memory space to hold values. We say that variables must be declared. Before we can effectively deal with a character we must tell C to set aside memory for a characer. Declarations must precede executable statements in the source code (instructions written using a computer language).
Here is a statement to declare a character variable :
char variable_name;
To manipulate a character we use the getchar( ) and putchar( ) functions. Here is a program to get a single character from the user then print it on screen.
/* Program 2A - Character manipulation */ main() { char c; c = getchar( ); putchar(c); } |
nb : When you run this program it seems as though nothing happens. This is because we simply told the program to get a character from the user but we did not tell it to print any prompt to advise the user what to do. Promps are needed because they tell the user exactly what data must be entered.
Program 2B is an improvement on 2A because it includes a prompt. Prompts make programs more user-friendly. Two new functions puts( ) and exit( ) are also introduced. puts( ) works something like a simple printf( ) function. It lacks some of the features of printf(), though.
/* Program 2B - Character manipulation using puts() and gets() */ #include<stdio.h> main() { char c; /* variable declared */ puts("Enter a single character"); /*User prompt */ c = getchar( ); printf(" You entered"); putchar(c); exit(0); /* To tell the compiler to end the program normally */ } |
Instructions :
Detailed Explanation :
To use the printf( ) function to print a character requires the use of the specifie %c which tells C exactly where within the print statemetnt the value of the variable must be placed.
Here is a print statement that can be used to replace the putchar( ) function used earlier :
printf("The character you entered was %c",c );
Integers are numbers within the range -32768 and +32,767. The printf( ) function requires the specifier %d or %i when displaying integer values.
Here is a statement to declare an integer variable:
int variable_name;
/* Program 2C - Adding two intergers */ main() { int x=2, y=3, sum; /* variable declared */ sum = x + y; printf(" The sum is %d", sum); exit(0); /* end normally */ } |
The Tutor |
|
Home | About | Comments | Lectures | Notice | Registration