You are on page 1of 39

Im links http://gigapedia.com/ //http://warez-bb.org/ Pdfdatabase.

com
http://www.exforsys.com/tutorials/c-language/c-structures-and-unions.html

http://www.technoexam.com/

HISTORY OF C LANGUAGE C is a programming language developed at AT & Ts Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. In the late seventies C began to replace the more familiar languages of that time like PL/I, ALGOL, etc. C seems so popular is because it is reliable, simple and easy to use. Moreover, in an industry where newer languages, tools and technologies emerge and vanish day in and day out, a language that has survived for more than 3 decades has to be really good. The Compiler A C program is made by running a compiler which takes the typed source program and converts it into an object file that the computer can execute. A compiler usually operates in two or more phases (and each phase may have stages within it). These phases must be executed one after the other.

Constants, Variables and Keywords Types of C Constants Primary Constants o Integer Constant o Real Constant o Character Constants Secondary Constants o o o o o Array Pointer Structure Union Enum,etc.

INTEGER CONSTANTS Rules for Constructing Real Constants Real constants are often called Floating Point constants. The real constants could be written in two formsFractional form and Exponential form. Default sign is positive. No commas or blanks are allowed within a real constant. Ex.: +325.34 426.0 -32.76 (a) (b) (c) (d) (e)

Character Constants A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Both the inverted commas should point to the left. For example, A is a valid character constant whereas A is not. The maximum length of a character constant can be 1 character. Variables : A variable is a way of referring to a memory location used in a computer program. Variable holds values- like numbers or text or more complicated types of data. Values of variable can be vary in a program A name or identifier in C can be anything from a single letter to a word. Rules for Constructing Variable Names 1. A variable name is any combination of 1 to 31 alphabets, digits or underscores. Some compilers allow variable names whose length could be up to 247 characters. Still, it would be safer to stick to the rule of 31 characters. Do not create unnecessarily long variable names as it adds to your typing effort. 2. The first character in the variable name must be an alphabet or underscore. 3. No commas or blanks are allowed within a variable name. 4. No special symbol other than an underscore (as in gross_sal) can be used in a variable name. Ex.: si_int m_hra pop_e_89 (a) (b) (c) (d) Keywords : Keywords are the words whose meaning has already been explained to the C compiler (or in a broad sense to the computer). The keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is not allowed by the computer.They always displayed in white colour There are only 32 keywords available in C. A Auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while

DATA TYPES : Data types are the keywords used to specify the type of data stored by the variable. Data types are of two types 1. Primary (Primitive ) Data types 2. Secondary ( Non primitive Data Types)

1. Primary data types ; are those who are defined by the c some of them are as follows Data Types signed char (for character value) unsigned char short signed int (for integer value) short unsigned int signed int unsigned int long signed int Range -128 to + 127 0 to 255 -32768 to +32767 0 to 65535 -32768 to +32767 0 to 65535 -2147483648 to +2147483647 0 to 4294967295 -3.4e38 to +3.4e38 Bytes 1 1 2 2 2 2 4 4 4 8 10 Format %c %c %d %u %d %u %ld %lu %f %lf %Lf

long unsigned int Float (for decimal values) double -1.7e308 to +1.7e308 long double -1.7e4932 to +1.7e4932

The First C Program Rules that are applicable to all C programs: Each instruction in a C program is written as a separate statement. Therefore a complete C program would comprise of a series of statements. (a) Each instruction in a C program is written as a separate statement. Therefore a complete C program would comprise of a series of statements. b)The statements in a program must appear in the same order in which we wish them to be executed; unless of course the logic of the problem demands a deliberate jump or transfer of control to a statement, which is out of sequence. c)Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are allowed within a variable, constant or keyword. d)All statements are entered in small case letters. e)C has no specific rules for the position at which a statement is to be written. Thats why it is often called a free-form language. f)Every C statement must end with a ;. Thus ; acts as a statement terminator.

main( ) { int p, n ; float r, si ; p = 1000 ; n=3; r = 8.5 ; /* formula for simple interest */ si = p * n * r / 100 ; printf ( "%f" , si ) ; } scanf conversion specifers The conversion characters for scanf are not identical to those for printf and it is important to distinguish the long types here. d ld x o h f lf e le c s Denary integer Long int Hexadecimal integer Octal integer Short integer Float type Long float or double Float type Double Single character Character string

Decision Control Structures In a c Program sometimes we have to execute a sequence of operations according to situation or we have to take decision according to the condition .This type of situations are handled in c by Decision control structures which are as follows. 1. The if statement 2. The if-else statement 3. The conditional operators The if statement C uses the keyword if to implement the decision control instruction. The general form of if statement looks like this: if ( this condition is true ) execute this statement ;

The keyword if tells the compiler that what follows is a decision control instruction. The condition following the keyword if is always enclosed within a pair of parentheses. If the condition, whatever it is, is true, then the statement is executed. If the condition is not true then the statement is not executed; instead the program skips past it. this expression x == y x != y x<y x>y x <= y x >= y is true if x is equal to y x is not equal to y x is less than y x is greater than y x is less than or equal to y x is greater than or equal to y

If-else statement If else statement is used when we have to execute both the situation of expression whether true or false. If (condition) { Execute when condition is true } else { Execute when condition is false }

1. The group of statements after the if upto and not including the else is called an if block Similarly, the statements after the else form the else block. 2. Notice that the else is written exactly below the if. The statements in the if block and those in the else block have been indented to the right. This formatting convention is follo wed throughout the book to enable you to understand the working of the program better. 3. Had there been only one statement to be executed in the if block and only one statement in the else block we could have dropped the pair of braces. 4. As with the if statement, the default scope of else is also the statement immediately after the else. To override this default scope a pair of braces as shown in the above example must be used.

