Page 1 :
1, Programming for Problem Solving, (KCS-101), , (PART-III), , Modular programming: Modular programming is also known as function programming in C because it, consists of various small blocks of code known as ‘module’ or ‘function’., , Functions in C: A function is a self contained block of code (or set of instructions) to carry out a, particular task., There are two types of functions available in C:, 1. Built-in or Pre-defined or Library functions, 2. User defined functions, Built-in functions are predefined in library and their prototype has already been declared in header files., e.g. printf(), scanf(), getch() etc., Here, we will discuss only user defined functions. Following points illustrate it:, ➢ User defined function behave similar to built-in functions but it consists of declaration part before, definition and calling in the function., ➢ All the user defied functions should have its parent function called main function., ➢ However user defined function may call any other user defined function., ➢ If any C program has only one function then it is definitely main function., Syntax for user defined function: There are three parts of a user defined function:, a) Function declaration or Function prototype, b) Function definition, c) Function call, , a) Function Declaration: Functions need to be declared before their use like variables. The syntax for, function declaration is given as:, return _type function_name (argument_list with data types);, OR, return _type function_name (parameter_list with data types);, Here,, (i), (ii), (iii), (iv), (v), , return_type → the type of value returned by function., function_name → unique name identifying function., argument_list or parameter_list → list of types & names of parameters (separated by, commas)., return_type and argument_list may be int, float, char, void, double, long double etc., The declaration should end with semicolon (;)., , Examples: int factorial (int);, float addition (float , float);, NOTE:
Page 2 :
2, (i), (ii), , Declaration part may be avoided if definition starts before main body., Function name should be valid identifier; not any built-in function name., , b) Function Definition: Defining a function means writing the actual code for function which performs, the specific task. Definition of any user defined function always given outside the main body the syntax of, definition is as follows:, return _type function_name (argument_list with data types), {, // start of function body, statement1;, :, ., :, statementN;, }, // end of function body, For Example:, // function definition for computing factorial of a number and return to main body, int factorial (int x), {, if (x==1), return (1);, else, return (x*factorial (x-1));, }, , c) Function Call: In order to use the defined function in a program, we need to access it by calling it using a, function call. User defined functions may call any function by its name and with or without parameter as they, are declared and defined. There should be no mismatching in each part., The function which is called in other function is known as called (or “callee”) function whereas the, function which has called that function, is known as calling (or “caller”) function., E.g. Let above function to be called inside the main body as shown below:, void main(), {, int a, fact;, printf (“enter the number”);, scanf(“%d”,&a);, fact = factorial (a);, //calling of factorial( ), printf (“the factorial of number is=%d”, fact);, getch ();, }, , ❖ Types of functions: Functions can be categorized in following ways:, 1) Functions with NO arguments & NO return value: These types of functions neither, receive any input (i.e. arguments) from the calling function nor they return any value. They simply, perform their specified task when called. Therefore their return_type & argument_list is declared as, void. So the syntax for such type of functions is:
Page 3 :
3, void function_name (void) OR, , void function_name ( ), , //Program to calculate sum of given two numbers, #include<stdio.h>, #include<conio.h>, void add ();, // Function declaration with NO arguments & NO return value, void main(), {, add ();, //calling of function, getch ();, }, // Function definition, void add (), {, int x, y, sum;, printf (“Enter any two numbers”);, scanf(“%d%d”, &x, &y);, sum = x+y;, printf (“The sum is=%d”, sum);, }, 2) Functions with arguments & NO return value: These types of functions only receive the, arguments (parameters) from the calling function but they do not return any value. After receiving, value they perform their specified task when called and display the result, if required., The syntax for such type of functions is:, void function_name (argument_list), , OR, , void function_name (parameter_list), , //Program to calculate sum of given two numbers, #include<stdio.h>, #include<conio.h>, void add (int, int);, // Function declaration with arguments & NO return value, void main(), {, int a, b;, printf (“Enter any two numbers”);, scanf(“%d%d”, &a, &b);, add (a,b);, //calling of function, getch ();, }, // Function definition, void add (int x, int y), {, int sum;, sum = x+y;, printf (“The sum is=%d”, sum);, }
Page 4 :
4, 3) Functions with arguments & return value: These types of functions receive the arguments, (parameters) from the calling function and also return value i.e. after performing the specified task, they return the computed result to the calling function., The syntax for such type of functions is:, return_type function_name (argument_list), OR, return_type function_name (parameter_list), //Program to calculate sum of given two numbers, #include<stdio.h>, #include<conio.h>, int add (int, int);, // Function declaration with arguments & return value, void main(), {, int a, b, result;, printf (“Enter any two numbers”);, scanf(“%d%d”, &a, &b);, result = add (a,b);, //calling of function, printf (“The sum is=%d”, sum);, getch ();, }, // Function definition, void add (int x, int y), {, int sum;, sum = x+y;, return sum;, }, 4) Functions with NO arguments but return a value: These types of functions neither receive, any input (i.e. arguments) from the calling function nor they return any value. They simply perform, their specified task when called. Therefore their return_type & argument_list is declared as void. So, the syntax for such type of functions is:, void function_name (void) OR, , void function_name ( ), , //Program to calculate sum of given two numbers, #include<stdio.h>, #include<conio.h>, int add ();, // Function declaration with NO arguments & but return value, void main(), {, int result;, result = add ();, //calling of function, printf (“The sum is=%d”, result);, getch ();, }
Page 5 :
5, // Function definition, int add (), {, int x, y, sum;, printf (“Enter any two numbers”);, scanf(“%d%d”, &x, &y);, sum = x+y;, return sum;, }, , Recursive Functions: A function which can call itself is known as recursive function. These functions, are used to solve certain problems which are recursive in nature such as computing factorial of a number or, Fibonacci series etc., //Program to compute factorial of given number using recursion, #include<stdio.h>, #include<conio.h>, int factorial (int);, // Function declaration, void main(), {, int a, fact;, printf (“enter the number”);, scanf(“%d”,&a);, fact = factorial (a);, // Calling factorial( ) function, printf (“the factorial of number is=%d”, fact);, getch ();, }, int factorial (int x), // Function definition, {, if (x==1), return (1);, else, return (x*factorial (x-1));, }, , Scope Rules: A main program could contain many functions as well as any function can contain any other, function also within them (i.e. nested functions). Scope rules are the rules that govern the visibility region (i.e., accessibility) for a piece of code (or entity) in the program., Scope rules are:, 1. The scope of an entity is the region where it is declared (i.e. local or global)., 2. A global entity is visible to all, including the function in which that entity is declared., 3. An entity declared in the scope of another entity is always a different entity, even if, their names are, identical., NOTE: If a function has variable declarations inside its own body, it referred to as local variables (unknown, to other functions) hence no other function can access those variables; whereas variables which are declared, outside all the functions and can be accessed by all functions referred to as global variables., , Refer to class notes for more programs…, *****************************************************************************
Page 6 :
6, UNIT - IV, Arrays: Array is a collection of similar (homogenous) data type items where a single variable holds only, one value at a time in the memory. Arrays require contiguous memory locations to store data., Array declaration syntax:, •, •, •, , data_type array_name [size];, , data_type may be any fundamental data type such as int, char, float, double etc., array_name is any valid identifier., size should be any integer constant value., , For example:, •, •, , int num [10];, , Here, num is an integer array which can hold maximum 10 integers starting from location 0 to (size - 1), i.e. 0 to 9 in this case., The address of num starts from index 0 and next element is stored in just contiguous (adjacent) memory, location as shown below:, , For example:, , int num [10] = {18, 128, 20, 35, 254, 65, 35, 70, 83, 105};, , All 10 elements shown as:, 18, , 128, , 20, , 35, , 254, , 65, , 35, , 70, , 83, , 105, , num[0] num[1] num[2] num[3] num[4] num[5] num[6] num[7] num[8] num[9], NOTE: In the case of character array, the last element is special null character (‘\0’) are stored. It means if we, declare character array of size 10 then only 9 characters can be stored starting from index 0 to 8 and at last null, character ‘\0’stored at index 9 as shown below (detailed study of character arrays is given under the topic, STRINGS):, char ch[10] = {‘A’, ’B’, ’C’, ’D’, ’E’, ’F’, ’G’, ’H’, ’I’, ’\0’};, , For example:, ‘A’, , ‘B’, , ‘C’, , ‘D’, , ‘E’, , ‘F’, , ‘G’, , ‘H’, , ‘I’, , ‘\0’, , ch[0], , ch[1], , ch[2], , ch[3], , ch[4], , ch[5], , ch[6], , ch[7], , ch[8], , ch[9], , This is called linear array or one dimension. Memory occupied by linear array is computed as:, Memory occupied by linear array = size of data type * size of array, In above case, num occupies 2*10 = 20 bytes and ch occupies 1*10=10 bytes contiguous memory, blocks., NOTE: For the computation of ith location address following formula applies:, Address of ith location = base address + data type size * (i - 1), base address is address for 0th element and data type size → (for int = 2 bytes, char = 1 byte, float = 4, bytes, double = 8 bytes, long double = 10 bytes).
Page 7 :
7, Program: Program that prints out the memory locations in which the elements of this array are stored., , main( ), {, int num[ ] = { 24, 34, 12, 44, 56, 17 } ;, int i ;, for ( i = 0 ; i <= 5 ; i++ ), {, printf ( "\nelement no. %d\t ", i ) ;, printf ( "address = %u", &num[i] ) ;, }, }, The output of this program would look like this:, , element no. 0, element no. 1, element no. 2, element no. 3, element no. 4, element no. 5, Program:, , address = 65512, address = 65514, address = 65516, address = 65518, address = 65520, address = 65522, //Program to access the elements of array, void main( ), {, int num[ ] = { 24, 34, 12, 44, 56, 17 } ;, int i ;, for ( i = 0 ; i <= 5 ; i++ ), {, printf ( "\n address = %u \t", &num[i] ) ;, printf ( "element = %d", num[i] ) ;, }, }, , The output of this program would be:, address = 65512, address = 65514, address = 65516, address = 65518, address = 65520, address = 65522, , element = 24, element = 34, element = 12, element = 44, element = 56, element = 17, , // program for accessing array elements, void main(), {, int i;, int num[5]={1,2,3,4,5};, for (i=0;i<5;i++), printf(“%d\t”, num[i]);, }, Output: 1, 2, 3, 4, 5
Page 8 :
8, Similarly, we can store element in the array using scanf () function., Program: Write a program to find average marks obtained by a class of 30 students in a test., main( ), {, int avg, sum = 0, i ;, int marks[30] ;, printf ( "\nEnter marks of 30 students:" ) ;, for ( i = 0 ; i <= 29 ; i++ ), {, scanf ( "%d", &marks[i] ) ;, }, for ( i = 0 ; i <= 29 ; i++ ), sum = sum + marks[i] ;, avg = sum / 30 ;, printf ( "\nAverage marks = %d", avg ) ;, }, , /* array declaration */, , /* store data in array */, , /* read & add data from array*/, , Multidimensional array: C permits multi-dimensional arrays. It is possible for arrays to have two or, more dimensions. The two-dimensional array is also called a “matrix”., Two dimensional arrays can be manipulated by matrix of m x n size by declaring as:, , a[m][n];, , E.g. int num[2][5] can be initialize as:, num[2][5] = { {12, 32, 63, 94, 75}, {68, 87, 28, 29, 70} };, NOTE: In the same way character & floating point arrays can also be initialized., , Storing two dimensional array elements in the memory: The above 2-D array can be shown as, below by matrix form., Column→ 0, Row 0, 12, Row 1, 68, , 1, 32, 87, , 2, 63, 28, , 3, 94, 29, , 4, 75, 70, , NOTE: The 2-D arrays can be stored in the memory either by row-major order or column-major order. Since, elements are stored only in contiguous locations in memory. Hence, in row-major order elements are stored row, by row and in column-major order elements are stored column by column., Above array can be stored in memory as below:, 1. Row-major order:, , num[0][0] =, num[0][1] =, num[0][2] =, num[0][3] =, num[0][4] =, num[1][0] =, num[1][1] =, num[1][2] =, num[1][3] =, num[1][4] =
Page 9 :
9, And column major order as shown below:, , num[0][0]=, num[1][0]=, num[0][1]=, num[1][1]=, num[0][2]=, num[1][2]=, num[0][3]=, num[1][3]=, num[0][4]=, num[1][4]=, NOTE: In C language, by default array elements are stored in row-major order., , Initializing a 2-Dimensional Array: 2-D arrays can be initialized at run time (dynamically) or at compile, time (statically) as required., , ➢ Dynamic initialization:, void main( ), {, int stud[4][2] ;, int i, j ;, for ( i = 0 ; i <= 3 ; i++ ), {, printf ( "\n Enter roll no. and marks" ) ;, scanf ( "%d %d", &stud[i][0], &stud[i][1] ) ;, }, for ( i = 0 ; i <= 3 ; i++ ), printf ("\n%d \t%d", stud[i][0], stud[i][1] ) ;, }, , /* 2-D array declaration */, , /* store data in array */, , /* read data from array*/, , ➢ Static initialization:, void main( ), {, int stud[4][2] = {, { 1234, 56 },, { 1212, 33 },, { 1434, 80 },, { 1312, 78 }, };, or even this would work..., int stud[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ;, There are two parts to the program—in the first part through a for loop we read in the values of roll no., and marks, whereas, in second part through another for loop we print out these values. Following figure shows, the arrangement of respective row & column values of matrix.
Page 10 :
10, column No. 0, , column No. 1, , row no. 0, , 1234, , 56, , row no. 1, , 1212, , 33, , row no. 2, , 1434, , 80, , row no. 3, , 1312, , 78, , NOTE: It is important to remember that while initializing a 2-D array it is necessary to mention the second, (column) dimension, whereas the first dimension (row) is optional., Thus the declarations,, int arr[2][3] = { 12, 34, 23, 45, 56, 45 } ;, int arr[ ][3] = { 12, 34, 23, 45, 56, 45 } ; are perfectly acceptable,, Whereas,, int arr[2][ ] = { 12, 34, 23, 45, 56, 45 } ;, int arr[ ][ ] = { 12, 34, 23, 45, 56, 45 } ; would never work., , Varying size arrays:, (i) The size of array is fixed but in some compilers, it is permitted to give size of array at run time. This type, of array is known as varying size array. Varying or unknown size array are used to implement stack and, queue data structures. This saves the memory at run time., (ii) In some cases, it is not known to programmer that how much length should declare to array. Such type of, situation can be handled by varying size array., , Refer to class notes for more programs…, *****************************************************************************, , Strings: The way a group of integers can be stored in an integer array, similarly a group of characters can be, stored in a character array. Character arrays are also called strings., A string constant is a one-dimensional array of characters terminated by a null ( ‘\0’ ). For example,, char name[ ] = { 'R', 'A', 'J', 'E', 'E', 'V', '\0' } ;, Each character in the array occupies one byte of memory and the last character is always ‘\0’. What, character is this? It looks like two characters, but it is actually only one character, with the \ indicating that what, follows it is something special. ‘\0’ is called null character. Note that ‘\0’ and ‘0’ are not same. ASCII value of, ‘\0’ is 0, whereas ASCII value of ‘0’ is 48., The terminating null (‘\0’) is important, because it is the only way the functions that work with a string, can know where the string ends., Example figure of character array has been shown (under the topic ARRAYS) for the way a character, array is stored in memory. Note that the elements of the character array are stored in contiguous memory locations., C provides a shortcut for initializing strings. For example, the string used above can also be initialized as,, char name[ ] = "RAJEEV" ;
Page 11 :
11, We can use any case (upper case / lower case) or mixture of cases while initializing strings as:, char name[ ] = "Rajeev" ;, Note that, in this declaration ‘\0’ is not necessary. C inserts the null character automatically., Program to demonstrate printing of a string in three different ways:, 1. By testing end of character array value:, void main( ), {, char name[ ] = "Rajeev" ;, int i = 0 ;, while ( i <= 5 ), {, printf ( "%c", name[i]) ;, i++ ;, }, }, Output:, Rajeev, 2. As we know that each character array always ends with a ‘\0’. Therefore, can also write the while loop, without using the final value i.e., void main( ), {, char name[ ] = "Rajeev" ;, int i = 0 ;, while ( name[i] != `\0' ), {, printf ( "%c", name[i] ) ;, i++ ;, }, }, Output:, Rajeev, 3. printf( ) function has got a very simple way of doing it, as shown below:, void main( ), {, char name[ ] = "Rajeev" ;, printf ( "%s", name ) ;, }, Output: Rajeev, NOTE: The %s used in printf( ) is a format specification for printing out a string., The same specification can be used to receive a string from the keyboard, as shown below., void main( ), {
Page 12 :
12, char name[25] ;, printf ( "Enter your name " ) ;, scanf ( "%s", name ) ;, printf ( "Hello %s!", name ) ;, }, While entering the string using scanf( ) we must be careful about two things:, ➢ The length of the string should not exceed the dimension of the character array. This is because the C, compiler doesn’t perform bounds checking on character arrays., ➢ scanf( ) is not capable of receiving multi-word strings. Therefore names such as ‘Rajeev Kumar’ would, be unacceptable. The way to overcome this limitation is by using the in-built function gets( ). The usage, of functions gets( ) and its counterpart puts( ) is shown below:, void main( ), {, char name[25] ;, printf ( "Enter your full name " ) ;, gets ( name ) ;, puts ( "Hello!" ) ;, puts ( name ) ;, }, The program and the output are self-explanatory except for the fact that, puts( ) can display only one string at a, time (hence the use of two puts( ) in the program above)., NOTE: gets( ) is capable of receiving only one string at a time but the plus point with gets( ) is that it can receive, a multi-word string., , Standard Library String Functions: With every C compiler a large set of useful string handling, library functions are provided. Following figure lists the more commonly used functions along with their purpose., Function, strlen, strlwr, strupr, strcat, strncat, strcpy, strncpy, strcmp, strncmp, , strcmpi, , Use, Finds length of a string, Converts a string to lowercase, Converts a string to uppercase, Appends one string at the end of, another, Appends first n characters of a string, at the end of another, Copies a string into another, Copies first n characters of one string, into another, Compares two strings, Compares first n characters of two, strings
Page 13 :
13, stricmp, strnicmp, strdup, strchr, strrchr, strstr, strset, strnset, strrev, , Compares two strings without regard, to case ("i" denotes that this function, ignores case), Compares two strings without regard, to case (identical to strcmpi), Compares first n characters of two, strings without regard to case, Duplicates a string, Finds first occurrence of a given, character in a string, Finds last occurrence of a given, character in a string, Finds first occurrence of a given string, in another string, Sets all characters of string to a given, character, Sets first n characters of a string to a, given character, Reverses string, , Out of the above list we shall discuss the functions strlen( ), strcpy( ), strcat( ) and strcmp( ), since these are, the most commonly used functions., , strlen( ) → This function counts the number of characters present in a string. Its usage is illustrated in the, following program., void main( ), {, char arr[ ] = "Introduction" ;, int len1, len2 ;, len1 = strlen ( arr ) ;, len2 = strlen ( "String Handling" ) ;, printf ( "\nstring = %s \t length = %d", arr, len1 ) ;, printf ( "\nstring = %s \t length = %d", " String Handling", len2 ) ;, }, The output would be..., string = Introduction, length = 12, string = String Handling, length = 15, , strcpy( ) → This function copies the contents of one string into another. The base addresses of the source, and target strings should be supplied to this function. Here is an example of strcpy( ) in action..., #include<string.h>, void main( ), {, char str1[20], str2[20];, printf ( "Enter the string:\t") ;, gets(str1);, printf ( "\n The copied string is: %s", strcpy (str2, str1)) ;
Page 14 :
14, getch();, }, And here is the output..., Enter the string:, Windows, The copied string is: Windows, NOTE: On supplying the base addresses, strcpy( ) goes on copying the characters in source string into the target, string till it doesn't encounter the end of source string (‘\0’). It is our responsibility to see to it that the target, string’s dimension is big enough to hold the string being copied into it., , strcat( ) → This function concatenates the source string at the end of the target string. Here is an example of, strcat( ) at work., void main( ), {, char source[ ] = "Students!" ;, char target[30] = "Hello" ;, strcat ( target, source ) ;, printf ( "source string = %s", source ) ;, printf ( "\n target string = %s", target ) ;, }, And here is the output..., source string = Students!, target string = HelloStudents!, NOTE: The target string should be made big enough to hold the final string., , strcmp( ) → This is a function which compares two strings to find out whether they are same or different., The two strings are compared character by character until there is a mismatch or end of one of the strings is, reached, whichever occurs first. If the two strings are identical, strcmp( ) returns a value zero. If they’re not, it, returns the numeric difference between the ASCII values of the first non-matching pairs of characters. Here is a, program which puts strcmp( ) in action., #include<string.h>, void main( ), {, char str1[20], str2[20];, printf ( "Enter the first string:\t") ;, gets(str1);, printf ( "Enter the second string:\t") ;, gets(str2);, if(strcmp (str1,str2)==0), printf ( "\n\n Strings are equal") ;, else, printf ( "\n\n Strings are unequal") ;, getch();, }, And here is the output..., Enter the first string: HELLO
Page 15 :
15, Enter the first string: Hello, Strings are unequal, #include<string.h>, void main( ), {, char str1[20], str2[20];, printf ( "Enter the first string:\t") ;, gets(str1);, printf ( "Enter the second string:\t") ;, gets(str2);, if(strcmpi (str1,str2)==0), printf ( "\n\n Strings are equal") ;, else, printf ( "\n\n Strings are unequal") ;, getch();, }, And here is the output..., Enter the first string: HELLO, Enter the first string: Hello, Strings are equal, , #include<string.h>, void main( ), {, char string1[ ] = "Jerry" ;, char string2[ ] = "Ferry" ;, int i, j, k ;, i = strcmp ( string1, "Jerry" ) ;, j = strcmp ( string1, string2 ) ;, k = strcmp ( string1, "Jerry boy" ) ;, printf ( "\n%d\t %d\t %d", i, j, k ) ;, }, And here is the output..., 0, , 4, , -32, , In the first call to strcmp( ), the two strings are identical—“Jerry” and “Jerry”—and the value returned by strcmp(, ) is zero. In the second call, the first character of “Jerry” doesn't match with the first character of “Ferry” and the, result is 4, which is the numeric difference between ASCII value of ‘J’ and ASCII value of ‘F’. In the third call, to strcmp( ) “Jerry” doesn’t match with “Jerry boy”, because the null character at the end of “Jerry” doesn’t, match the blank in “Jerry boy”. The value returned is -32, which is the value of null character minus the ASCII, value of space, i.e., ‘\0’ minus ‘ ’, which is equal to -32., NOTE: The exact value of mismatch will rarely concern us. All we usually want to know is whether or not the first, string is alphabetically before the second string. If it is, a negative value is returned; if it isn’t, a positive value is, returned. Any non-zero value means there is a mismatch.
Page 16 :
16, Refer to class notes for more programs…, *****************************************************************************, , Why we need Structures? Quite often we deal with entities that are collection of dissimilar data, types. For example, suppose we want to store data about a book. We might want to store its name (a string), its, price (a float) and number of pages in it (an int). If data about say 3 such books are to be stored, then we can, follow two approaches:, a) Construct individual arrays, one for storing names, another for storing prices and still another for storing, number of pages., b) Use a structure variable., Let us begin with a program that uses arrays., , void main( ), {, char name[3] ;, float price[3] ;, int pages[3], i ;, printf ( "\nEnter names, prices and no. of pages of 3 books\n" ) ;, for ( i = 0 ; i <= 2 ; i++ ), scanf ( "%c %f %d", &name[i], &price[i], &pages[i] );, printf ( "\nAnd this is what you entered\n" ) ;, for ( i = 0 ; i <= 2 ; i++ ), printf ( "%c %f %d\n", name[i], price[i], pages[i] );, }, The program becomes more difficult to handle as the number of items relating to the book go on, increasing. For example, we would be required to use a number of arrays, if we also decide to store name of the, publisher, date of purchase of book, etc. To solve this problem, C provides a special data type—the structure., , Structures: A structure contains a number of data types grouped together. These data types may or may not, be of the same type. Hence, structure may be recognized as a collection of dissimilar data types. The following, example illustrates the use of this data type., , void main( ), {, struct book, {, char name ;, float price ;, int pages ;, };, struct book b1, b2, b3 ;, printf ( "\nEnter names, prices & no. of pages of 3 books\n" ) ;, scanf ( "%c %f %d", &b1.name, &b1.price, &b1.pages ) ;, scanf ( "%c %f %d", &b2.name, &b2.price, &b2.pages ) ;
Page 17 :
17, scanf ( "%c %f %d", &b3.name, &b3.price, &b3.pages ) ;, printf ( "\nAnd this is what you entered" ) ;, printf ( "\n%c %f %d", b1.name, b1.price, b1.pages ) ;, printf ( "\n%c %f %d", b2.name, b2.price, b2.pages ) ;, printf ( "\n%c %f %d", b3.name, b3.price, b3.pages ) ;, }, This program demonstrates two fundamental aspects of structures:, • Declaration of a structure, • Accessing of structure elements, , Declaring a Structure: In our example program, the following statement declares the structure type:, struct book, {, char name ;, float price ;, int pages ;, };, This statement defines a new data type called struct book. Each variable of this data type will consist of a, character variable called name, a float variable called price and an integer variable called pages. The general, form of a structure declaration statement is given below:, struct <structure name>, {, structure element 1 ;, structure element 2 ;, structure element 3 ;, ......, ......, };, Once the new structure data type has been defined one or more variables can be declared to be of that, type. For example the variables b1, b2, b3 can be declared to be of the type struct book, as,, struct book b1, b2, b3 ;, This statement sets aside space in memory. It makes available space to hold all the elements in the structure—in, this case, 7 bytes—one for name, four for price and two for pages. These bytes are always in adjacent memory, locations., Like primary variables and arrays, structure variables can also be initialized where they are declared. The, format used is quite similar to that used to initiate arrays., struct book, {, char name[10] ;, float price ;, int pages ;, };, struct book b1 = { "Basic", 130.00, 550 } ;, struct book b2 = { "Physics", 150.80, 800 } ;
Page 18 :
18, Note the following points while declaring a structure type:, •, •, , The closing brace in the structure type declaration must be followed by a semicolon., It is important to understand that a structure type declaration does not tell the compiler to reserve any space in, memory. All a structure declaration does is, it defines the ‘form’ of the structure., , Accessing Structure Elements: After declaration of the structure type and the structure variables, now let, us see how it can be accessed?, Structures use dot (.) operator for accessing its elements. So to refer to pages of the structure defined in our, sample program we have to use,, b1.pages, Similarly, to refer to price we would use,, b1.price, NOTE: Before the dot (.) there must always be a structure variable and after the dot there must always be, a structure element., , Array of Structures: In our sample program, to store data of 100 books we would be required to use 100, different structure variables from b1 to b100, which is definitely not very convenient. A better approach would, be to use an array of structures. Following program shows how to use an array of structures:, /* Usage of an array of structures */, void main( ), {, struct book, {, char name ;, float price ;, int pages ;, };, struct book b[100] ;, int i ;, for ( i = 0 ; i <= 99 ; i++ ), {, printf ( "\nEnter name, price and pages " ) ;, scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ;, }, for ( i = 0 ; i <= 99 ; i++ ), printf ( "\n%c %f %d", b[i].name, b[i].price, b[i].pages ) ;, }, , Union: A union is a data type similar to structure but the difference lies in their storage allocation schemes., In structure, each member has its separate memory locations whereas union shares common memory space., Hence, in structure, the number of locations allocated would be equal to the number of members in the, structure.
Page 19 :
19, Size of structure variable is equal to the addition of its all the members size, In the case of union, only one location which is large enough to collect the largest data type member in, the union gets allocated (but only one member can remain in memory at a given time)., Size of union variable is equal to its largest member’s size, E.g. If we are storing following three types of data i.e. one integer, one float & one character, in a structure &, union then they will require memory spaces respectively as:, Size of structure variable = size of (int + float + char) = 2 bytes + 4 bytes + 1 byte = 7 bytes, Size of union variable = size of largest data type i.e. float = 4 bytes, , Enumerated data types: An enumeration is a set of named integer constants that specify all the, legal values a variable of that type may have. Enumerations, , Refer to class notes for more illustrations…, *****************************************************************************, , Standard C Preprocessors: The C preprocessor is a program that processes the source, program before passing it to the compiler. It is like a language defined within a language. The preprocessor, directly substitutes the value or expression in source program resulting in fast execution., , Source Program, , C Preprocessor, , Compiler, , Object code, , The preprocessor offers several features called preprocessor directives. Each of these preprocessor, directives begin with a # symbol. The directives can be placed anywhere in a program but are most often placed, at the beginning of a program, before the first function definition. We would learn the following preprocessor, directives here:, ➢ Macro expansion, ➢ File inclusion, ➢ Conditional Compilation, ➢ Miscellaneous directives, Let us understand these features of preprocessor one by one., , ➢ Macro Expansion: Macro expansion is a preprocessor statement, which is used to make the programs, more readable & fast executing. Each preprocessor begins with #define statement and not terminated by, semicolon., Have a look at the following program:, #define UPPER 25, void main( ), {, int i ;, for ( i = 1 ; i <= UPPER ; i++ ), printf ( "\n%d", i ) ;, }, In this program instead of writing 25 in the for loop we are writing it in the form of UPPER, which has already, been defined before main( ) through the statement,
Page 20 :
20, #define UPPER 25, This statement is called ‘macro definition’. During preprocessing, the preprocessor replaces every occurrence of, UPPER in the program with 25. Here is another example of macro definition., #define PI 3.1415, void main( ), {, float r = 6.25 ;, float area ;, area = PI * r * r ;, printf ( "\nArea of circle = %f", area ) ;, }, UPPER and PI in the above programs are often called ‘macro templates’, whereas, 25 and 3.1415 are called, their corresponding ‘macro expansions’., When we compile the program, before the source code passes to the compiler it is examined by the C, preprocessor for any macro definitions. When it sees the #define directive, it goes through the entire program in, search of the macro templates; wherever it finds one, it replaces the macro template with the appropriate macro, expansion. Only after this procedure completed, the program is handed over to the compiler., In C programming it is mandatory to use capital letters for macro template. This makes it easy for, programmers to pick out all the macro templates when reading through the program., Note that a macro template and its macro expansion are separated by blanks. A space between # and define, is optional. Remember that a macro definition is never to be terminated by a semicolon., A #define directive is many a times used to define operators as shown below:, #define AND &&, #define OR ||, , Refer to class notes for more illustrations…, *****************************************************************************