C Language introduction LANGUAGES :
A set of statements is called a Language.
There are four types of languages according to their time. I Generation Languages :
These languages are Machine languages. To write programs in these languages the system technology must be required. The data is non-portable. That means a program written in a system does not work in another systems.
II Generation Languages :
---These are Assembly Languages. ---These are also system oriented that means to write any program in a system that system's technology must be required and data is non-portable. But they used MNEMONIC words in programs. That means they used a single word instead of more words.
III Generation Languages :
---In these languages programs are witten in general english language. There is no need to know the system technology and the data can be transfered anywhere. IV Generation languages :
These languages are defined in any one of the above languages. These are also called as packages.
Here I & II Generation languages are called Low Level Languages and III & IV generation languages are called High Level Languages.
For high level languages we have to use translaters to translate the source code written in general english language into machine language.
These translaters are two types. 1) Interpreters, 2) Compilers. 1) Interpreters :
---These translaters translate the source code step by step into machine language until any error. If there is any error it stops and shows some message. After correction it can continue.
Ex : BASIC, DBase III+, ....
2) Compilers :
These translaters translate the entire source code into machine language when it is error-free and creates an object file in machine language. If there is any error it shows the list of error. After debugging it creates the object file.
Ex: COBOL, C, C++, ... C
---The language 'C' was designed by Dennis Ritchie at AT & T Bell Laboratories. The standardised C was released in 1979.
The 'C' language is used to develop i) Scientific applications,
ii) Business applications,
iii) Graphical applications (Ex: WINDOWS ), iv) System programs,
v) Operating Systems (Ex: UNIX) , ... Character Set :
alphabets constants, statements, digits ==> variables, ==>
==> Programs
special symbols keywords instructions
Constants :
---The unchangeable quantities are called Constants. The constants are generally two types.
1) Character constants :
a) Characters Ex: 'a', '5', '+', ' ', ... b) Strings Ex: "abc", "435", 'rama", ... 2) Numeric Constants :
a) integers Ex: 435, -657, 65535, -32768,... b) Real numbers
i) Fractional form Ex: 435.67, 345.00054, ... ii) Exponential form Ex: 0.02e3, 1.17e-38, ... Variables :
---The quantities which can be changed during the execution of program are called Variables. A variable can be considered as the name of the cell which can hold the constants.
To use any variable it must be declared with its data type before the first executable statement and they can be initialised.
Naming the variable is very important.
1) The variable name must be start with either alphabets or an underscore and may contain alphabets, digits, hyphen or underscore.
2) The maximum length of a variable is 8 characters. But some compilers can accept upto 32 characters.
3) There must not be any blank spaces or special symbols in a variable name. 4) A variable name must not be a keyword.
Ex:valid invlid
eno emp name
empname emp(name emp-name 45abc emp_name int _abc char ab45 Keywords :
These are predefined words. There are 32 keywords in C language. These keywords can not be used as user-defined variables.
Operators :
There are 42 operators in C language. 1) Arithmetic Operators : + - * / % Ex: 100 + 40 ==> 140 100 - 40 ==> 60 100 * 40 ==> 4000 100 / 40 ==> 2 100 % 40 ==> 20 40 % 100 ==> 40 2) Assigning Operators : =
(variable) = (constant) / (variable) / (expression) ; Ex: a = 5 b = a c = a + b -2 3) Multiple operators : += -= *= /= %= Ex: a = a + 3 ==> a += 3
a = a - 3 ==> a -= 3 a = a * 3 ==> a *= 3 a = a / 3 ==> a /= 3 a = a % 3 ==> a %= 3 4) Unary Operators : ++ Ex : a = a + 1 ==> a += 1 ==> a ++ ==> ++ a a = a - 1 ==> a -= 1 ==> a -- ==> -- a 5) Relational Operators : == > < >= <= != 6) Logical Operators : && || ! Structure of a 'C' program : preprocessor commands global declarations main() { local declarations ; statements ; } function(arguments) { local delcarations ; statements ; }
The 'C' program has a free formated structure.
Every statement must be terminated with a semicolor ;
A program is a collection of functions. There may be a lot of functions but at least one function must be there that is main(), where the execution starts.
C has case sensitivity. All the keywords are defined in lower case. So better to write entire program in lower case.
Preprocessor commands :
The commands which start with a hash(#) symbol are called Preprocessor commands.
Ex : # include <stdio.h> # include "conio.h" # define PI 3.14159 Global declarations :
To use any variable it must be declared with its data type before the first
executable statement. The variables which declared in a block are available in that block only.
To use the variable in the entire program with same effect it must be declared as global.
Data Types :
Type Range occupied bytes format string
signed char -128 to 127 1 %c
unsigned char 0 to 255 1 %c
short signed int -32768 to 32767 2 %i %d %o %x
short unsigned int 0 to 65535 2 %u
long signed int -2^16 to 2^16 -1 4 %ld
long unsigned int 0 to 2^32 -1 4 %lu
float 3.14e-38 to 3.14e38 4 %f
double 1.17e-308 to 1.17e308 8 %lf
long double 1.17e-4932 to
1.17e4932 10 %Lf
Functions : 1) clrscr()
This function is used to clear the screen. This function's prototype has defined in the header file CONIO.H
( CONIO ==> Console Input Output ) Syntax :
clrscr() 2) printf()
This function is used to display the text and the values of variables. This function's prototype has defined in the header file STDIO.H To display the variable's value the format string must be used. ( STDIO ==> Standard Input Output )
Syntax :
printf(" format string ", variables) ; Ex :
printf(" %d %c", k, j);
printf("The marks are %d, %d, %d", m1, m2, m3 ); Note :
The function printf() returns an integer value that is the number of arguments given to the statement.
Remarks :
To write any remarks or comments to the statements they must be enclosed with the symbols
/* */ Ex : /* sdfjkshadjfsdjkafkjsadjkfhkasdj sdafhasdfhgasdhfgasdgfgasdfhasdfj sdafjksadfjasdkhfjasdhkfjhksda */ Escape Sequences : ---\0 ==> Null character \t ==> Tab ( 8 spaces) \l ==> Line feed \r ==> Carriage Return
\n ==> New line character ( \n = \l + \r ) \a ==> Alert (beep sound)
\' ==> Single quotes \" ==> Double quotes \\ ==> back slash
TURBO C editor :
It is a compiler of C program and it can be also used as an general editor. To enter into editor first change into the directory which contains the software and enter the command TC at the command prompt.
C:\> CD TURBOC2 C:\TURBOC2> tc
Then it opens the editor which contains a menu bar at the top, a status bar at the bottom and a main window to write the programming statements and a sub window which shows the messages.
The menu bar contains some menu pads and they can be selected by pressing ALT and the highlighted character in the required menu pad.
Then it shows the submenu which contains some bars and they can be selected using arrow keys.
The status bar shows online help and the keys information.
1) To write a new program select 'New' command from "File" menu. 2) To save the working program select 'Save' command from "File" menu
or press F2 and enter a name.
3) To compile the program select 'Compile to OBJ' command from "compile" menu or press Alt + F9. Then it shows the list of
errors or warnings. If the program is error-free then the compiler creates an object file (.OBJ) and an executable file (.EXE).
4) To execute the program select 'Run' command from "Run" menu or press Ctrl + F9.
5) To seee the output of the execution select 'User Screen' command from "Run" menu or press Alt + F5.
6) To close the editor select 'Quit' command from "File" menu or press Alt + X.
scanf() :
This function is used to accept the values for the variables while executing the program from keyboard. This function's prototype has defined in the header file STDIO.H
Syntax:
scanf("formatstring" , &(variables) ); Note :
To accept two or more values with a single scanf() they can be seperated by space or tab or enter key.
Ex :
i) int a;
scanf("%d", &a); ii) int m1, m2, m3;
scanf("%d%d%d", &m1, &m2, &m3); iii) char ch;
scanf("%c", &ch);
getch() & getche() :
This function is used to accept a single character for the variable while executing the program. But this function does not display the entered character. This function's prototype has defined in the header file CONIO.H
Note : To see the entered character the function getche() can be used. Syntax:
(variable) = getch() ; Ex :
c = getch();
Note :
---The arithmetic expressions are three types. integer integer ==> integer
integer float ==> float float float ==> float Ex : 10 / 4 ==> 2 10 / 4.0 ==> 2.5 10.0 / 4 ==> 2.5 10.0 / 4.0 ==> 2.5 Conditional Statements :
In C language the conditional statement returns zero when the condition is false. Otherwise it returns a non-zero(1) value when the condition is true.
There are three types of conditional statements in 'C' . 1) if, 2) switch, 3) conditional operators
1) if ... else : Syntax : if (condition) if (condition) { { (statements); (statements); } or } else { (statements) ; } 2) switch... case : Syntax: switch(variable) {
case (value) : (statements) ; case (value) : (statements) ; ---default : (statements) ; } break:
---This keyword stops the execution in the given block and comes out. Generally it is used in switch..case statements and looping statements. 3) Ternary Operators ( ? : ; ) :
Syntax :
(condition) ? (statement1) : (statement2) ; gotoxy() :
This function changes the cursor position on the screen to the required location by giving the x and y co-ordinates. This function's prototype was defined in the header file CONIO.H
Syntax:
gotoxy(x, y); or gotoxy(col, row) ; Note :
Generally in MS-DOS mode the screen contains 25 rows from top to bottom and 80 columns from left to right.
textcolor() & textbackground() :
These functions changes the colors of screen. There are 16 colors numbered from 0 to 15. The colors may be given with numbers or color names. These functions prototypes was defined in the header file CONIO.H
Syntax:
textcolor(colorname); or textcolor(colornumber) ;
textbackground(colorname); or textbackground(colornumber); Colors List :
BLACK, BLUE, ... WHITE
cprintf() :
This function displays the given text with the current console settings. This function's prototype was defined in the header file CONIO.H
Syntax:
goto :
This keyword changes the execution control to the required statement by defining the statement with label. This keyword is a branching statement. Syntax: goto (label) ; ----(label) : Note :
The world wide programmers decided to avoid this keyword to reduce the complexity in big programs.
Looping Statements :
Repeating a block of statements number of times is called Looping. There are three types of looping statements in 'C' .
1) for, 2) while, 3) do..while. Note :
The keyword 'goto' is a branching statement. It can also used to execute a block of statements number of times.
1) do ... while : Syntax: do { (statements) ; } while (condition) ; Note :
There is a drawback in do..while looping. Here the conditional statement executes after executing the block of statements. If the given value is less than the initial value of the loop generating variable it displays some mistakes. To avoid this problem we can use 'while' statement.
2) while : Syntax:
while (condition) {
(statements) ; }
3)
Arrays :
An array is a collection of similar data type elements. It stores the elements in contiguous locations. To use any array it must be declared with its size and they may be initialized. The indexing is start with 0. The arrays are two types.
1) Single Dimensional arrays, 2) Multi Dimensional Arrays. 1) Single Dimensional Arrays :
Syntax :
(type) (variable) [size] ; Ex:
int eno[5] = { 56, 67, 45, 89, 45}; char ena[] = { 'a', 'b', 'c', 'd' } ; float bas[] = { 56.67, 900.45, 567 } ;
2) Multi Dimensional Arrays : Ex:
int a[5][3], b[4][5][6][7], ...
char na[3][20] = { "abcdefgh", "ramakrishna", "Bhanodaya" };
A multi dimensional array is a collection of another arrays. That means a double dimensional array is a collection of single dimensional arrays.
Ex:
The array a[5][3] is a collection of 5 single dimensional arrays with size 3.
STRINGS :
A string is an array of characters. It ends with a null character. ( '\0' ==> Null character )
Ex :
char na1[6] = { 'a', 'b','c', 'd', 'e', '\0' } ; char na2[6] = "abcde" ;
char names[][] = { "rama", "krishna", "abcd" } ; char str1[20], str2[40] ;
Note :
The format string for a string variable is %s . Note :
scanf() function can accept the string values. But it does not allow spaces in the string. To avoid this problem gets() can be used.
gets() :
This function is used to accept the value for a string variable. This function's prototype has defined in the header file STDIO.H. Syntax : gets(varaible) ; Ex : gets(str) ; puts() :
This function is used to display the string value of the variable. This function's prototype has defined in the header file STDIO.H Syntax : puts(string) ; Ex : puts("The string is "); puts(str) ; STRING.H functions :
To manipulate the strings the C authors designed some functions in the header file STRING.H
1) strlen():
This function returns an integer value that is the length of the string. length means the number of characters.
Syntax:
int strlen(string) ;
2) strupr() :
This function changes the given string into uppercase characters. Syntax :
strupr(string) ; 3) strlwr() :
This function changes the given string into lowercase characters. Syntax :
4) strcpy() :
This function copies the string to another string. Syntax :
strcpy(target, source) ; 5) strcat() :
This function adds two strings. Syntax :
strcat(destination, second) ; 6) strrev() :
This function change the given string into reverse order. Syntax :
strrev(string) ; 7) strcmp() :
This function compares two strings and returns zero when both are same.
Syntax :
int strcmp(first, second) ;
FUNCTIONS :
The function is a piece of code. These functions are used to reduce the repetition of coding.
The functions are two types. 1) Derived functions, 2) User-defined functions.
The derived functions are provided by the C writers and they defined them in header files. To use these functions the header file must be included at the top of the program.
We can create our own functions. To write any function there are three steps. 1) Functions declarations, 2) Functions calling, 3) Function definition.
or
1) Function definition, 2) Function calling.
In the function declaration and/or in the definition the name must be follow the return data type, and it should be followed by parenthesis. In the parenthesis there may be arguments with their data types. If the function does not return any value it must be declared as void.
Syntax:
(datatype) (functionname) (argumentstype) ; /* Function declaration */ functionname(arguments) ; /* Function calling */ (datatype) (functionname) (argumentstype) /* Function definition */ {
(statements) ; }
These functions are three types.
1) No arguments with no return value functions, 2) Arguments with no return value functions, 3) Arguments with return value functions. PREPROCESSOR COMMANDS :
The commands which start with hash (#) are called Preprocessor Commands. Ex : # define PI 3.14159 # include <stdio.h> # include "conio.h" # define A 1.7 define :
This command is used to define our own constants. include :
This command is used to include the files which contains the definition of functions.
There are two types to include the files. 1) # include < name >
This type of command includes the file which is located in the specified directory. These specifications are set by selecting the Directories command from Options menu.
2) # include " name "
This type of command includes the file which is located in the current directory and/or in the specified directory.
STORAGE CLAUSES :
The declared variables are generally stored in memory devices. But by using the storage clauses they can be stored either in memory devices or in CPU registers. These storage clauses are 4 types. The variables initialization depends on this type. 1) auto, 2) register, 3) static, 4) extern
1) auto :
This keyword is an option. It stores the variable in memory device. It assigns a junk(garbage) value to the variable. The variable which declared in a block that is available in that block only. The default type is auto.
2) register :
This keyword stores the variable in CPU registers. It assigns a junk(garbage) value to the variable. In CPU registers it can't store more and big values like floats, doubles,..etc. It can store only chars and integers. These variables are also local that means the variables which declared in a block are available in that block only. Generally these variables are used to generate the looping statements.
3) static :
This keyword stores the variable in memory device. It initialises the variable as 0. The scope of variable is local that means the variables which declared in a block are available in that block only. But it does not destroy the variable's value when end that block. It takes the previous value when the controller entered into that block again.
4) extern :
This keyword stores the variable in memory device. It initialises the variable as 0. The scope of variable is global. This variable is declared before the main() . The variable's value can be changed in the functions.
This topic is the most important in C.
The variables stored in the memory can be accessed with their addresses using pointers.
To access with pointers we have to use two new operators. & ==> Address of
* ==> Value at address of
Note: The variables are stored in memory between 64 kb and 128 kb. Ex :
int a = 5; a ==> 5
&a ==> 65500 *(&a) ==> 5
These address value can be stored in another variable. But that must be a pointer variable of the same type to the variable.
sizeof :
This keyword is used to find the size occupied by the variable in the memory. Syntax :
int sizeof(type) ; int sizeof(variable) ;
Note : Any Pointer variable occupies two bytes of memory. Because The pointer variable contains the address of the variable. The address of any type of variable is only a number.
Pointers in Functions :
The functions can be send some arguments to the definition and may take a return value. If the value of these variables changed in the functions that does not effected to the function calling.
To change the value after calling the function the values can be send by reference. That means the address of the variable can be send to change the value.
Arrays with Pointers :
An array is a collection of similar data type elements mentioning with a single variable.
The address of first element is considered the address of the array.
The array elements can be accessed using the address of array and the index value.
Note : By increasing the address it increases the size to address. DYNAMIC MEMORY ALLOCATION :
malloc() :
This function is used to allocate the memory while exeuting the program. This functions returns a pointer that is the address of the location where it allocates the required space. If this function fails to allocate the required space it returns NULL value. This function's prototype was defined in the header file ALLOC.H and
STDLIB.H Syntax:
(pointer) = (pointertype) malloc(size*number) ; calloc() :
This function works same as the function malloc(). But the main difference between these two functions is the initial values. The malloc() function initilises the allocated space with junk values. But the calloc() function initialises the allocated space with zeros.
Syntax:
(pointer) = (pointertype) calloc(number, size) ; realloc() :
It re allocates the allocated memory with the required size and returns the address. This may be differ to the previous address.
Syntax:
(pointer) realloc(block, size) ; STRUCTURES :
A structure is a collection of variety of data type elements. This is created with the keyword struct.
struct (name) {
(elements declaration); } ;
struct (name) (variable) ; (variable).(element) Ex :
1) struct employee {
char ename[80]; float bas;
};
struct employee emp = { 5, "rama", 5600 } ;
2) struct employee { int eno; char ename[80]; float bas; } emp = { 5, "rama", 5600 } ; 3) struct { int eno; char ename[80]; float bas; } emp = { 5, "rama", 5600 } ; Structures with Pointers :
The structure elements can be accessed using the address of the structure variables. To access the elements with structure variable there must be a period operator(.) between the variable and element. But to call the element with
structure pointer there must be -> operator between the structure pointer and the element.
(structurevariable).(element) (structurepointer)->(element)
FILE HANDLING IN C :
Using C programs the data files and text files can be manipulated. To use any file it must be loaded into memory. In C programs the file pointer where the file stored can be found.
fopen():
This function is used to open the required file in the required mode and returns the file pointer where the file stored. If it is unable to open in the given mode it returns a constant value NULL.
Syntax :
FILE * (filepointer) ;
(filepointer) = fopen("filename", "mode" ); modes :
"a" ==> To add the data to the file "r" ==> To read the data from the file Ex :
FILE *fp;
fp = fopen("data.txt", "w"); fclose() :
The file, which opened in memory must be closed to avoid the data corruption. To close the file the function fclose() must be used.
Syntax : fclose(filepointer); Ex : fclose(fp) ; fputc():
This function is used to store the characters in the data file opened in the filepointer. Syntax : fputc(char, filepointer) ; Ex : fputc(ch, fp) ; fgetc() :
This function is used to read a character to the variable from the file pointer. Syntax :
char variable = fgetc(filepointer) ; Ex :
ch = fgetc(fp) ; fprintf() :
This function stores the data in the file. Syntax :
fprintf(filepointer, "format string", variables); Ex :
fprintf(fp, "%d %s %f", eno, ena, bas);
fscanf() :
This function reads the data from the file. Syntax :
Ex :
fscanf(fp, "%d %s %f", &eno, ena, &bas);
fwrite() :
This function is used to store the structures in the file in binary mode. Syntax:
fwrite( (pointer to structure), (size of structure), (numberofstructures), (filepointer) );
Ex:
fwrite( &emp, sizeof(emp), 1, fp); fread() :
---This function is used to read the structures from the file in binary level. Syntax:
fread( (pointer to structure), (size of structure), (numberofstructures), (filepointer) );
Ex:
fread(&emp, sizeof(emp), 1, fp);
COMMAND LINE ARGUMENTS :
The arguments can be passed to any function when they are calling.
The main() is also a function and some arguments can be passed to it from the MS-DOS prompt.
Here we have to use the words argv, args[] .
Here argv is the an integer value and it is the number of arguments passed and *args[] is an array of strings contain the arguments
Syntax:
main(int argv, char *args[])
GRAPHICS :
Generally the screen is in textmode. It can be changed by the display adopters. There are a number of adopters like VGA, CGA, EGA, ...
The normal text mode has 25 rows and 80 columns. It can be changed using the MODE command in MS-DOS. Using C programs we can design some graphics by changing the screen from text mode to graphics mode.
initgraph() :
This function changes the screen from text mode to graphics mode. But here we have to mention the display driver and mode. To use this command the file
EGAVGA.BGI must be in the current directory. This function's prototype has defined in the header file GRAPHICS.H
Syntax:
initgraph( (address of driver), (address of mode), (path to file) ); Ex :
int gdr = DETECT, gmd;
initgraph(&gdr, &gmd, "C:\TC" ); detectgraph() :
This function detects the using graphic driver and modes. It assign the values to the variables.
Syntax :
detectgraph( (address of graphic driver), (address of graphic mode) ); Ex :
int gdr, gmd;
detectgraph(&gdr, &gmd);
closegraph() :
This function closes the graphics mode and changes to text mode. Syntax:
closegraph(); setcolor() :
This function changes the displaying color of screen. In VGAHI we can use 16 colors. The color can be mentioned as integer.
Syntax: setcolor(integer) ; Ex : setcolor(RED) ; setcolor(4) ; setbkcolor() :
This function changes the background color of screen . Syntax : setbkcolor(integer) ; Ex: setbkcolor(YELLOW) ; setbkcolor(15); putpixel() :
This function highlights the pixel(picture element) at the given co-ordinates to the given color .
Syntax :
Ex :
putpixel(320, 240, 5) ; line() :
This function displays a line between the given coordinates. Syntax : line(x1, y1, x2, y2 ); Ex : line(200,300, 240, 370 ); lineto() :
This function displays a line to the given coordinates from the current coordinates. Syntax : lineto(x2, y2) ; Ex : lineto(400, 600) ; circle() :
This function displays a circle with the given center coordinates and the radius. Syntax : circle(x, y, radius) ; Ex : circle(320, 240, 100) ; ellipse() : Syntax :
ellipse(x, y, st-angle, end-angle,x-radius, y-radius ); Ex :
ellipse( 320, 240, 0, 360, 200, 100 ); arc() :
Syntax :
arc(x, y, st-angle, end-angle, radius ); Ex : arc(320, 240, 45, 135, 200 ) ; rectangle() : Syntax : rectangle( x1, y1, x2, y2 ); Ex : rectangle( 200, 150, 440, 320 ); random() :
This function returns the value which is between 0 and 1 less than the given number. This function's prototype has defined in the header file STDLIB.H
Syntax : random(n);
This function returns any number from 0 to n-1 . settextstyle() :
This function sets the displaying text style . Syntax :
settextstyle( font, direction, size ); fonts :
direction : HORIZ_DIR, VERT_DIR size :
Ex : settextstyle( 3, 0, 5 ); outtextxy() :
This functions displays the given text at the given coordinates with the setted style.
Syntax :
outtextxy(x, y, text) ; Ex :