Loops Loops free a program from writing things again & again. They allow the programmer to build a sequence of instructions which can be executed again and again, with some condition deciding when they will stop. There are three kinds of loop in C. They are called:

while do ... while for

while The simplest of the three loops is the while loop. In common language while has a fairly obvious meaning: the while-loop has a condition: while (condition) { statements; } and the statements in the curly braces are executed while the condition has the value "true" ( 1 ).

The first important thing about this loop is that has a conditional expression (something like (a > b) etc...) which is evaluated every time the loop is executed by the computer. If the value of the expression is true, then it will carry on with the instructions in the curly braces. If the expression evaluates to false (or 0) then the instructions in the braces are ignored and the entire while loop ends. The computer then moves onto the next statement in the program. The second thing to notice about this loop is that the conditional expression comes at the start of the loop: this means that the condition is tested at the start of every `pass', not at the end. The reason that this is important is this: if the condition has the value false before the loop has been executed even once, the statements inside the braces will not get executed at all - not even once.

do..while The do..while loop resembles most closely the repeat..until loops of Pascal and BASIC except that it is the `logical opposite'. The do loop has the form: do { statements; } while (condition) Notice that the condition is at the end of this loop. This means that a do..while loop will always be executed at least once, before the test is made to determine whether it should continue. This is the only difference between while and do..while. A do..while loop is like the "repeat .. until" of other languages in the following sense: if the condition is NOTed using the ! operator, then the two are identical. repeat == until(condition) while (!condition) do

for The form of the for loop is: for (statement1; condition; statement2) { } statement1 This is some kind of expression which initializes the control variable. This statement is only carried out once before the start of the loop. e.g. i = 0; condition

This is a condition which behaves like the while loop. The condition is evaluated at the beginning of every loop and the loop is only carried out while this expression is true. e.g. i < 20; statement2 This is some kind of expression for altering the value of the control variable. In languages such as Pascal this always means adding or subtracting 1 from the variable. In C it can be absolutely anything. e.g. i++ or i *= 20 or i /= 2.3 ... for (x = 0; x <= 10; x += 0.5) { } Quitting Loops (Break Statement) Break -provides a simple way of jumping out of any of the three loops above at any stage, whether it has finished or not. Break forcefully throws the control out of the loops

If this statement is encountered a loop will quit where it stands. For instance, an expensive way of assigning i to be 12 would be: for (i = 1; i <= 20; i++) { if (i == 12) { break; } } The loop will exit when i=12

Continue - is used perhaps to avoid executing a lot of irrelevant statements in a loop, for instance. continue; When a continue statement is encountered, a loop will stop whatever it is doing and will go straight to the start of the next loop pass. This might be useful to avoid dividing by zero in a program: for (i = -10; i <= 10; i++) { if (i == 0) { continue; } printf ("%d", 20/i); }

Nested Loops Loops can be placed inside other loops. Although this feature will work with any loop at all, . A loop controls the number of times that a particular set of statements will be carried out. Another outer loop could be used to control the number of times that a whole loop is carried out. To see the benefit of nesting loops, the example below shows how a square could be printed out using two printf statements and two loops. main () { int i,j; for (i = 1; i <= 10; i++) { for (j = 1; j <= 10; j++) { printf("*"); } printf ("\n"); } } Output ********** ********** ********** ********** ********** ********** ********** ********** ********** **********

Functions A function is a module or block of program code which performs a particular task. Making functions is a way of isolating one block of code from other independent blocks of code. Functions help us to organize a program in a simple way Returntype identifier (parameter1,parameter2,..) Void sum(int x, int y); Advatnages of functions 1.Writing functions avoids rewriting the same code over and over 2. Using functions it becomes easier to write programs and keep track of what they are doing. If the operation of a program can be divided into separate activities, and each activity placed in a different function, then each could be written and checked more or less independently. 3. Debugging is easier 4. It is easier to understand the logic involved in the program 5. 6. 7. 8. Testing is easier Recursive call is possible Irrelevant details in the user point of view are hidden in functions Functions are helpful in generalizing the program

Types of functions S.no 1 2 3 4 Returntype NO NO YES YES Argument NO YES NO YES Function Protoype with example void sum() void sum(int a) int sum() int sum(int a, intb)

Note : Write the programs of above four type.

Recursion: Recursion is a process in which a function calls itself A function is called recursive if a statement within the body of a function calls the same function. Sometimes called circular definition, recursion is thus the process of defining something in terms of itself.
example of recursion. to calculate the factorial value of an integer.

main( ) { int a, fact ; printf ( "\nEnter any number " ) ; scanf ( "%d", &a ) ; fact = factorial ( a ) ; printf ( "Factorial value = %d", fact ) ; } factorial ( int x ) { int f = 1, i ; for ( i = x ; i >= 1 ; i-- ) f=f*i; return ( f ) ; }

And here is the output...


Enter any number 3 Factorial value = 6

Call by Value
whenever we called a function and passed something to it we have always passed the values of variables to the called function. Such function calls are called calls by value. By this what we mean is, on calling a function we are passing values of variables to it. The examples of call by value are shown below:
sum = calsum ( a, b, c ) ;

f = factr ( a ) ;

Call by Reference: in call by reference instead of passing the value of a variable, we


pass the location number (also called address) of the variable to a function? in pointers) (we will do it

ARRAYS Arrays are collection of elements of similar datatype.Arrays are a convenient way of grouping a lot of variables under a single variable name. . For example: an array of three integers called "arr" would be declared like this: int arr[3]

Why use arrays?


Arrays are most useful when they have a large number of similar elements: that is, in cases where it would be completely impractical to have a different name for every storage space in the memory. It is then highly beneficial to move over to arrays for storing information for two reasons:

It is much easier to initialize an array than it is to initialize twenty or so variables. allocates a linear storage space in memory

Array declaration & initialization 1) int arr[3]; 2) int arr[ ]= {1,2,3}; 3) int arr[1]=10;

A Simple Program Using Array


Let us try to write a program to find average marks obtained by a class of 30 students in a test.
main( ) { int avg, sum = 0 ; int i ; int marks[30] ; /* array declaration */ for ( i = 0 ; i <= 29 ; i++ ) { printf ( "\nEnter marks " ) ; scanf ( "%d", &marks[i] ) ; /* store data in array */ } for ( i = 0 ; i <= 29 ; i++ ) sum = sum + marks[i] ; /* read data from an array*/ avg = sum / 30 ; printf ( "\nAverage marks = %d", avg ) ;

Points to remember in array

An array is a collection of similar elements. The first element in the array is numbered 0, so the last element is 1 less than the size of the array. An array is also known as a subscripted variable. Before using an array its type and dimension must be declared. However big an array its elements are always stored in contiguous memory locations. This is a very important point which we would discuss in more detail later on.

Array Elements in Memory one dimensional array Consider the following array declaration:
int arr[8] ;

What happens in memory when we make this declaration? 16 bytes get immediately reserved in memory, 2 bytes each for the 8 integers since the array is not being initialized, all eight values present in it would be garbage values.. Whatever be the initial values, all the array elements would always be present in contiguous memory locations. This arrangement of array elements in memory is shown in Figure 8.1. 3508 3510 3512 3514 3516 3518 3520 3522

Passing Array Elements to a Function


Array elements can be passed to a function by calling the function by value, or by reference. In the call by value we pass values of array elements to the function, whereas in the call by reference we pass addresses of array elements to the function. These two calls are illustrated below:
/* Demonstration of call by value */ main( ) { int i ; int marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ; for ( i = 0 ; i <= 6 ; i++ ) display ( marks[i] ) ; }

display ( int m ) { printf ( "%d ", m ) ; }

And heres the output...

55 65 75 56 78 78 90

And now the call by reference.


main( ) { int i ; int marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ; for ( i = 0 ; i <= 6 ; i++ ) disp ( &marks[i] ) ; } disp ( int *n ) { printf ( "%d ", *n ) ; }

Passing an Entire Array to a Function


In the previous section we saw two programsone in which we passed individual elements of an array to a function, and another in which we passed addresses of individual elements to a function. Let us now see how to pass an entire array to a function rather than its individual elements. Consider the following example:
/* Demonstration of passing an entire array to a function */ main( ) { int num[ ] = { 24, 34, 12, 44, 56, 17 } ; dislpay ( &num[0], 6 ) ; } display ( int *j, int n ) { int i ; for ( i = 0 ; i <= n - 1 ; i++ ) { printf ( "\nelement = %d", *j ) ; j++ ; /* increment pointer to point to next element */ } }

Two Dimensional Arrays int arr[5][5]; this array has five row nad five columns int arr[row][col];

Memory Map of a 2-Dimensional Array arr[0][0] arr[0][1] arr[0][2]


2052 2054 2056

arr[1][0]
2058

arr[1][1]..
2060

{ int s[4][2] = { { 1234, 56 }, { 1212, 33 }, { 1434, 80 }, { 1312, 78 } } ; Input in 2d Array for(i=0;i<row;i++) { for(j=0;j<col;j++) { scanf(%d,&arr[i][j]); } } Sorting

1. 2.
3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47.

#include<stdio.h> #include<conio.h> void bubble(int a[],int n) { int i,j,t; for(i=n-2;i>=0;i--) { for(j=0;j<=i;j++) { if(a[j]>a[j+1]) { t=a[j]; a[j]=a[j+1]; a[j+1]=t; } } }//end for 1. }//end function. void main() { int a[100],n,i; clrscr(); printf("\n\n Enter integer value for total no.s of elements to be sorted: "); scanf("%d",&n); for( i=0;i<=n-1;i++) { printf("\n\n Enter integer value for element no.%d : ",i+1); scanf("%d",&a[i]); } bubble(a,n); printf("\n\n Finally sorted array is: "); for( i=0;i<=n-1;i++) printf("%3d",a[i]); } //end program.

Selection sort
#include #include #define MAXSIZE 500 void selection(int elements[], int maxsize); int elements[MAXSIZE],maxsize; int main() { int i; printf(\nHow many elements you want to sort: ); scanf(%d,&maxsize); printf(\nEnter the values one by one: ); for (i = 0; i < maxsize; i++) { printf (\nEnter element %i :,i); scanf(%d,&elements[i]); } printf(\nArray before sorting:\n); for (i = 0; i < maxsize; i++) printf([%i], ,elements[i]); printf (\n); selection(elements, maxsize); printf(\nArray after sorting:\n); for (i = 0; i < maxsize; i++) printf([%i], , elements[i]); } void selection(int elements[], int array_size) { int i, j, k; int min, temp; for (i = 0; i < maxsize-1; i++) { min = i; for (j = i+1; j < maxsize; j++) { if (elements[j] < elements[min]) min = j; } temp = elements[i]; elements[i] = elements[min]; elements[min] = temp; } }

5.3 Pointers and Arrays


The declaration int a[10]; defines an array of size 10, that is, a block of 10 consecutive objects named a[0], a[1], ...,a[9]. The notation a[i] refers to the i-th element of the array. If pa is a pointer to an integer, declared as int *pa; then the assignment pa = &a[0]; sets pa to point to element zero of a; that is, pa contains the address of a[0].

If pa points to a particular element of an array, then by definition pa+1 points to the next element, pa+i points i elements after pa, and pa-i points i elements before. Thus, if pa points to a[0], *(pa+1) refers to the contents of a[1], pa+i is the address of a[i], and *(pa+i) is the contents of a[i]. Since the name of an array is a synonym for the location of the initial element, the assignment pa=&a[0] can also be written as pa = a; a[i] can also be written as *(a+i)

STRINGS
A string is an array of characters. Strings must have a \0 or null character after the last character to show where the string ends. The null character is not included in the string. There are 2 ways of using strings. The first is with a character array and the second is with a string pointer. A character array is declared in the same way as a normal array.
char ca[10];

You must set the value of each individual element of the array to the character you want and you must make the last character a 0. Remember to use %s when printing the string.
char ca[10]; ca[0] = 'H'; ca[1] = 'e'; ca[2] = 'l'; ca[3] = 'l'; ca[4] = 'o'; ca[5] = 0; printf("%s",ca);

C Programming - Handling of Character String


In C language, strings are stored in an array of char type along with the null terminating character "\0" at the end. In other words to create a string in C you create an array of chars and set each element in the array to a char value that makes up the string. When sizing the string array you need to add plus one to the actual size of the string to make space for the null terminating character, "\0" Syntax to declare a string in C: Sample Code
char fname[4];

The above statement declares a string called fname that can take up to 3 characters. It can be indexed just as a regular array as well. fname[] = {'t','w','o'};

Charact er ASCII Code

t 11 6

w 11 9

o 4 1

\ 0 0

The last character is the null character having ASCII value zero. Initializing Strings To initialize our fname string from above to store the name Brian, Sample Code
char fname[31] = {"Brian"};

You can observe from the above statement that initializing a string is same as with any array. However we also need to surround the string with quotes. Writing Strings to the Screen To write strings to the terminal, we use a file stream known as stdout. The most common function to use for writing to stdout in C is the printf function, defined as follows: Sample Code
printf("Please type a name: \n");

The above statement prints the prompt in the quotes and moves the cursor to the next line. If you wanted to print a string from a variable, such as our fname string above you can do this: Sample Code
printf("First Name: %s", fname);

Reading Strings from the Terminal When we read a string from the terminal we read from a file stream known as stdin.
#include <stdio.h> void main() { char fname[30]; char lname[30]; printf("Type first name:\n"); scanf("%s", fname); printf("Type last name:\n"); scanf("%s", lname); printf("Your name is: %s %s\n", fname, lname); }

We declare two strings fname and lname. Then we use the printf function to prompt the user for a first name. The scanf function takes the input from stdin and automatically exits once the user presses enter. Then we repeat the above sequence except using the last name this time. Finally we print the full name that was typed back to stdout. Should look something like this: STRING OPERATIONS Character arrays are a special type of array that uses a "\0" character at the end. As such it has it is own header library called string.h that contains built-in functions for performing operations on these specific array types. You must include the string header file in your programs to utilize this functionality. Sample Code Length of a String Use the strlen function to get the length of a string minus the null terminating character.
#include <string.h>

Sample Code If we had a string, and called the strlen function on it we could get its length. Sample Code
char fname[30] = {"Bob"}; int length = strlen(fname); int strlen(string);

This would set length to 3. CONCATENATION OF STRINGS The strcat function appends one string to another. Sample Code The first string gets the second string appended to it. So for example to print a full name from a first and last name string we could do the following: Sample Code
char fname[30] = {"Bob"}; char lname[30] = {"by"}; printf("%s", strcat(fname, lname)); char *strcat(string1, string2);

The output of this snippet would be "Bobby." COMPARE TWO STRINGS Sometimes you want to determine if two strings are the same. For this we have the strcmp function. Sample Code The return value indicates how the 2 strings relate to each other. if they are equal strcmp returns 0. The value will be negative if string1 is less than string2, or positive in the opposite case. For example if we add the following line to the end of our getname.c program: Sample Code
printf("%d", strcmp(fname, lname)); int strcmp(string1, string2);

When run on a Linux computer with the following first and last name combinations, the program will yield the following output. Sample Code
First name: Bob, last name: bob, output: -1. First name: bob, last name: Bob, output 1. First name: Bob, last name: Bob, output 0.

COMPARE TWO STRINGS (NOT CASE SENSITIVE) If you do not care whether your strings are upper case or lower case then use this function instead of the strcmp function. Other than that, it's exactly the same. Sample Code
int strcmpi(string1, string2);

Imagine using this function in place of strcmp in the above example, all of the first and last combinations would output 0. COPY STRINGS To copy one string to another string variable, you use the strcpy function. This makes up for not being able to use the "=" operator to set the value of a string variable. Sample Code
strcpy(string1, string2);

To set the first name of our running example in code rather than terminal input we would use the following: Sample Code
strcpy(fname, "Bob");

CONVERTING UPPERCASE STRINGS TO LOWERCASE STRINGS This function is not part of the ANSI standard and therefore strongly recommended against if you want your code to be portable to platforms other than Windows. Sample Code
strlwr(string);

This will convert uppercase characters in string to lowercase. So "BOBBY" would become "bobby". REVERSING THE ORDER OF A STRING This function is not part of the ANSI standard and therefore strongly recommended against if you want your code to be portable to platforms other than Windows. Sample Code
strrev(string);

Will reverse the order of string. So if string was "bobby", it would become "ybbob". CONVERTING LOWERCASE STRINGS TO UPPERCASE STRINGS This function is not part of the ANSI standard and therefore strongly recommended against if you want your code to be portable to platforms other than Windows. strupr(string); This will convert lowercase characters in string to uppercase. So "bobby" would become "BOBBY".

C Programming - Structures and Unions


Structures are slightly different from the variable types you have been using till now. Structures are data types by themselves or known as user defined data type . When you define a structure or union, you are creating a custom data type.

Structures
Structures in C are used to encapsulate, or group together different data into one object. You can define a Structure as shown below: Sample Code
1. 2. 3. 4. 5. struct object { char id[20]; int xpos; int ypos; };

Structures can group data of different types as you can see in the example of a game object for a video game. The variables you declare inside the structure are called data members.

Initializing a Structure
Structure members can be initialized when you declare a variable of your structure: Sample Code

1.

struct object player1 = {player1, 0, 0};


Copyright exforsys.com

The above declaration will create a struct object called player1 with an id equal to player1, xpos equal to 0, and ypos equal to 0. To access the members of a structure, you use the . (scope resolution) operator. Shown below is an example of how you can accomplish initialization by assigning values using the scope resolution operator: Sample Code
1. 2. 3. 4. struct object player1; player1.id = player1; player1.xpos = 0; player1.ypos = 0;
Copyright exforsys.com

Functions and Structures


Since structures are of custom data types, functions can return structures and also take them as arguments. Keep in mind that when you do this, you are making a copy of the structure and all it's members so it can be quite memory intensive. To return a structure from a function declare the function to be of the structure type you want to return. In our case a function to initialize our object structure might look like this: Sample Code
1. 2. 3. 4. 5. 6. 7. 8. 9. struct object createobj(char id[], int xpos, int ypos) { struct object newobj; strcpy(newobj.id, name); newobj.xpos = xpos; newobj.ypos = ypos; return newobj; }

Pass Structure to a Function


Let us now learn to pass a structure to a function. As an example let us use a function that prints members of the structure passed to it: Sample Code
1. 2. 3. 4. 5. 6. void printobj(struct object obj) { printf(name: %s, , obj.id); printf(x position: %d, , obj.xpos); printf(y position: %d, obj.ypos); printf(\n); }

For completeness we shall include the full source of the above examples so you may see how it all fits together. object1.c:

Sample Code
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. #include <stdio.h> #include <stdlib.h> struct object { char id[20]; int xpos; int ypos; }; struct object createobj(char id[], int xpos, int ypos); void printobj(struct object obj); void main() { struct object player1 = createobj("player1", 0, 0); struct object enemy1 = createobj("enemy1", 2, 3); printobj(player1); printobj(enemy1); } struct object createobj(char id[], int xpos, int ypos) { struct object newobj; strcpy(newobj.id, id); newobj.xpos = xpos; newobj.ypos = ypos; return newobj; } void printobj(struct object obj) { printf("name: %s, ", obj.id); printf("x position: %d, ", obj.xpos); printf("y position: %d", obj.ypos); printf("\n"); }

Arrays of Structure
Since structures are data types that are especially useful for creating collection items, why not make a collection of them using an array? Let us now modify our above example object1.c to use an array of structures rather than individual ones. object2.c: Sample Code
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. #include <stdio.h> #include <stdlib.h> struct object { char id[20]; int xpos; int ypos; }; struct object createobj(char id[], int xpos, int ypos); void printobj(struct object obj); void main() { int i; struct object gameobjs[2]; gameobjs[0] = createobj("player1", 0, 0); gameobjs[1] = createobj("enemy1", 2, 3); for (i = 0; i < 2; i++) printobj(gameobjs[i]); //update enemy1 position gameobjs[1].xpos = 1; gameobjs[1].ypos = 2; for (i = 0; i < 2; i++)

29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45.

printobj(gameobjs[i]);

struct object createobj(char id[], int xpos, int ypos) { struct object newobj; strcpy(newobj.id, id); newobj.xpos = xpos; newobj.ypos = ypos; return newobj; } void printobj(struct object obj) { printf("name: %s, ", obj.id); printf("x position: %d, ", obj.xpos); printf("y position: %d", obj.ypos); printf("\n"); }

We create an array of structures called gamobjs and use the createobj function to initialize it's elements. You can observer that there is not much difference between the two programs. We added an update for the enemy1's position to show how to access a structure's members when it is an element within an array.

Structure within a Structure


Structures may even have structures as members. Imagine our x, y coordinate pair is a structure called coordinates. We can redeclare our object structure as follows: Sample Code
1. 2. 3. 4. struct object { char id[20]; struct coordinates loc; };

You can still initialize these by using nested braces, like so: Sample Code
1. struct object player1 = {player1, {0, 0}};

To access or set members of the above internal structure you would do like this: Sample Code
1. 2. 3. 4. struct object player1; player1.id = player1; player1.loc.xpos = 0; player1.loc.ypos = 0;

You simply add one more level of scope resolution.

Unions
Unions and Structures are identical in all ways, except for one very important aspect. Only one element in the union may have a value set at any given time. Everything we have shown you for structures will work for unions, except for setting more than one of its members at a time. Unions are mainly used to conserve memory. While each member within a structure is assigned its own unique storage area, the members that compose a union share the common storage area within the memory. Unions are useful for application involving multiple members where values are not assigned to all the members at any one time. Sample Code
1. 2. 3. struct object { char id[20]; struct coordinates loc;

4. 5. 6. 7. 8.

union deadoralive { int alive; int dead; } };

Only dead or alive can be set to anything at any one time. You can get to it the same as with a structure inside a structure as we learned in the last section.
C Programming - Pointers

Pointers are widely used in programming; they are used to refer to memory location of another variable without using variable identifier itself. Diagram 1 illustrates the idea of pointers. As you can see below; Yptr is pointing to memory address 100.

Diagram 1: 1. Pointer and memory relationship

Pointer Declaration
To declare pointer variable we need to use * .Pointer can only point to variable of the same data type.
Syntax

Sample Code
1. Datatype * identifier;

Example

Character Pointer Sample Code


1. 2. 3. 4. 5. 6. #include <stdio.h> int main() { char a='b'; char *ptr; printf("%cn",a);

7. 8. 9. 10. 11. 12.

ptr=&a; printf("%pn",ptr); *ptr='d'; printf("%cn",a); return 0; }

Description of code: In line 1 we are declaring char variable called a; it is initialized to character b, in line 2, the pointer variable ptr is declared. In line 4, the address of variable a is assigned to variable ptr. In line 6 value stored at the memory address that ptr points to is changed to d Note: & notation means address-of operand in this case &a means address-of a.

Address operator
Address operator (&) is used to get the address of the operand. For example if variable x is stored at location 100 of memory; &x will return 100. This operator is used to assign value to the pointer variable. It is important to remember that you MUST NOT use this operator for arrays, no matter what data type the array is holding. This is because array identifier (name) is pointer variable itself. When we call for ArrayA[2]; ArrayA returns the address of first item in that array so ArrayA[2] is the same as saying ArrayA+=2; and will return the third item in that array.

Pointer arithmetic
Pointers can be added and subtracted. However pointer arithmetic is quite meaningless unless performed on arrays. Addition and subtraction are mainly for moving forward and backward in an array. Note: you have to be very careful NOT to exceed the array elements when you use arithmetic; otherwise you will get horrible errors such as access violation. This error is caused because your code is trying to access a memory location which is registered to another program. Operator ++ --= or += or +
Example:

Result Goes to the next memory location that the pointer is pointing to. Goes to the previous memory location that the pointer is pointing to. Subtracts value from pointer. Adding to the pointer

Array and pointer arithmetic Sample Code


1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. #include <stdio.h> int main() { int ArrayA[3]={1,2,3}; int *ptr; ptr=ArrayA; printf("address: %p - array value:%d n",ptr,*ptr); ptr++; printf("address: %p - array value:%d n",ptr,*ptr); return 0; }

Code 2 result Description of code 2: in line 1 we are declaring ArrayA integer array variable initialized to numbers 1,2,3, in line 2, the pointer variable ptr is declared. In line 3, the address of variable ArrayA is assigned to variable ptr. In line 5 ptr is incremented by 1. Note: & notation should not be used with arrays because arrays identifier is pointer to the first element of the array.

Pointers and functions


Pointers can be used with functions. The main use of pointers is call by reference functions. Call by reference function is a type of function that has pointer/s (reference) as parameters to that function. All calculation of that function will be directly performed on referred variables. Sample Code
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. #include <stdio.h> void DoubleIt(int *num) { *num*=2; } int main() { int number=2; DoubleIt(&number); printf("%d",number); return 0; }

Description of code 3: in line 1 we are declaring DoubleIt function, in line 4, the variable number is declared and initialized to 2. In line 5, the function DoubleIt is called.

Pointer to Arrays
Array identifier is a pointer itself. Therefore & notation shouldnt be used with arrays. The example of this can be found at code 3. When working with arrays and pointers always remember the following:

Never use & for pointer variable pointing to an array. When passing array to function you dont need * for your declaration. Be VERY CAREFUL not to exceed number of elements your array holds when using pointer arithmetic to avoid errors.

Pointers and Structures


Pointers and structures is broad topic and it can be very complex to include it all in one single tutorial. However pointers and structures are great combinations; linked lists, stacks, queues and etc are all developed using pointers and structures in advanced systems.
Example:

Number Structure Sample Code


1. 2. 3. 4. #include <stdio.h> struct details { int num;

5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18.

}; int main() { struct details MainDetails; struct details *structptr; structptr=&MainDetails; structptr->num=20; printf("n%d",MainDetails.num); return 0; }

Figure 4. code 4 result Description of code 4: in line 1-3 we are declaring details structure, in line 4, the variable Maindetails is declared.in line 6, pointer is set to point to MainDetails. In line 7, 20 is assigned to MainDetails.num through structptr->num.

Pointer to Pointer
Pointers can point to other pointers; there is no limit whatsoever on how many pointer to pointer links you can have in your program. It is entirely up to you and your programming skills to decide how far you can go before you get confused with the links. Here we will only look at simple pointer to pointer link. Pointing to pointer can be done exactly in the same way as normal pointer. Diagram below can help you understand pointer to pointer relationship.

Diagram 2. Simple pointer to pointer relationship Code for diagram 2: Char *ptrA; Char x=b; Char *ptrb; ptrb=&x; ptrA=&ptrb; ptrA gives 100, *ptrA gives 101 , ptrb is 101 ,*ptrb gives b, **ptrA gives b comment: **ptrA means value stored at memory location of value stored in memory location stored at PtrA

C Language - The Preprocessor


Preprocessor is a program that processes the code before it passes through the compiler. It operates under the control of preprocessor command lines and directives. Preprocessor directives are placed in the source program before the main line before the source code passes through the compiler it is examined by the preprocessor for any preprocessor directives. If there is any appropriate actions are taken then the source program is handed over to the compiler. Preprocessor directives follow the special syntax rules and begin with the symbol #bin column1 and do not require any semicolon at the end. A set of commonly used preprocessor directives Preprocessor directives:
Directive #define #undef #include #ifdef #endif #ifndef #if #else Function Defines a macro substitution Undefines a macro Specifies a file to be included Tests for macro definition Specifies the end of #if Tests whether the macro is not def Tests a compile time condition Specifies alternatives when # if test fails

The preprocessor directives can be divided into three categories 1. Macro substitution division 2. File inclusion division 3. Compiler control division Macros: Macro substitution is a process where an identifier in a program is replaced by a pre defined string composed of one or more tokens we can use the #define statement for the task. It has the following form #define identifier string The preprocessor replaces every occurrence of the identifier int the source code by a string. The definition should start with the keyword #define and should follow on identifier and a string with at least one blank space between them. The string may be any text and identifier must be a valid c name. There are different forms of macro substitution. The most common form is 1. Simple macro substitution 2. Argument macro substitution 3. Nested macro substitution

Simple macro substitution: Simple string replacement is commonly used to define constants example: #define pi 3.1415926 Writing macro definition in capitals is a convention not a rule a macro definition can include more than a simple constant value it can include expressions as well. Following are valid examples:
#define AREA 12.36

Macros as arguments: The preprocessor permits us to define more complex and more useful form of replacements it takes the following form. # define identifier(f1,f2,f3..fn) string. Notice that there is no space between identifier and left parentheses and the identifier f1,f2,f3 . Fn is analogous to formal arguments in a function definition. There is a basic difference between simple replacement discussed above and replacement of macro arguments is known as a macro call A simple example of a macro with arguments is # define CUBE (x) (x*x*x) If the following statements appears later in the program, volume=CUBE(side); The preprocessor would expand the statement to volume =(side*side*side) Nesting of macros: We can also use one macro in the definition of another macro. That is macro definitions may be nested. Consider the following macro definitions # define SQUARE(x)((x)*(x)) Undefining a macro: A defined macro can be undefined using the statement # undef identifier. This is useful when we want to restrict the definition only to a particular part of the program.

File inclusion: The preprocessor directive "#include file name can be used to include any file in to your program if the function s or macro definitions are present in an external file they can be included in your file In the directive the filename is the name of the file containing the required definitions or functions alternatively the this directive can take the form #include< filename > Without double quotation marks. In this format the file will be searched in only standard directories. The c preprocessor also supports a more general form of test condition #if directive. This takes the following form #if constant expression { statement-1; statemet2 . . } #endif the constant expression can be a logical expression such as test < = 3 etc If the result of the constant expression is true then all the statements between the #if and #endif are included for processing otherwise they are skipped. The names TEST LEVEL etc., may be defined as macros.

RECURSION Recursive function is a function that contains a call to itself . Recursive function allows you to divide your complex problem into identical single simple cases which can handle easily. This is also a well-known computer programming technique: divide and conquer.

Note of Using Recursive Function


Recursive function must have at least one exit condition that can be satisfied. Otherwise, the recursive function will call itself repeatly until the runtime stack overflows.
# include<stdio.h> int factorial(int number) { if(number <= 1) return 1; return number * factorial(number - 1); } void main() { int x = 5; printf("factorial of %d is %d",x,factorial(x)); }

Call by Value and Call by Reference in Functions

Arguments in a function can be passed or function can be called as 1. Pass By Value


Passing a variable by value makes a copy of the variable before passing it onto a function. This means that if you try to modify the value inside a function, it will only have the modified value inside that function. One the function returns, the variable you passed it will have the same value it had before you passed it into the function.

2. Pass By Reference
Passing a variable by reference means when we pass address of the variable and the changes made in that variable in the function will automatically reflect back in variable. xytotals.c: Sample Code
1. 2. 3. #include <stdio.h> #include <stdlib.h>

4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36.

void printtotal(int total); void addxy(int x, int y, int total); void subxy(int x, int y, int *total); void main() { int x, y, total; x = 10; y = 5; total = 0; printtotal(total); addxy(x, y, total); printtotal(total); subxy(x, y, &total); printtotal(total);

void printtotal(int total) { printf("Total in Main: %dn", total); } void addxy(int x, int y, int total) { total = x + y; printf("Total from inside addxy: %dn", total); } void subxy(int x, int y, int *total) { *total = x - y; printf("Total from inside subxy: %dn", *total); }

There are three functions in the above program. In the first two functions variable is passed by value, but in the third function, the variable `total` is passed to it by reference. This is identified by the * operator in its declaration. The program prints the value of variable `total` from the main function before any operations have been performed. It has 0 in the output as expected. Then we pass the variables by value the 2nd function addxy, it receives a copy of `x`, `y`, and `total`. The value of `total` from inside that function after adding x and y together is 15. Notice that once addxy has exited and we print `total` again its value remains 0 even though we passed it from the main function. This is because when a variable is passed by value, the function works on a copy of that value. They were two different `total` variables in memory simultaneously. The one we set to 15 in the addxy function, was removed from memory once the addxy function finished executing. However, the original variable `total` remains 0 when we print its value from main. Now we subtract y from x using the subxy function. This time we pass variable `total` by reference (using the address of operator (&)) to the subxy function. Note how we use the dereference operator * to get the value of total inside the function. This is necessary, because you want the value in variable `total`, not the address of variable `total` that was passed in. Now we print the value of variable `total` from main again after the subxy function finishes. We get a value of 5, which matches the value of total printed from inside of subxy function. The reason is because by passing a variable total by reference we did not make a copy of the variable `total` instead we passed the address in memory of the same variable `total` used in the function main. In other words we only had one total variable during entire code execution time.

Call By Value In call by value the value of the variable passer to the function and it does not return any value

Call By Reference In call by reference the address of the variable is passed to the function and therefore any change made in the function is permanent since it affects the memory location Call by value is used to secure the value of the actual parameter which has been used as an argument to a function after coming back to to calling function.
main() { int x=50, y=70; interchange(&x,&y); printf(x=%d y=%d,x,y); } interchange(x1,y1) int *x1,*y1; { int z1; z1=*x1; *x1=*y1; *y1=z1; printf(*x=%d *y=%d,x1,y1); }

Call by reference is used to reflect the modification of value in actual parameter which has been assigned as an argument to a function after coming back from the called function Ex
main() { int x=50, y=70; interchange(x,y); printf(x=%d y=%d,x,y); } interchange(x1,y1) int x1,y1; { int z1; z1=x1; x1=y1; y1=z1; printf(x1=%d y1=%d,x1,y1); }

Here the value to function interchange is passed by value.

Here the function is called by reference. In other words address is passed by using symbol & and the value is accessed by using symbol *.

The main difference between them can be seen by analyzing the output of program1 and program2.

Storage Class: 'Storage' refers to the scope of a variable and memory allocated by compiler to store that variable. Scope of a variable is the boundary within which a variable can be used. Storage class defines the scope and lifetime of a variable. From the point view of C compiler, a variable name identifies physical location from a computer where variable is stored. There are two memory locations in a computer system where variables are stored as: Memory and CPU Registers.

Functions of storage class: To determine the location of a variable where it is stored ? Set initial value of a variable or if not specified then setting it to default value. Defining scope of a variable. To determine the life of a variable. Types of Storage Classes : Storage classes are categorised in 4 (four) types as,
1. 2. 3. 4.

Automatic Storage Class Register Storage Class Static Storage Class External Storage Class

Automatic Storage Class : o Keyword : auto o Storage Location : Main memory o Initial Value : Garbage Value o Life : Control remains in a block where it is defined. o Scope : Local to the block in which variable is declared. Syntax : auto [data_type] [variable_name]; Example : auto int a; Register Storage Class : o Keyword : register o Storage Location : CPU Register o Initial Value : Garbage o Life : Local to the block in which variable is declared. o Scope : Local to the block. Syntax : register [data_type] [variable_name]; Example : register int a;

Static Storage Class : o Keyword : static o Storage Location : Main memory o Initial Value : Zero and can be initialize once only. o Life : depends on function calls and the whole application or program. o Scope : Local to the block. Syntax : static [data_type] [variable_name]; Example : static int a; Static storage class can be used only if we want the value of a variable to persist between different function calls. External Storage Class : o Keyword : extern o Storage Location : Main memory o Initial Value : Zero o Life : Until the program ends. o Scope : Global to the program. Syntax : extern [data_type] [variable_name]; Example : extern int a; The variable access time is very fast as compared to other storage classes. But few registers are available for user programs. The variables of this class can be referred to as 'global or external variables.' They are declared outside the functions and can be invoked at anywhere in a program.

Enumerations
An enumeration is a data type consisting of a set of named values that represent integral constants, known as enumeration constants. An enumeration literally means a series, like 0, 1, 2, ..., etc. So, using enumerations in C is just an easy way to declare constants.

For example, instead of declaring 4 #define constants that all have arbitrary values, we could define them inside an enumeration, like this: #include <stdio.h> int main() { enum Days{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday}; Days TheDay; int j = 0; printf("Please enter the day of the week (0 to 6)\n"); scanf("%d",&j); TheDay = Days(j); if(TheDay == Sunday || TheDay == Saturday) printf("Hurray it is the weekend\n"); else printf("Curses still at work\n"); return 0; } DYNAMIC MEMORY ALLOCATION (CALLOC, SIZEOF, FREE) It is desirable to dynamically allocate space for variables at runtime. The C programming language allows users to dynamically allocate and deallocate memory when required. The functions that accomplish this are calloc(), which allocates memory to a variable, sizeof, which determines how much memory a specified variable occupies, and free(), which deallocates the memory assigned to a variable back to the system. Allocating a Block of Memory Use the malloc function to allocate a block of memory for a variable. If there is not enough memory available, malloc will return NULL. The prototype for malloc is: Sample Code 1. void *malloc(size_t size);

Do not worry about the size of your variable, there is a nice and convenient function that will find it for you, called sizeof. Most calls to malloc will look like the following example: Sample Code 1. ptr = (struct mystruct*)malloc(sizeof(struct mystruct)); This way you can get memory for your structure variable without having to know exacly how much to allocate for all its members as well.

Allocating Multiple Blocks of Memory You can also ask for multiple blocks of memory with the calloc function: Sample Code 1. void *calloc(size_t num, size_t size); If you want to allocate a block for a 10 char array, you can do this: Sample Code 1. char *ptr; 2. ptr = (char *)calloc(10, sizeof(char)); The above code will give you a chunk of memory the size of 10 chars, and the ptr variable would be pointing to the beginning of the memory chunk. If the call fails, ptr would be NULL. Releasing the Used Space All calls to the memory allocating functions discussed here, need to have the memory explicitly freed when no longer in use to prevent memory leaks. Just remember that for every call to an *alloc function you must have a corresponding call to free. The function call to explicitly free the memory is very simple and is written as shown here below: Sample Code 1. free(ptr); COMMAND LINE ARGUMENTS Command-line arguments are given after the name of a program in command-line operating systems like DOS or Linux, and are passed in to the program from the operating system. main can actually accept two arguments: one argument is number of command line arguments, and the other argument is a full list of all of the command line arguments. The full declaration of main looks like this:
int main ( int argc, char *argv[] )

The integer, argc is the argument count. It is the number of arguments passed into the program from the command line, including the name of the program. The array of character pointers is the listing of all the arguments.

#include <stdio.h> int main ( int argc, char *argv[] ) { int i;

for (i=1;i<argc;i++) printf(%s,*(argv+i)); }

You might also like