Chethan Raj C Assistant Professor Dept. of CSE
|
|
- Bryce Page
- 5 years ago
- Views:
Transcription
1 Chethan Raj C Assistant Professor Dept. of CSE Module 01: Contents 1. Data Structures. 2. Classifications (Primitive & Non Primitive). 3. Data structure Operations. 4. Review of Arrays. 5. Structures. 6. Self-Referential Structures. 7. Unions. 8. Pointers. 9. Dynamic Memory Allocation Functions. 10. Representation of Linear Arrays in Memory. 11. Dynamically allocated arrays. 12. Array Operations. 13. Traversing, inserting, deleting, searching, and sorting. 14. Multidimensional Arrays. 15. Polynomials and Sparse Matrices. 16. Strings: Basic Terminology & Storing. 17. Operations and Pattern Matching algorithms. 18. Programming Examples. Chethan Raj C, Assistant Professor, Dept. of CSE Page 1
2 Data and Information: Data are plain facts. Data is the raw material that can be processed by any computing machine. Data can be represented in the form of: Numbers and words which can be stored in computer's language. When the data are processed, organized, structured or presented in a given context to make them useful, they are called Information. Information is data that has been processed in such a way as to be meaningful to the person who receives it. It is anything that is communicated. Data themselves are fairly useless, but when these data are interpreted and processed to determine its true meaning, they becomes useful and can be named as information. Information is data that has been converted into a more useful or intelligible form. For example, marks obtained by students and their roll numbers form data, the report card/sheet is the information. Other forms of information are pay-slips, schedules, reports, worksheet, bar charts, invoices and account returns etc. It may be noted that information may further be processed and/or manipulated to form knowledge. Introduction: In the modern world, Data and its information is an essential part, and various implementations are being made to store in different ways. Data is just a collection of facts and figures, or data are values or set of values that are in a particular format. A data item refers to a single set of values. Data items are then further categorized into subitems which are the group of items which are not being called a plain elementary form of items. Consider an example where the name of the student may be divided into three sub-items namely: first name, middle name and last name, but the ID that is assigned to a student would normally be considered as a single item. Definition: The Data structure is defined as a specific way to store, organize, manipulate and process the data in a computer's memory with allowed operations, so that these data can be used efficiently later. Data may be arranged in many different ways such as the logical or mathematical model for a particular organization of data is termed as a data structure. Data structure also maintains the logical relationship existing between individual data elements. Set of a well-defined algorithm and data structure makes a computer program efficient. Data structures are considered as the main building blocks of a computer program hence selection of data structure is important. Selection of Data structure must possesses 2 steps, 1. The data structure must be powerful enough to handle the different relationship existing between the data. 2. The structure of data to be simple, so that user can efficiently process data when required. The variety of a specific data model depends on the two factors - Firstly, it must be loaded enough in structure to reflect the actual relationships of the data with the real world object. Secondly, the formation should be simple enough so that anyone can efficiently process the data each time it is necessary. Chethan Raj C, Assistant Professor, Dept. of CSE Page 2
3 Refer Class notes for attributes of Data. Specification of data structure: 1. Organization of data 2. Accessing methods 3. Degree of associativity 4. Processing alternatives for information Classifications (Primitive & Non Primitive) A program can be made using the different data structure to produce the same output. But the efficiency of the program will depend on the choice of the best data structure to create that particular program. Fig: Classification of Data Types Primitive data structure: (Basic/fundamental/primary) The primitive data structures are known as basic data structures and are directly operated upon by the machine instructions. Normally, primitive data structures have different representation on different computers. The data structure that are atomic (indivisible) are called primitive. Primitive data types are predefined types of data, and they directly contain values which are supported by the programming language. Example of primitive data structure: byte short int long char boolean float(real) double Pointer. Integer : The integers are signed or unsigned whole numbers with the specified range such as 5, 39, -1917, 0 etc. They have no fractional parts. Integers can be positive or negative but whether or not they can have negative values, it depends upon the integer types. Float : Float refers floating point or real number. It can hold a real number or a number having a fractional part like or etc. The decimal point signals that it is a floating point number, not an integer. The number 15 is an integer but 15.0 is a floating point number. Chethan Raj C, Assistant Professor, Dept. of CSE Page 3
4 Character : It can store any member of the basic character set. If a character from this set is stored in a character variable, its value is equivalent to the integer code of that character basically known as ASCII code. It can hold one letter/symbol like a, B, d etc. Characters can also be of different types. Non-Primitive data structure: The non-primitive data structures are developed from the primitive data structure that are used to store group of values. The Data structures that are not atomic are called non-primitive or composite. The nonprimitive data structure is responsible for organizing the group of homogeneous and heterogeneous data elements and relationship between each data item. Non-primitive data types are not defined by the programming language, but are instead created by the programmer. They are sometimes called "reference variables," or "object references," since they reference a memory location, which stores the data Example of Non-primitive data structure : Arrays Structure Union linked list Stacks Queue Tress & Graphs Non-Primitive data structures can further be classified into two categories: 1. Linear Data Structures 2. Non-Linear Data Structures Linear Data Structures In a Linear Data Structure, the elements of data structure are stored in a linear or sequential order. Examples: Arrays, Linked Lists, Stacks, Queues Non-Linear Data Structures If the elements of a Data Structure are not stored in a sequential order, then it is a Non-Linear Data Structure. Examples: Trees, Graphs Data structure Operations. Some specific operations applied to data available in the data structures. The different data structure operations are listed below: 1. Traversing 2. Searching 3. Insertion 4. Deletion 5. Sorting 6. Merging Insertion: Insertion means addition of a new data element in a data structure. When an element of the same type is added to an existing data structure, the operation is called as Insertion operation. The element can be added anywhere in the data structure. When the element is added in the end it is called as special type addition, Appending. In case of adding an element to the data structure may results Overflow. If the size of the data structure is fixed and it is full, then if user tries the insertion operation on the data structure it is said to be overflow of data structure or the data structure is full. Chethan Raj C, Assistant Professor, Dept. of CSE Page 4
5 Suppose user has an array of size 20 used to store marks obtained by the students in Computer Science subject. If users have already added 15 students marks according to an ascending order, then user can add another student marks at appropriate place, by shifting the already stored element accordingly. Then it is called Insertion operation. Deletion: Deletion means removal of a data element from a data structure if it is found. When an element is removed from the data structure, the operation is called as Deletion operation. User can delete an element from data structure from any position. In case of deleting an element from the data structure results Underflow. If no elements are stored in the data structure, then if user tries deletion operation on the data structure it is said to be underflow of data structure or data structure is empty. Suppose user has an array of size 20 used to store marks obtained by the students in Computer Science subject. If user have already added 15 student s marks according to an ascending order, then user can delete one student s marks from any place, by shifting the already stored elements accordingly. Then it is called Deletion operation. Searching: Searching involves searching for the specified data element in a data structure. When an element is checked for its presence in a data structure, that operation is called as searching operation. The element that is to be searched is called as key element. The searching can be done using either linear search or binary search. Suppose user has an array of size 10 and assume elements stored are 1,2,3,23,34,54,56,21,32,33 and assume user want to search the number 23. So here the number 23 is key element. The key is searched through the array starting from the first element till end. When it is compared with the fourth element in it is present in the list (array) of numbers. So search is successful. This type of searching is called as Linear Search. In order to apply linear search, the list may not be in any particular order but when binary search is applied the list must be an ordered one (Ascending order). Traversal: Traversal of a data structure means processing all the data elements present in it i.e process every element of data structure is visited once and only once, such type of operation is called as traversing. For example to display all the elements of an array, every element is visited only once, so it is called as traversing operation. Suppose user has an array of 20 students average makes, and if user need to calculate the average of group, user visit (read) each individual average and accumulate (sum) them. Then user will find the array is visited once and only once. Then it is traversing of an array. Sorting: Arranging data elements of a data structure in a specified order is called sorting. When all the elements of array are arranged in either ascending or descending order, the operation is called as Sorting. The Sorting can be done using Insertion, Selection or Bubble sort techniques. Suppose user has an array of size 10 and assume elements stored are 1,2,3,23,34,54,56,21,32,33. The elements of the array are not in proper order. If they are arranged in ascending order the list (array) becomes 1,2,3,21,23,32,34,54,56. Merging: Combining elements of two similar data structures to form a new data structure of the same type, is called merging. When two lists List A and List B of size M and N respectively, of same type of Chethan Raj C, Assistant Professor, Dept. of CSE Page 5
6 elements, clubbed or joined to produce the third list, List C of size (M+N), and the operation done during the process is called as Merging. Suppose user have a list of size 6, containing the elements 1,2,3,4,71,87 and user have another list of size 5, containing the elements 9,13,21,65,67. Here both the lists are in ascending order. User can produce the third list of size 11 that will also be in ascending order, containing the element 1,2,3,4,9,13,21,65,67,71,87. The third list is called the merged list of first and second lists. In order to merge two lists into single list one needs to compare each element from both the lists and one of them will go the merged list. Review of Arrays Array is a data structure that can store a fixed-size sequential set of elements of the same type. An array is defined as collection/set of variables of the same type under single variable name, & array is linear data structure that can store fixed number of values. Arrays index are always start from 0 and arrays are always stored in Continuous Memory Locations. The number of elements and types of array are identified by subscript of array Elements. Address of first element is random (depends on computer), address of next subsequent elements depend upon the type of array. Here, the type is integer and integer takes two bytes in memory, therefore every next address will increment by two. Types/Classification of an array 1. One dimensional array(1d) 2. Multi dimensional array (2D, 3D,...) One dimensional array (1D) One dimensional array is defined as type of array which stores the set of elements of similar data type in linear form. Array having only one subscript is called One-Dimensional array. It is also called as Single Dimensional Array or Linear Array. As name suggest that 1D array consists of single subscript[] operator to store the values. Syntax : Declaration of array means creating sequential blocks of memory to hold fixed number of values : <data-type> <array_name> [size]; Example of Single Dimensional Array : int iarr[3] = 2, 3, 4; char carr[20] = "CRC-DSA" ; float farr[3] = 12.5,13.5,14.5 ; Example of array declaration : Ex: int Array [5]; //Statement 1 float Array [10]; //Statement 2 In the example, statement 1 will allocate memory for an integer array which will hold five values. Each element in an array is accessed using same name with different index (position) value. The statement 2 will allocate memory for float point array which will hold ten values. Chethan Raj C, Assistant Professor, Dept. of CSE Page 6
7 Initialization of Array Initialization means assigning value to declared Array. Ex: int Array [ ] = 78, 45, 12, 89, 56 ; In the above example user declared and initializing an array at same time. When user declares and initialize an array at same time then giving the size of an array is optional. Array of an element of an array say Array[ I ] is calculated using the following formula: Address of A [ I ] = B + W * ( I LB ) Where, B = Base address W = Storage Size of one element stored in the array (in byte) I = Subscript of element whose address is to be found LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero). Address of A [ I ] = B + W * ( I LB ) Where, B = Base address W = Storage Size of one element stored in the array (in byte) I = Subscript of element whose address is to be found LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero). Access of Element= Base Address+Index*Sizeof Example: Given the base address of an array B[ ] as 1020 and size of each element is 2 bytes in the memory. Find the address of B[1700]. Solution: The given values are: B = 1020, LB = 1300, W = 2, I = 1700 Address of A [ I ] = B + W * ( I LB ) = * ( ) = * 400 = = 1820 Ex: Display the address of array #include <stdio.h> int i; int AR[5] = 12,20,8,16, 40; printf("the address of the array is: %p\n", AR); printf("the addresses of the four elements are as below.\n"); for (i =0; i<5; i++) printf("address of AR [%d] = %p\n",i, AR+i); Chethan Raj C, Assistant Professor, Dept. of CSE Page 7
8 Output: Ex: Read and Display the array element #include<stdio.h> int array [5]; int i; for(i=0;i<5;i++) //Input arrray from user. printf("\nenter any number : "); scanf("%d",&array [i]); for(i=0;i<5;i++) //Output arrray to console. printf("%d, ",array [i]); Output : Enter any number : 78 Enter any number : 45 Enter any number : 12 Enter any number : 89 Enter any number : 56 78, 45, 12, 89, 56 Ex: Duplicate element in an array #include <stdio.h> int main() int array1 [10], i, number, j, flag=0; printf("\n Enter the size of the array:"); scanf ("%d", &number); for(i=0;i<number;i++) scanf("%d", &array1[i]); for(i=0;i<number;i++) for(j= i+1;j<number;j++) if(array1[i] == array1[j] && i!=j) flag=1; printf("\n Duplicate number %d found at location %d and %d", array1 [i],i, j); if (flag==60) printf ("\n No Duplicate"); Chethan Raj C, Assistant Professor, Dept. of CSE Page 8
9 Output: Enter the size of an array: Duplicate number 3 found at location 1 and 3 Multi-Dimensional Array (Array of Array) Array having more than one subscript is called Multi-Dimensional array. Multi Dimensional Array is also called as Matrix. Ex: Two dimensional array, Three dimensional array, four dimensional array etc. Multidimensional Array User can create an array of arrays known as multidimensional array(2d, 3d...) For example, float x[3][4]; Here, x is a two-dimensional (2d) array. The array can hold 12 elements. User can think the array as table with 3 row and each row has 4 column. 2D array The Two Dimensional array is used for representing the elements of the array in the form of the rows and columns and these are used for representing the matrix. Two Dimensional Array uses the two subscripts for declaring the elements of the Array syntax : data_type array_name[num_of_rows][num_of_column]; Array declaration syntax: data_type arr_name [num_of_rows][num_of_column]; Array initialization syntax: Different ways to initialize two dimensional array int arr_name[2][2] = 0,0,0,1,1,0,1,1; int c[2][3] = 1, 3, 0, -1, 5, 9; int c[][3] = 1, 3, 0, -1, 5, 9; int c[2][3] = 1, 3, 0, -1, 5, 9; Array accessing syntax: arr_name[index][index]; Ex: int arr[2][2]; int arr[2][2] = 1,2, 3, 4; arr [0] [0] = 1; arr [0] ]1] = 2; arr [1][0] = 3; arr [1] [1] = 4; Three-dimensional (3d) array An array consists of 3 subscripts is called 3d array. User can declare a three-dimensional (3d) array. Chethan Raj C, Assistant Professor, Dept. of CSE Page 9
10 For example: float y[2][4][3]; Here,The array y can hold 24 elements. Each 2 elements have 4 elements, which makes 8 elements and each 8 elements can have 3 elements. Hence, the total number of elements is 24. Initialization of a three dimensional array. User can initialize a three dimensional array in a similar way like a two dimensional array. Ex: int test[2][3][4] = 3, 4, 2, 3, 0, -3, 9, 11, 23, 12, 23, 2, 13, 4, 56, 3, 5, 9, 3, 5, 3, 1, 4, 9 ; Array Advantage/ Benefits: 1. Code Optimization: Less code to the access the data. 2. Easy to traverse data: By using the for loop, user can retrieve the elements of an array easily. 3. Easy to sort data: To sort the elements of array, user need a few lines of code only. 4. Random Access: User can access any element randomly using the array. 5. Arrays are used to implement other data structures like linked lists, stacks, queues, trees, graphs etc. 6. Arrays are used to represent matrices. 7. It is used to represent multiple data items of same type by using only single name. 8. It is better and convenient way of storing the data of same data-type with same size. 9. It allocates memory in contiguous memory locations for its elements. It does not allocate any extra space/ memory for its elements. Hence there is no memory overflow or shortage of memory in arrays. 10. Iterating the array using their index is faster compared to any other methods like linked list etc. 11. It allows storing the elements in any dimensional array - supports multidimensional array. Array Disadvantages: 1. User must know in advance that how many elements are to be stored in array. 2. Array is static structure. It means that array is of fixed size. The memory which is allocated to array cannot be increased or reduced. 3. Since array is of fixed size, if user allocate more memory than requirement then the memory space will be wasted. And if user allocates less memory than requirement, then it will create problem. 4. The elements of array are stored in consecutive memory locations. So insertions and deletions are very difficult and time consuming. 5. Array can store a single type of primitives only. Refer Class notes for 2D array and Programming Examples. Functions: Function is a logically grouped set of statements that perform a specific task. For example, a function sort() may sort a group of data. Every C program has a function named main() where the execution of the program starts. It is a mandatory function in C. Advantages of Function Creating functions in a program is beneficial. They 1 Avoid repetition of codes. 2 Increase program readability. 3 Divide a complex problem into many simpler problems. 4 Reduce chances of error. 5 Makes modifying a program becomes easier. 6 Makes unit testing possible. Chethan Raj C, Assistant Professor, Dept. of CSE Page 10
11 Components of Function A function usually has three components. They are: 1. Function prototype/declaration 2. Function definition 3. Function call 1. Function prototype/declaration Function declaration informs the compiler about the function's name, type and number of argument it receives and type of value it returns. Syntax for function declaration: returntype function_name ([arguments type]); Ex: void display(char);//function name = display, receives a character as argument and returns nothing int sum(int,int);//function name = sum, receives two integers as argument and returns an integer 2. Function definition: It is the most important part of function which that consists of body of function. It consists of block of statements that specifies what task is to be performed. When a function is called, the control is transferred to the function definition. Syntax for function definition: returntype function_name ([arguments]) statement(s); Return Statement Function can return values. A return statement is used to return values to the invoking function. The type of value a function can return is specified in the function prototype. A function which has void as return type don't return any value. Beside basic data type, it can return object and pointers too. A return statement is usually place at the end of function definition or inside a branching statement. Ex: int sum (int x, int y) int s = x+y; return s; In this function, the return type of sum() is int. So it returns an integer value s to the invoking function. 3. Function call Function call statement calls the function by matching its name and arguments. A function call can be made by using function name and providing the required parameters. Syntax for function call: function_name ([actual arguments]); Ex: display(a); s = sum(x,y); Passing Argument to Function : Two Ways of Passing Argument to Function in C Language : 1. Call by Value 2. Call by Reference Call by Value In call by value method a copy of actual parameters is passed which is stored in formal parameters. Actual Parameters: The parameters that are passed while calling the function are called actual parameters. Chethan Raj C, Assistant Professor, Dept. of CSE Page 11
12 Formal Parameters: The parameters that hold the values of actual parameters are called formal parameters. In call by value method, if any changes are done in formal parameters then actual parameters are not changed. Ex: #include<stdio.h> void fun(int x) x=x+5; int a=10; printf("before calling\na=%d",a); fun(a); printf("\n\nafter calling\na=%d",a); Output: Before calling A=10 After calling A=10 As shown in above output that after calling the function and doing changes in formal parameter x, the actual parameter a is not changed. Ex: #include<stdio.h> void interchange(int number1,int number2) int temp; temp = number1; number1 = number2; number2 = temp; int main() int num1=50,num2=70; interchange(num1,num2); printf("\nnumber 1 : %d",num1); printf("\nnumber 2 : %d",num2); return(0); Output : Number 1 : 50 Number 2 : 70 While Passing Parameters using call by value, xerox copy of original parameter is created and passed to the called function. Any update made inside method will not affect the original value of variable in calling function. In the above example num1 and num2 are the original values and xerox copy of these values is passed to the function and these values are copied into number1,number2 variable of sum function respectively. As their scope is limited to only function so they cannot alter the values inside main function. Call by Reference/Pointer/Address : In call by reference method, reference or address of actual parameters is passed which is stored in formal parameters. If any changes are done in formal parameters then actual parameters are also changed. Chethan Raj C, Assistant Professor, Dept. of CSE Page 12
13 Example of call by reference: #include<stdio.h> void fun(int *x) *x=(*x)+5; int a=10; printf("before calling\na=%d",a); fun(&a); printf("\n\nafter calling\na=%d",a); Output: Before calling A=10 After calling A=15 As shown in above output that after calling the function and doing changes in formal parameter x, the actual parameter a is also changed. Ex: #include<stdio.h> void interchange(int *num1,int *num2) int temp; temp = *num1; *num1 = *num2; *num2 = temp; int main() int num1=50,num2=70; interchange(&num1,&num2); printf("\nnumber 1 : %d",num1); printf("\nnumber 2 : %d",num2); return(0); Output : Number 1 : 70 Number 2 : 50 While passing parameter using call by address scheme, we are passing the actual address of the variable to the called function. Any updates made inside the called function will modify the original copy since we are directly modifying the content of the exact memory location. S. No. Call by Value Call by Reference A copy of actual parameters is passed into formal parameters. Changes in formal parameters will not result in changes in actual parameters. Separate memory location is allocated for actual and formal parameters. Reference of actual parameters is passed into formal parameters. Changes in formal parameters will result in changes in actual parameters. Same memory location is allocated for actual and formal parameters. Chethan Raj C, Assistant Professor, Dept. of CSE Page 13
14 Types of function There are two kinds of function. They are: 1. Library functions 2. User-defined functions 1. Library functions Library functions are built in function that are defined in the C++ library. Function prototype is present in header files so we need to include specific header files to use library functions. These functions can be used by simply calling the function. Some library functions are pow(), sqrt(), strcpy(), toupper(), isdigit(), etc. 2. User-defined functions These functions are defined by user as per the requirement, hence called user-defined functions. Function definition is written by user and is present in the program. main() is an example of userdefined function. Array and functions: User can pass an array (one-, two- or multidimensional) as an argument/parameter to a function. These parameters can be of different types and sizes. A function can use one-dimensional array as a parameter as shown below. Syntax: ret_type func_name ( arr_type arr_name [ ]) where parameter arr_name is a one-dimensional array of type arr_type. Note that the array size is not required in the above definition and is usually ignored. A call to this function takes the following form: func_name ( arr ) The call by value is the default mechanism for passing parameters i.e When a function is called, the argument specified in the function call is copied to the corresponding function parameter specified in the function definition Passing of an array to a function #include<stdio.h> double Average(int Array[10]); //function prototype int Dal[]= 1,2,3,4,5,6,7,8,9,10; //array clrscr(); printf("average of Array Element is : %5.3f\n",Average (Dal)); double Average (int AR [10]) // definition of function int i; double Sum =0; for( i =0; i<10; i++) Sum +=AR[i]; return Sum/10; Output: Average of Array Element is Chethan Raj C, Assistant Professor, Dept. of CSE Page 14
15 Structures. A normal variable can hold only one data type at a time. An array can hold group/set of data of same /homogenous data type. A structure is an user defined data type that can hold group of data of different data types and Data types can be int, char, float, double and long double etc. Each element of a structure is called a member. It is widely used to store student information, employee information, product information, book information etc i.e heterogeneous data. Definition of structure The struct is a keyword is used to define structure. The syntax to define structure in c. struct structure_name data_type member1;... data_type memebern; ; Example to define structure for employee in c. struct employee int id; char name[50]; float salary; ; Here, struct is the keyword, employee is the tag name of structure; id, name and salary are the members or fields of the structure. Declaring structure variable User can declare variable for the structure, so that member of structure can be access easily. There are two ways to declare structure variable: By struct keyword within main() function. By declaring variable at the time of defining structure. 1st Method: The example to declare structure variable by struct keyword. It should be declared within the main function. struct employee int id; char name[50]; float salary; ; struct employee e1, e2; 2nd Method: Another way to declare variable at the time of defining structure. struct employee int id; Chethan Raj C, Assistant Professor, Dept. of CSE Page 15
16 char name[50]; float salary; e1,e2; DATA STRUCTURES AND APPLICATIONS, III Sem CSE Dept. (17CS33) Accessing members of structure There are two ways to access structure members: By. (member or dot operator) By -> (structure pointer operator) The code to access the id member of p1 variable by. (member) operator. p1.id Ex: #include<stdio.h> struct employee int id; char name[50]; e1; //declaring e1 variable for structure void main( ) e1.id=101; //store first employee information strcpy(e1.name, "Spandana");//copying string into char array printf( "employee 1 id : %d\n", e1.id); //printing first employee information printf( "employee 1 name : %s\n", e1.name); Output: employee 1 id : 101 employee 1 name : Spandana. Example: #include<stdio.h> struct employee int id; char name[50]; float salary; e1,e2; //declaring e1 and e2 variables for structure void main( ) e1.id=101; //store first employee information strcpy(e1.name, "Spandana");//copying string into char array e1.salary=56000; e2.id=102; //store second employee information strcpy(e2.name, "Shreyas"); e2.salary=126000; printf( "employee 1 id : %d\n", e1.id); //printing first employee information printf( "employee 1 name : %s\n", e1.name); printf( "employee 1 salary : %f\n", e1.salary); printf( "employee 2 id : %d\n", e2.id); //printing second employee information printf( "employee 2 name : %s\n", e2.name); printf( "employee 2 salary : %f\n", e2.salary); return 0; Output: employee 1 id : 101 employee 1 name : Spandana employee 1 salary : Chethan Raj C, Assistant Professor, Dept. of CSE Page 16
17 employee 2 id : 102 employee 2 name : Shreyas employee 2 salary : Using normal variable Syntax: struct tag_name data type var_name1; data type var_name2; data type var_name3; ; Example: struct student int mark; char name[10]; float average; ; Declaring structure using normal variable: struct student report; Initializing structure using normal variable: struct student report = 100, Mani, 99.5; Accessing structure members using normal variable: report.mark; report.name; report.average; Using pointer variable Syntax: struct tag_name data type var_name1; data type var_name2; data type var_name3; ; Example: struct student int mark; char name[10]; float average; ; Declaring structure using pointer variable: struct student *report, rep; Initializing structure using pointer variable: struct student rep = 100, Mani, 99.5; report = &rep; Accessing structure members using pointer variable: report -> mark; report -> name; report -> average; Initialization of structure Like normal variable, structure variables can be initialized at the time of declaration. Initialization of structure is similar to initializing array/variable. The structure object/variable is followed by equal sign and the list/set of values enclosed in braces and each value is separated with comma. Example for declaring & initializing structure at same time, #include<stdio.h> struct Employee int Id; char Name[25]; int Age; long Salary; struct Employee E = 2,"Suresh",35,35000;//Structure Variable Declaration and initialization printf("\n\nemployee Id : %d",e.id); printf("\nemployee Name : %s",e.name); printf("\nemployee Age : %d",e.age); printf("\nemployee Salary : %ld",e.salary); Output : Employee Id : 1 Chethan Raj C, Assistant Professor, Dept. of CSE Page 17
18 Employee Name : Kumar Employee Age : 29 Employee Salary : Ex: #include <stdio.h> struct student int id; char name[20]; float percentage; record; record.id=1; strcpy(record.name, "Raj"); record.percentage = 86.5; printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); Output: Id is: 1 Name is: Raj Percentage is: Array of Structures in C There can be array of structures in C programming to store many information of different data types. The array of structures is also known as collection of structures. Structure is collection of different data type. An object of structure represents a single record in memory, if users want more than one record of structure type, user has to create an array of structure or object. In general, an array is a collection of similar type, therefore an array can be of structure type. Syntax for declaring structure array struct struct-name datatype var1; datatype varn; ; struct struct-name obj [ size ]; The example of structure with array that stores information of 3 students and displays the result. #include<stdio.h> struct student int rollno; char name[10]; ; int i; struct student st[3]; printf("enter Records of 3 students"); Chethan Raj C, Assistant Professor, Dept. of CSE Page 18
19 for(i=0;i<3;i++) printf("\nenter Rollno:"); scanf("%d",&st[i].rollno); printf("\nenter Name:"); scanf("%s", st[i].name); printf("\nstudent Information List:"); for(i=0;i<3;i++) printf("\nrollno:%d, Name:%s",st[i].rollno,st[i].name); Output: Enter Records of 3 students Enter Rollno:1 Enter Name:S Enter Rollno:2 Enter Name:R Enter Rollno:3 Enter Name:V Student Information List: Rollno:1, Name:S Rollno:2, Name:R Rollno:3, Name:V Ex 2: #include <stdio.h> struct student int id; char name[30]; float percentage; ; int main() int i; struct student record[2]; record[0].id=1; // 1st student's record strcpy(record[0].name, "R"); record[0].percentage = 86.5; record[1].id=2; // 2nd student's record strcpy(record[1].name, "S"); record[1].percentage = 90.5; record[2].id=3; // 3rd student's record strcpy(record[2].name, "T"); record[2].percentage = 81.5; for(i=0; i<3; i++) printf(" Records of STUDENT : %d \n", i+1); printf(" Id is: %d \n", record[i].id); printf(" Name is: %s \n", record[i].name); printf(" Percentage is: %f\n\n",record[i].percentage); Chethan Raj C, Assistant Professor, Dept. of CSE Page 19
20 Ex: #include <stdio.h> struct student int id; char name[30]; float percentage; ; int main() int i; struct student record1 = 1, "R", 90.5; struct student record2 = 2, "M", 93.5; printf("records of STUDENT1: \n"); printf(" Id is: %d \n", record1.id); printf(" Name is: %s \n", record1.name); printf(" Percentage is: %f \n\n", record1.percentage); printf("records of STUDENT2: \n"); printf(" Id is: %d \n", record2.id); printf(" Name is: %s \n", record2.name); printf(" Percentage is: %f \n\n", record2.percentage); Output: Records of STUDENT1: Id is: 1 Name is: R Percentage is: Records of STUDENT2: Id is: 2 Name is: M Percentage is: Array within Structure In a programme the structure is collection of different data type. Like normal data type, it can also store an array as well. Syntax for array within structure struct struct-name datatype var1; // normal variable datatype array [size]; datatype varn; ; struct struct-name obj; // array variable Example for array within structure #include<stdio.h> struct Student int Roll; char Name[25]; int Marks[3]; //Statement 1 : array of marks Chethan Raj C, Assistant Professor, Dept. of CSE Page 20
21 int Total; float Avg; ; int i; struct Student S; printf("\n\nenter Student Roll : "); scanf("%d",&s.roll); printf("\n\nenter Student Name : "); scanf("%s",s.name); S.Total = 0; for(i=0;i<3;i++) printf("\n\nenter Marks %d : ",i+1); scanf("%d",&s.marks[i]); S.Total = S.Total + S.Marks[i]; S.Avg = S.Total / 3; printf("\nroll : %d",s.roll); printf("\nname : %s",s.name); printf("\ntotal : %d",s.total); printf("\naverage : %f",s.avg); Output : Enter Student Roll : 10 Enter Student Name : Kumar Enter Marks 1 : 78 Enter Marks 2 : 89 Enter Marks 3 : 56 Roll : 10 Name : Kumar Total : 223 Average : In the above example, user created an array Marks[ ] inside structure representing 3 marks of a single student. Marks[ ] is now a member of structure student and to access Marks[ ] user used dot operator(.) along with object S. Nested Structure in C Nested structure in C is nothing but structure within structure. One structure can be declared inside other structure i.e user declare structure members inside another structure. The structure variables can be a normal structure variable or a pointer variable to access the data. Structure within structure in C using normal variable Structure within structure in C using pointer variable Structure within structure in c using normal variable: The structure is defined & accessed within another structure using normal variable. i.e student_college_detail structure is declared inside student_detail structure. Both structure variables are normal structure variables. The members of student_college_detail structure are accessed by 2 dot(.) operator and members of student_detail structure are accessed by single dot(.) operator. Chethan Raj C, Assistant Professor, Dept. of CSE Page 21
22 Accessing Nested Structure User can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below: e1.doj.dd e1.doj.mm e1.doj.yyyy When a structure contains another structure, it is called nested structure. For example, consider the two structures named address and employee. To make address nested to employee, user have to define address structure before and outside employee structure and create an object of address structure inside employee structure. Syntax for structure within structure or nested structure struct structure ; struct structure struct structure1 obj; ; Example for structure within structure or nested structure #include<stdio.h> struct Address char HouseNo[25]; char City[25]; char PinCode[25]; ; struct Employee int Id; char Name[25]; float Salary; struct Address Add; ; int i; struct Employee E; printf("\n\tenter Employee Id : "); scanf("%d",&e.id); printf("\n\tenter Employee Name : "); scanf("%s", E.Name); printf("\n\tenter Employee Salary : "); scanf("%f",&e.salary); printf("\n\tenter Employee House No : "); scanf("%s", E.Add.HouseNo); printf("\n\tenter Employee City : "); scanf("%s", E.Add.City); printf("\n\tenter Employee House No : "); scanf("%s", E.Add.PinCode); Chethan Raj C, Assistant Professor, Dept. of CSE Page 22
23 printf("\ndetails of Employees"); printf("\n\temployee Id : %d",e.id); printf("\n\temployee Name : %s",e.name); printf("\n\temployee Salary : %f",e.salary); printf("\n\temployee House No : %s",e.add.houseno); printf("\n\temployee City : %s",e.add.city); printf("\n\temployee House No : %s",e.add.pincode); Output : Enter Employee Id : 101 Enter Employee Name : Suresh Enter Employee Salary : Enter Employee House No : 4598/D Enter Employee City : Delhi Enter Employee Pin Code : Details of Employees Employee Id : 101 Employee Name : Suresh Employee Salary : Employee House No : 4598/D Employee City : Delhi Employee Pin Code : Ex: #include <stdio.h> struct student_college_detail int college_id; char college_name[50]; ; struct student_detail int id; char name[20]; float percentage; struct student_college_detail clg_data; // structure within structure stu_data; struct student_detail stu_data = 1, "R", 90.5, 71145,"ABC";//variable declaration & initilization printf(" Id is: %d \n", stu_data.id); printf(" Name is: %s \n", stu_data.name); printf(" Percentage is: %f \n\n", stu_data.percentage); printf(" College Id is: %d \n", stu_data.clg_data.college_id); printf(" College Name is: %s \n", stu_data.clg_data.college_name); Output: Id is: 1 Name is: R Percentage is: College Id is: College Name is: ABC Structure within structure in c using pointer variable:(typedef) Chethan Raj C, Assistant Professor, Dept. of CSE Page 23
24 The structure is defined & accessed within another structure using pointer variable i.e student_college_detail structure is declared inside student_detail structure of one normal structure variable and one pointer structure variable. The combination of.(dot) and ->(arrow) operators are used to access the structure member which is declared inside the structure. Ex: Consider an example to access structure's member through pointer. #include <stdio.h> typedef struct person int age; float weight; ; struct person *personptr, person1; personptr = &person1; printf("enter integer: "); scanf("%d",&(*personptr).age); printf("enter number: "); scanf("%f",&(*personptr).weight); printf("displaying: "); printf("%d%f",(*personptr).age,(*personptr).weight); // Referencing pointer to memory address of person1 In this example, the pointer variable of type struct person is referenced to the address of person1. Then, the structure member through pointer can be accessed. Structure pointer members is accessed by using -> operator. (*personptr).age is same as personptr->age (*personptr).weight is same as personptr->weight Ex: #include <stdio.h> struct student_ college_detail int college_id; char college_name[50]; ; struct student_detail int id; char name[20]; float percentage; // structure within structure struct student_college_detail clg_data; stu_data, *stu_data_ptr; struct student_detail stu_data = 1, "Raju", 90.5, 71145, "ABC"; stu_data_ptr = &stu_data; printf(" Id is: %d \n", stu_data_ptr->id); printf(" Name is: %s \n", stu_data_ptr->name); printf(" Percentage is: %f \n\n", stu_data_ptr->percentage); printf(" College Id is: %d \n", stu_data_ptr->clg_data.college_id); Chethan Raj C, Assistant Professor, Dept. of CSE Page 24
25 printf(" College Name is: %s \n", stu_data_ptr->clg_data.college_name); OUTPUT: Id is: 1 Name is: Raju Percentage is: College Id is: College Name is: ABC C Nested Structure example #include <stdio.h> struct Employee int id; char name[20]; struct Date int dd; int mm; int yyyy; doj; e1; void main( ) e1.id=101; //storing employee information strcpy(e1.name, "SJ");//copying string into char array e1.doj.dd=10; e1.doj.mm=11; e1.doj.yyyy=2014; printf( "employee id : %d\n", e1.id); //printing first employee information printf( "employee name : %s\n", e1.name); printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy); Output: employee id : 101 employee name : SJ employee date of joining (dd/mm/yyyy) : 10/11/2014 Passing structure to function in c: It can be done in 3 ways. 1. Passing structure to a function by value 2. Passing structure to a function by address(reference) 3. No need to pass a structure Declare structure variable as global Passing structure to function in c by value: It describes the how the whole structure is passed to another function by value i.e the whole structure is passed to another function with all members and their values. Hence this structure can be accessed from called function. This concept is useful while writing big/complex programs in C. #include <stdio.h> struct student int id; char name[20]; Chethan Raj C, Assistant Professor, Dept. of CSE Page 25
26 float percentage; ; void func(struct student record); struct student record; record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; func(record); void func(struct student record) printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); Output: Id is: 1 Name is: Raju Percentage is: Passing structure to function in c by address The whole structure is passed to another function by address i.e only the address of the structure is passed to another function. The whole structure is not passed to another function with all members and their values. So, this structure can be accessed from called function by its address. #include <stdio.h> struct student int id; char name[20]; float percentage; ; void func(struct student *record); struct student record; record->id=1; strcpy(record->name, "Raju"); record->percentage = 86.5; func(&record); void func(struct student *record) printf(" Id is: %d \n", record->id); printf(" Name is: %s \n", record->name); printf(" Percentage is: %f \n", record->percentage); Output: Id is: 1 Name is: Raju Percentage is: Chethan Raj C, Assistant Professor, Dept. of CSE Page 26
27 Program to declare a structure variable as global in c: Structure variables can be declared as global variables as user declare other variables in C i.e, the structure variable is declared as global, then it is visible to all the functions in a program. #include <stdio.h> struct student int id; char name[20]; float percentage; ; struct student record; // Global declaration of structure void structure_demo(); record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; structure_demo(); void structure_demo() printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); Output: Id is: 1 Name is: Raju Percentage is: Union: Union is a user defined data type that is used to hold different data type & it doesn't occupy sum of all the members size like structure, instead it occupies the memory of largest member only. It shares memory of largest member to the members of the structure. The union keyword is used to define union. The syntax to define union: union union_name data_type member1; data_type memebern; ; Example to define union for employee. union employee int id; char name[50]; float salary; ; Chethan Raj C, Assistant Professor, Dept. of CSE Page 27
28 Ex: #include <stdio.h> union employee int id; char name[50]; e1; //declaring e1 variable for union void main( ) e1.id=1; //store first employee information strcpy(e1.name, "S");//copying string into char array printf( "employee 1 id : %d\n", e1.id); //printing first employee information printf( "employee 1 name : %s\n", e1.name); Output: employee 1 id : 1 employee 1 name : S Structure and Union Difference Self-Referential Structures (SRS) Self Referential Structure is the data structure in which the pointer refers (points) to the same type of structure, as their member. (OR) A structure that contains pointers to a structure of its own type is known as self-referential structure. The concept of linked lists, stacks, queues, trees and many others works on the principle of self referential structures. One important is that user cannot reference the typedef that create within the structure itself in programming. Note: 1) Self-referential structure is the one which includes a pointer to an instance of itself. 2) In structures, members can be of any data type. If user includes a member in the structure, which is a pointer to the parent structure type, such a structure is called self-referential structure. struct tag member 1; member 2; struct tag *name; ; The structure of type tag contains a member, name which is a pointer to structure of type tag. Thus tag is a self referential structure. Chethan Raj C, Assistant Professor, Dept. of CSE Page 28
29 Types of Self Referential Structures 1. Self Referential Structure with Single Link 2. Self Referential Structure with Multiple Links Self Referential Structure with Single Link: These structures can have only one self-pointer as their member. The following example will show us how to connect the objects of a self-referential structure with the single link and access the corresponding data members. struct node int data; struct node *next; // self-referential Structure (node) ; In the above declaration next is the pointer to the structure of type node. Here next is the pointer which will contains the address of the structure of the same type (i.e address of next node) and data will contain the actual data. Ex: struct demo int a,b; struct demo *ptr1, *ptr2; As shown in above syntax, ptr1 and ptr2 are structure pointers that are pointing to the structure demo, hence structure demo is a self referential structure. These types of data structures are helpful in implementing data structures like linked lists and trees. It is an error to use a structure variable as a member of its own struct type structure or union type union, respectively. Ex: #include <stdio.h> struct node int data1; char data2; struct node *link; //node is SRS ; struct node ob1; // Node1 ob1.link = NULL; // Intialization ob1.data1 = 10; ob1.data2 = 20; struct node ob2; // Node2 ob2.link = NULL; // Initialization ob2.data1 = 30; // Initialization Chethan Raj C, Assistant Professor, Dept. of CSE Page 29
30 ob2.data2 = 40; // Initialization ob1.link = &ob2; // Linking ob1 and ob2 printf("%d", ob1.link->data1); // Accessing data members of ob2 using ob1 printf("\n%d", ob1.link->data2); Output: Self Referential Structure with Multiple Links: Self referential structures with multiple links can have more than one self-pointers. Many complicated data structures can be easily constructed using these structures. Such structures can easily connect to more than one nodes at a time. The following example shows one such structure with more than one links. Ex: #include <stdio.h> struct node int data; struct node* prev_link; struct node* next_link; ; struct node ob1; // Node1 ob1.prev_link = NULL; // Intialization ob1.next_link = NULL; ob1.data = 10; struct node ob2; // Node2 ob2.prev_link = NULL; // Intialization ob2.next_link = NULL; ob2.data = 20; struct node ob3; // Node3 ob3.prev_link = NULL; // Intialization ob3.next_link = NULL; ob3.data = 30; ob1.next_link = &ob2; // Forward links ob2.next_link = &ob3; // Forward links ob2.prev_link = &ob1; // Backward links ob3.prev_link = &ob2; // Backward links printf("%d\t", ob1.data); // Accessing data of ob1, ob2 and ob3 by ob1 printf("%d\t", ob1.next_link->data); printf("%d\n", ob1.next_link->next_link->data); Chethan Raj C, Assistant Professor, Dept. of CSE Page 30
31 printf("%d\t", ob2.prev_link->data); // Accessing data of ob1, ob2 and ob3 by ob2 printf("%d\t", ob2.data); printf("%d\n", ob2.next_link->data); printf("%d\t", ob3.prev_link->prev_link->data); // Accessing data of ob1, ob2 and ob3 by ob3 printf("%d\t", ob3.prev_link->data); printf("%d", ob3.data); Output: In the above example the ob1, ob2 and ob3 are three objects of the self referential structure node and they are connected using their links in such a way that any of them can easily access each other s data. The connections can be manipulated according to the requirements of the programmer/user. Applications: Self referential structures are very useful in creation of other complex data structures like: Linked Lists Stacks Queues Trees Graphs etc Pointers Pointer is a derived data type and it s a variable that stores the address of another variable. Memory in a computer is made up of bytes (A byte consists of 8 bits) arranged in a sequential manner. Each byte has a number associated with it like index or subscript in an array, which is called the address of the byte. The address of byte starts from 0 to one less than size of memory. For example, consider 64MB of RAM, there are 64 * 2^20 = bytes. Therefore the address of these bytes will start from 0 to int marks; The data type int occupies 4 bytes of data (assuming 32-bit compiler) hence compiler reserves 4consecutive bytes from memory to store an integer value. The address of the first byte of the 4 allocated bytes is known as the address of the variable marks. Consider the address of 4 consecutive bytes are 5004, 5005, 5006and 5007 then the address of the variable marks will be Syntax: Data type *variable name; //pointer variable declaration Ex: int a,*p; p=&a;//p is a pointer variable which holds the address of another variable. EX: #include<stdio.h> Chethan Raj C, Assistant Professor, Dept. of CSE Page 31
32 int a = 3; int *ptr; ptr = &a; Output: Description Variable 'a' Variable 'ptr' Name of Variable a ptr Type of Value that it holds Integer Address of Integer 'a' Value Stored Address of Variable 2001 (Assumption) 4001 (Assumption) Ex: #include<stdio.h> int a = 3; int *ptr,**pptr; ptr = &a; pptr = &ptr; return 0; Point Variable 'a' Variable 'ptr' Variable 'pptr' Name of Variable a ptr pptr Type of Value that it holds Integer Address of 'a' Address of 'ptr' Value Stored Address of Variable Address Operator (&) Pointer address operator is denoted by & (address of /ampersand symbol). When user use ampersand symbol as a prefix to a variable name &, it gives the address of that variable. To find the address of a variable an operator called address operator (&) is needed. To find out the address of the variable like marks user need to place & operator in front of variable, as &marks. The following program demonstrates how to use address operator (&). #include<stdio.h> Chethan Raj C, Assistant Professor, Dept. of CSE Page 32
33 int i = 12; printf("address of i = %u \n", &i); // Address of i may vary every time when user run the program. printf("value of i = %d ", i); Output: Address of i = Value of i = 12 In order to print the variable then user has to use name of variable while to print the address of the variable by ampersand along with %u. printf("\nvalue of &n is : %u", &n); After declaration memory looks like int i = 5; int *ptr; after Assigning the address of variable to pointer, i.e after the execution of this statement ptr = &i; Assigning Address to Pointer Variable After declaring a pointer variable the next step is to assign some valid memory address to it. User should never use a pointer variable without assigning some valid memory address to it, because just after declaration it contains garbage value and it may be pointing to anywhere in the memory. The use of an unassigned pointer may give an unpredictable result. It may even cause the program to crash. int *ip, i = 10; float *fp, f = 12.2; ip = &i; fp = &f; Here ip is declared as a pointer to int, so it can only point to the memory address of an int variable. Similarly, fp can only point to the address of a float variable. In the last two statements, user have assigned the address of i and f to ip and fp respectively. Now ip points to variable i and fp points to variable f. It is important to note that even if user assign an address of a float variable to an int pointer, the compiler will not show any error and may not get the desired result. So as a general rule always user should always assign the address of a variable to its corresponding pointer variable of the same type. The normal variable must be declared and initialized before the pointer variable. int i = 10, *iptr = &i; Chethan Raj C, Assistant Professor, Dept. of CSE Page 33
34 User can assign the value of one pointer variable to another pointer variable If their base type is same. For example: int marks = 100, *p1, *p2; p1 = &marks; p2 = p1; After the assignment p1 and p2 points to the same variable marks. Asterisk (*) is frequently used with pointers, pointer expressions and arrays. Address of operator (&) is generally used to fetch address of any operand as lvalue. lvalue means variable on the left side of assignment statement. Both these operators are frequently used with pointers. For example: Dereferencing Pointer Variable Address is represented as &a read as address of a. When user taking the value of 'a' using 'input', by taking an input from the user and storing it at the address of 'a', i.e. in a. Referencing (address &) and Dereferencing (value *) of pointer variable: Example: int a = 44; int *b; /* declaration of pointer b */ b = &a; int *b - This statement mean that '*b' is an integer but the significance of '*' before 'b' is that b points to some integer ('b' is a pointer to some integer). Or user can say that 'b' will store the address of some integer. b = &a; - As said, 'b' will store the address of some integer because it is a pointer to an integer. In this declaration, it is storing the address of 'a'. Since 'b' is a pointer and '&a' represents address, so, by declaring 'b = &a;' user are storing the address of 'a' in 'b'. So, *b is the value of the variable 'b' is pointing to. Here *b is 44. 'int *b;' means that '*b' is an integer, but '*' before means that b is a pointer. So, '*b' will be the value of the variable to which 'b' is pointing. Here, 'b' is pointing to 'a' therefore, 'b' will store the address of 'a' and '*b' will be the value of the integer to which 'b' is pointing i.e. 'a'. 1 Asterisk(*) indirection operator is used along with pointer variable while Dereferencing the pointer variable. 2 Asterisk Operator is also called as value at operator. 3 When used with Pointer variable, it refers to variable being pointed to, this is called as Dereferencing of Pointers. 4 Dereferencing Operation is performed to access or manipulate data contained in memory location pointed to by a pointer. 5 Any Operation performed on the de-referenced pointer directly affects the value of variable it pointes to. Ex: int a; - 'a' is an integer. int *b; - 'b' is a pointer to an integer. Chethan Raj C, Assistant Professor, Dept. of CSE Page 34
35 b = &a; - 'b' is now pointing to 'a'(value of 'b' is the address of 'a'). '*b' will now represent a (value of '*b' is the value of 'a'). Dereferencing a pointer variable means accessing data at the address stored in the pointer variable. User have been using the name of the variable to access data inside it, but user can also access variable data indirectly using pointers by using a new operator called indirection operator (*). By placing indirection operator (*) before a pointer variable user can access data of the variable whose address is stored in the pointer variable. int i = 100, *ip = &i; Here ip stores address of variable i, if we place * before ip then we can access data stored in the variable i. It means following two statements does the same thing. printf("%d\n", *ip); // prints 100 printf("%d\n", i); // prints 100 Indirection operator (*) can be read as value at the address. For example, *ip can be read as value at address ip. Note: User must never apply indirection operator to an uninitialized pointer variable that cause unexpected behaviour or the program may even crash. int *ip; printf("%d", *p); // WRONG By dereferencing a pointer variable, user can access the value at the address stored in the pointer variable. Consider how the compiler actually retrieves data. char ch = 'a'; int i = 10; double d = ; char *cp = &ch; int *ip = &i; double *ip = &d; Example: #include<stdio.h> int i = 12, *ip = &i; double d = 2.31, *dp = &d; printf("value of ip = address of i = %d\n", ip); printf("value of fp = address of d = %d\n\n", d); printf("address of ip = %d\n", &ip); printf("address of dp = %d\n\n", &dp); printf("value at address stored in ip = value of i = %d\n", *ip); printf("value at address stored in dp = value of d = %f\n\n", *dp); // memory occupied by pointer variables is same regardless of its base type printf("size of pointer ip = %d\n", sizeof(ip)); printf("size of pointer dp = %d\n\n", sizeof(dp)); Output: Value of ip = address of i = Value of fp = address of d = Address of ip = Address of dp = Chethan Raj C, Assistant Professor, Dept. of CSE Page 35
36 Value at address stored in ip = value of i = 12 Value at address stored in dp = value of d = Size of pointer ip = 4 Size of pointer dp = 4 Note: Memory address may vary every time user run the program. The size of the pointer variables is same regardless of its base type but the size of the memory address that will be accessed while dereferencing depends on upon the base type of the pointer variable. Program 1: Size of Integer Pointer #include<stdio.h> int a = 10, *ptr; ptr = &a; printf("\nsize of Integer Pointer : %d",sizeof(ptr)); Output :Size of Integer Pointer : 2 Program 2 : Size of Character Pointer #include<stdio.h> char a = 'a', *cptr; cptr = &a; printf("\nsize of Character Pointer : %d",sizeof(cptr)); Output : Size of Character Pointer : 2 Program 3: Size of Float Pointer #include<stdio.h> float a = 3.14, *fptr; fptr = &a; printf("\nsize of Character Pointer : %d",sizeof(fptr)); Output : Size of Float Pointer : 2 Size of Pointer variable in C Pointer is the variable that stores the address of another variable. Example : 1. & operator is called as address Operator. 2. * is called as Value at address Operator. 3. Value at address Operator gives Value stored at Particular address. 4. Value at address is also called as Indirection Operator. m = * ( &n ) = * ( Address of Variable 'n') = * ( 1000 ) = Value at Address 1000 = 20 Chethan Raj C, Assistant Professor, Dept. of CSE Page 36
37 An example of pointers. #include <stdio.h> int main() int a = 10; int *p; p = &a; printf( "p = %d\n",p); printf("*p = %d\n",*p); printf ("&p = %d\n", &p); printf("*&p = %d\n", *&p); return 0; Output: p = 0xffff377c(address) *p = 10(value) &p = 0xffff3778(address) *&p = 0xffff377c(address) Value of address will vary every time user run our program because every time a new memory will be allocated. 'p' is a pointer to 'a'. Since 'a' has a value of 10, so '*p' is 10. 'p' stores the address of a. So the output p = 0xffff377c implies that 0xffff377c is the address of 'a'. '&p' represents the address of 'p' which is 0xffff3778. Now, '*&p' is the value of '&p' and the value of '&p' is the address of 'a'. So, it is 0xffff377c. Pointer Arithmetic in C The arithmetic operations can be performed on pointers. User can't perform every/all type of arithmetic operations with pointers. Pointer arithmetic is slightly different from arithmetic. The only valid arithmetic operations applicable on pointers are: 1. Addition of integer to a pointer 2. Subtraction of integer to a pointer 3. Subtracting one pointer from another of the same type The pointer arithmetic is performed relative to the base type of the pointer. For example: if user have an integer pointer ip which contains address 1000, then on incrementing it by 1, user will get 1004 (i.e * 4) instead of 1001 because the size of the int data type is 4 bytes. If user had been using a system where the size of int is 2 bytes then user would get 1002 ( i.e * 2 ). Similarly, on decrementing it, user will get 996 (i.e * 4) instead of 999. So the expression ip + 4 will point to address 1016 (i.e * 4 ). Examples: int i = 12, *ip = &i; double d = 2.3, *dp = &f; char ch = 'a', *cp = &ch; Suppose the address of i, d and ch are 1000, 2000, 3000 respectively, therefore ip, fp and cp are at 1000, 2000, 3000 initially. Pointer Arithmetic on Integers Pointer Expression ip = ip + 1 ip => ip + 1 => *4 => 1004 ip++ or ++ip ip++ => ip + 1 => *4 => 1008 ip = ip + 5 ip => ip + 5 => *4 => 1028 Chethan Raj C, Assistant Professor, Dept. of CSE Page 37
38 Pointer Expression ip = ip - 2 ip => ip - 2 => *4 => 1020 ip-- or --ip ip => ip + 2 => *4 => 1028 Pointer Arithmetic on Float Pointer Expression dp + 1 dp = dp + 1 => *8 => 2008 dp++ or ++dp dp++ => dp+1 => *8 => 2016 dp = dp + 5 dp => dp + 5 => *8 => 2056 dp = dp - 2 dp => dp - 2 => *8 => 2040 dp-- or --dp dp => dp - 1=>2040-1*8=>2032` When user increment or decrement pointer variables using pointer arithmetic then, the address of variables i, d, ch are not affected in any way. Pointer Arithmetic on Characters Pointer Expression cp + 1 cp = cp + 1 => *1 => 3001 cp++ or ++cp cp => cp + 1 => *1 => 3002 cp = cp + 5 cp => cp + 5 => *1 => 3007 cp = cp - 2 cp => cp + 5 => *1 => 3005 cp-- or --cp cp => cp + 2 => *1 => 3004 Arithmetic operation on type char seems like ordinary arithmetic because the size of char type is 1 byte. Another important point to note is that when user increment and decrement pointer variable by adding or subtracting numbers then it is not necessary that the pointer variable still points to a valid memory location hence user must always pay special attention when moving the pointer. Generally, User can use pointer arithmetic with arrays because elements of an array are arranged in contiguous memory locations. Ex: #include<stdio.h> int *ptr=(int *)1000; ptr=ptr+3; printf("new Value of ptr : %u",ptr); Output : New Value of ptr : 1006 Pointer arithmetic program. #include<stdio.h> int i = 12, *ip = &i; Chethan Raj C, Assistant Professor, Dept. of CSE Page 38
39 double d = 2.3, *dp = &d; char ch = 'a', *cp = &ch; printf("value of ip = %d\n", ip); printf("value of dp = %d\n", dp); printf("value of cp = %d\n\n", cp); printf("value of ip + 1 = %d\n", ip + 1); printf("value of dp + 1 = %d\n", dp + 1); printf("value of cp + 1 = %d\n\n", cp + 1); printf("value of ip + 2 = %d\n", ip + 2); printf("value of dp + 2 = %d\n", dp + 2); printf("value of cp + 2 = %d\n", cp + 2); Output: Value of ip = Value of dp = Value of cp = Value of ip + 1 = Value of dp + 1 = Value of cp + 1 = Value of ip + 2 = Value of dp + 2 = Value of cp + 2 = Program on pointer arithmetic between two pointers of the same type. #include<stdio.h> int i1 = 12, *ip1 = &i1; int i2 = 12, *ip2 = &i2; printf("value of ip1 or address of i1 = %u\n", ip1); printf("value of ip2 or address of i2 = %u\n\n", ip2); printf("ip2 - ip1 = %d\n", ip1 - ip2); printf("ip1 - ip2 = %d\n", ip2 - ip1); Output: Value of ip1 or address of i1 = Value of ip2 or address of i2 = ip2 - ip1 = 2 Program for pointer arithmetic (32-bit machine) #include <stdio.h> int m=5,n=10,o=0; int *p1, *p2, *p3; p1 = &m; //printing the address of m p2 = &n;//printing the address of n printf("p1 = %d\n",p1); printf("p2 = %d\n",p2); o = *p1+*p2; printf("*p1+*p2 = %d\n",o);// 1 p3 = p1-p2; printf("p1 - p2 = %d\n",p3); // 2 p1++; Chethan Raj C, Assistant Professor, Dept. of CSE Page 39
40 printf("p1++ = %d\n",p1); // 3 p2--; printf("p2-- = %d\n",p2); // 4 //Below line will give error printf("p1+p2 = %d\n",p1+p2); // 5 Output: p1 = p2 = *p1+*p2 = 15; p1-p2 = 1; p1++ = p2-- = Array of Pointers in C User can declare an array of int, float or char etc, similarly user can also declare an array of pointers, here is the syntax to do the same. Syntax: datatype *array_name[size]; Example: int *arrop[5]; Here arrop is an array of 5 integer pointers. It means that this array can hold the address of 5 integer variables, or in other words, user can assign 5 pointer variables of type pointer to int to the elements of this array. The following program demonstrates how to use an array of pointers. #include<stdio.h> #define SIZE 10 int *arrop[3]; int a = 10, b = 20, c = 50, i; arrop[0] = &a; arrop[1] = &b; arrop[2] = &c; for(i = 0; i < 3; i++) printf("address = %d\t Value = %d\n", arrop[i], *arrop[i]); Output: Address = Value = 10 Address = Value = 20 Address = Value = 50 Process: Consider how address are assigned to a, b and c. In line 9, if the address assigned to the variable a for the 0th element of the of the array is Similarly, the address of b and c is assigned to 1st and 2nd element respectively. At this point arr_of_pointer appears shown below: arrop[i] gives the address of ith element of the array. So arrop[0] returns address of variable a, arrop[1]returns address of b and so on. To get the value at address use indirection operator (*). *arrop[i], So *arrop[0] gives value at address[0], Similarly *arrop[1] gives the value at address arrop[1] and so on. Since *p refers to the first array element, *(p+1) and *(p+2) refers to the second and third elements respectively and so on. So, *p is age[0], *(p+1) is age[1], *(p+2) is age[2]. Chethan Raj C, Assistant Professor, Dept. of CSE Page 40
41 Similarly, *age is age[0] ( value at age ), *(age+1) is age[1] ( value at age+1 ), *(age+2) is age[2] ( value at age+2 ) and so on. Symbol Name Description & address of operator Determines the address of a variable. * indirection operator Accesses the value at the address. Advantages of pointer 1. Access any memory location 2. Improves the performance i.e reduces the execution time of the program. 3. Reduces the code 4. Used in arrays, functions and structures 5. Pointers provide direct access to memory. 6. Pointers allows user to return more than one value from the functions. 7. Pointers provides/used to perform dynamic memory allocation and deallocation. Disadvantages of Pointer 1. Uninitialized pointers might cause segmentation fault. 2. Dynamically allocated block needs to be freed explicitly. 3. If pointers are updated with incorrect values, it might lead to memory corruption Pointer and Array When user declares an array the compiler allocates continuous blocks of memory so that all the elements of an array can be stored in that memory. The address of first allocated byte or the address of first element is assigned to an array name. The different data in an array can be referenced through pointers instead of using array subscripts. The data type of such a pointer is referred to as "pointer to array of type". The array name itself behaves like a pointer, so there are several alternative methods to accessing array elements. For example : int x[5] = 0, 1, 2, 3, 4 ; //Array x declared with five elements int *p = x; // Pointer declared and initialized to point to the first element of the array int a, b; a = *(x + 3); //Pointer x incremented by twelve bytes to reference element 3 of x b = x[3]; /* b now holds the same value as a */ In the previous example, a receives the value 3 by using the dereferencing operator (*). The b receives the same value by using the subscripting operator. The address of first element is also known as base address. Example: Displaying elements of an array using pointer. #include<stdio.h> Chethan Raj C, Assistant Professor, Dept. of CSE Page 41
42 int arr []=78,45,12,89,56,23,79,46,13,82; // Array of 10 elements int *ptr; // Pointer variable ptr = arr; // Assigning reference of array in pointer variable printf("\nvalues : "); for(int a=1;a<=10;a++) printf("%d, ",*ptr); // Displaying values of array using pointer ptr++; // Incrementing pointer variable Output : Values : 78, 45, 12, 89, 56, 23, 79, 46, 13, 82, In the above example statement 1 creates an array of 10 elements. Statement 2 creates a pointer variable ptr. The array name acts as pointer variable (Constant pointer) therefore statement 3 is assigning the address of array in pointer variable ptr. Now ptr have the address of first element in an array. Statement 4 will display the value at address of ptr. After display the first value, statement 5 increase the pointer variable ptr to point to next element in an array and statement 4 will display the next value in an array until the loop ends. Ex: pointers and arrays #include <stdio.h> inti, classes[6],sum = 0; printf("enter 6 numbers:\n"); for(i = 0; i< 6; ++i) scanf("%d",(classes + i)); // (classes + i) is equivalent to &classes[i] sum += *(classes + i); // *(classes + i) is equivalent to classes[i] printf("sum = %d", sum); Output: Enter 6 numbers: Sum = 21 Array of Pointers Array is a collection of values of similar type. It can also be a collection of references of similar type. Syntax: Data-type * array [size]; Example: #include<stdio.h> int x=10,y=20,z=30; int *arr[3]; // Declaring array of three pointer arr[0] = &x; // Assigning reference of x to array 0th position arr[1] = &y; // Assigning reference of y to array 1th position Chethan Raj C, Assistant Professor, Dept. of CSE Page 42
43 arr[2] = &z; // Assigning reference of z to array 2nd position printf("\nvalues : "); for(int a=0;a<3;a++) printf("%d, ",*arr[a]); Output : Values : 10, 20, 30, In the above example, user declared three variable x, y, z and assigning the addresses of these variables into an array of pointer(*arr[]). Ex: #include<stdio.h> float var[5]=1.1f,2.2f,3.3f; float(*ptr)[5]; ptr=&var; printf("value inside ptr : %u",ptr); ptr=ptr+1; printf("value inside ptr : %u",ptr); Output : Value inside ptr : 1000 Value inside ptr : 1020 Address of ptr[0] = 1000 The storing Address of float array to ptr[0]. Address of ptr[1] = Address of ptr[0] + (Size of Data Type)*(Size of Array) = (4 bytes) * (5) = 1020 Address of Var[0] Var[4] : Address of var[0] = 1000 Address of var[1] = 1004 Address of var[2] = 1008 Address of var[3] = 1012 Address of var[4] = 1016 Array vs pointers 1) Array name gives address of first element of array. Consider the following program for example. Ex: #include <stdio.h> int arr[] = 10, 20, 30, 40, 50, 60; int *ptr = arr; // Assigns address of array to ptr printf("value of first element is %d", *ptr); Chethan Raj C, Assistant Professor, Dept. of CSE Page 43
44 Output: Value of first element is 10 2) Array members are accessed using pointer arithmetic. Compiler uses pointer arithmetic to access array element. For example, an expression like arr[i] is treated as *(arr + i) by the compiler. That is why the expressions like *(arr + i) work for array arr, and expressions like ptr[i] also work for pointer ptr. Ex: #include <stdio.h> int arr[] = 10, 20, 30, 40, 50, 60; int *ptr = arr; printf("arr[2] = %d\n", arr[2]); printf("*(arr + 2) = %d\n", *(arr + 2)); printf("ptr[2] = %d\n", ptr[2]); printf("*(ptr + 2) = %d\n", *(ptr + 2)); Output: arr[2] = 30 *(arr + 2) = 30 ptr[2] = 30 *(ptr + 2) = 30 3) Array parameters are always passed as pointers, even when users use square brackets. Ex: #include <stdio.h> void fun(int ptr[]) int x = 10; printf("sizeof(ptr) = %d\n", sizeof(ptr)); // size of a pointer is printed ptr = &x; // This allowed because ptr is a pointer, not array printf("*ptr = %d ", *ptr); int arr[] = 10, 20, 30, 40, 50, 60; fun(arr); Output: sizeof(ptr) = 4 *ptr = 10 The generalized form for using pointer with an array, *(a+i) is same as a[i]. Chethan Raj C, Assistant Professor, Dept. of CSE Page 44
45 Pointer and Array Difference Pointer 1. A pointer is a place in memory that keeps the address of another place inside Array 1. An array is a single, pre-allocated chunk of contiguous elements (all of the same type), fixed in size and location. 2. Pointer can t be initialized at definition. 2. Array can be initialized at definition. Example int num[] = 2, 4, 5 3. Pointer is dynamic in nature. The memory allocation can be resized or freed later. 4. The assembly code of Pointer is different than Array 3. They are static in nature. Once the memory is allocated, it cannot be resized or freed dynamically. 4. The assembly code of Array is different than Pointer. Pointers and 1-D arrays The elements of an array are stored in contiguous memory locations. For example: if user have the following array. int my_arr[5] = 1, 2, 3, 4, 5; The elements are stored in the array as shown below: Here the first element is at address 5000, since each integer takes 4 bytes the next element is at 5004 and so on. In C, pointers and arrays are very closely related. User can access the elements of the array using a pointer. Behind the scenes compiler also access elements of the array using pointer notation rather than subscript notation because accessing elements using pointer is very efficient as compared to subscript notation. The most important thing to remember about the array is this: The name of the array is a constant pointer that points to the address of the first element of the array or the base address of the array. User can use subscript notation (i.e using square brackets) to find the address of the elements of the array. For example: int my_arr[5] = 11, 22, 33, 44, 55; here &my_arr[0] points to the address of the first element of the array. Since the name of the array is a constant pointer that points to the first element of the array, my_arr and &my_arr[0] represent the same address. &my_arr[1] points to the address of the second element. Similarly &my_arr[2] points to the address of the third element and so on. Note: my_arr is of type (int *) or pointer to int. The following program demonstrates that the elements of an array are stored in contiguous memory locations: #include<stdio.h> int my_arr[5] = 1, 2, 3, 4, 5, i; for(i = 0; i < 5; i++) printf("value of a[%d] = %d\t", i, my_arr[i]); printf("address of a[%d] = %u\n", i, &my_arr[i]); Chethan Raj C, Assistant Professor, Dept. of CSE Page 45
46 Output: Value of a[0] = 1 Address of a[0] = Value of a[1] = 2 Address of a[1] = Value of a[2] = 3 Address of a[2] = Value of a[3] = 4 Address of a[3] = Value of a[4] = 5 Address of a[4] = Note: Memory address may differ every time when user run the program. Using pointers to access elements and address of elements in an array In programme the name of the array is a constant pointer to the first element. Consider the following snippet: int arr[] = 1,2,3,4,5; Here arr is a pointer to the first element.pointer to int or (int *). In this case, arr points to the address of an integer number i.e address of integer 1. So the base type of arr is a pointer to int or (int*). Example: char arr[] = 'A','B','C','D','E'; The type of pointer arr is, here arr points to the address of the first element which is a character. So the type of arr is a pointer to charor (char *). Similarly, double arr[] = 1.03, 29.3, 3.42, 49.3, 51.2; here arr is a pointer of type pointer to double or (double *). Now user can easily access values and address of elements using pointer arithmetic. Suppose my_arr is an array of 5 integers. int my_arr[5] = 11, 22, 33, 44, 55; Here my_arr is a constant pointer of base type pointer to int or (int *) and according to pointer arithmetic when an integer is added to a pointer user get the address of the next element of same base type. So In the above example my_arr points to the address of the first element, my_arr+1 points to the address of the second element, my_arr + 2 points to the address of the third element and so on. my_arr is same as &my_arr[0] my_arr + 1 is same as &my_arr[1] my_arr + 2 is same as &my_arr[2] my_arr + 3 is same as &my_arr[3] my_arr + 4 is same as &my_arr[4] In general (my_arr + i) is same as writing &my_arr[i]. Now to get the address of each element of the array, by using indirection operator (*) user can get the value at the address. If user dereference my_arr then user get the first element of the array i.e *my_arr. Similarly, *(my_arr + 1) will return the second element of the array and so on. `*(my_arr)` is same as `my_arr[0]` `*(my_arr + 1)` is same as `my_arr[1]` `*(my_arr + 2)` is same as `my_arr[2]` `*(my_arr + 3)` is same as `my_arr[3]` `*(my_arr + 4)` is same as `my_arr[4]` In general *(my_arr+i) is same as writing my_arr[i]. The following program prints value and address of array elements using pointer notation. #include<stdio.h> int my_arr[5] = 1, 2, 3, 4, 5, i; for(i = 0; i < 5; i++) printf("value of a[%d] = %d\t", i, *(my_arr + i) ); Chethan Raj C, Assistant Professor, Dept. of CSE Page 46
47 printf("address of a[%d] = %u\n", i, my_arr + i ); Output: Value of a[0] = 1 Address of a[0] = Value of a[1] = 2 Address of a[1] = Value of a[2] = 3 Address of a[2] = Value of a[3] = 4 Address of a[3] = Value of a[4] = 5 Address of a[4] = Note: Memory address may differ every time user run the program. Assigning 1-D array to a Pointer variable User can assign a 1-D array to a pointer variable. Consider the following example: int *p; int my_arr[] = 11, 22, 33, 44, 55; p = my_arr; Now user can use pointer p to access address and value of each element in the array. It is important to note that assignment of a 1-D array to a pointer to int is possible because my_arr and p are of the same base type i.e pointer to int. In general (p+i) denotes the address of the ith element and *(p+i) denotes the value of the ith element. There are some differences between the name of the array (i.e my_arr) and pointer variable (i.e p). The name of the array is a constant pointer hence user can't alter it to point to some other memory location. User can t assign some other address to it nor user can apply increment/decrement operator like pointer variable. my_arr++; // error my_arr--; // error my_arr = &i // error However, p is an ordinary pointer variable, so user can apply pointer arithmetic and even assign a new address to it. p++; // valid p--; // valid p = &i // valid The following program demonstrates how user can access values as address of elements of a 1-D array by assigning it to a pointer variable. Ex: #include<stdio.h> int my_arr[5] = 1, 2, 3, 4, 5, i; int *p; p = my_arr; // p = &my_arr[0]; // user can represent the alternate syntax for(i = 0; i < 5; i++) printf("value of a[%d] = %d\t", i, *(p + i) ); printf("address of a[%d] = %u\n", i, p + i ); Output: Value of a[0] = 1 Address of a[0] = Value of a[1] = 2 Address of a[1] = Chethan Raj C, Assistant Professor, Dept. of CSE Page 47
48 Value of a[2] = 3 Address of a[2] = Value of a[3] = 4 Address of a[3] = Value of a[4] = 5 Address of a[4] = Note: Memory address may differ every time when user run the program. Ex: A pointer that points to the 0th element of an array and a pointer that points to the whole array are totally different. The following program demonstrates this concept. #include<stdio.h> int *p; // pointer to int int (*parr)[5]; // pointer to an array of 5 integers int my_arr[5]; // an array of 5 integers p = my_arr; parr = my_arr; printf("address of p = %u\n", p ); printf("address of parr = %u\n", parr ); p++; parr++; printf("\nafter incrementing p and parr by 1 \n\n"); printf("address of p = %u\n", p ); printf("address of parr = %u\n", parr ); printf("address of parr = %u\n", *parr ); Output: Address of p = Address of parr = After incrementing p and parr by 1 Address of p = Address of parr = Here p is a pointer which points to the 0th element of the array my_arr, while parr is a pointer which points to the whole array my_arr. The base type of p is of type (int *) or pointer to int and base type of parr is pointer to an array of 5 integers. Since the pointer arithmetic is performed relative to the base type of the pointer, that's why parr is incremented by 20 bytes i.e ( 5 x 4 = 20 bytes ). On the other hand, p is incremented by 4bytes only. The important point about pointer to an array is: Whenever a pointer to an array is de-referenced user get the address (or base address) of the array to which it points. So, on dereferencing parr, user will get *parr. The important thing to notice is although parr and *parr points to the same address, but parr's base type is a pointer to an array of 5 integers, while *parr base type is a pointer to int. This is an important concept and will be used to access the elements of a 2-D array. Dynamic Memory Allocation Functions. Memory Allocation Process: Global variables, static variables and program instructions get their memory in permanent storage area whereas local variables are stored in a memory area called Stack. The memory space between these two region is known as Heap area. This region is used for dynamic memory allocation during execution of the program. The size of heap keep changing. In C and C++, it s very convenient to allocate and de-allocate blocks of memory as and when needed. Chethan Raj C, Assistant Professor, Dept. of CSE Page 48
49 The concept of dynamic memory allocation in a programming language enables the user/programmer to allocate memory at runtime. Dynamic memory allocation is possible by 4 functions/methods by using the stdlib.h header file. malloc(): Allocates single block of requested memory calloc(): Allocates multiple block of requested memory. realloc(): Reallocates the memory occupied by malloc() or calloc() functions. free(): Frees/Delete the dynamically allocated memory. Consider the difference between static memory allocation and dynamic memory allocation. Static Memory Allocation In static memory allocation, memory is allocated while writing the C program. Actually, user requested memory will be allocated at compile time. Memory size can t be modified while execution. Example: array It allocates only single block of requested memory int *ptr; ptr = malloc( 20 * sizeof(int)); For the above syntax, 20*4 bytes of memory only allocated in one block. Total = 80 bytes malloc () doesn t initializes the allocated memory. It contains garbage values type cast must be done since this function returns void pointer int*ptr; ptr = (int*)malloc(sizeof(int)*20); Dynamic Memory Allocation In dynamic memory allocation, memory is allocated while executing the program. That means at run time. Memory size can be modified while execution. Example: Linked list It allocates multiple blocks of requested memory int *ptr; Ptr = calloc( 20, 20 * sizeof(int) ); For the above syntax, 20 blocks of memory will be created and each contains 20*4 bytes of memory. Total = 1600 bytes calloc () initializes the allocated memory to zero Same as malloc () function int *ptr; ptr = (int*)calloc( 20, 20 * sizeof(int) ); malloc() function The malloc() function allocates single block of requested memory. It doesn't initialize memory at execution time, so it has garbage value initially. It returns NULL if memory is not sufficient. The syntax of malloc() function is given below: ptr=(cast-type*)malloc(byte-size) Example of malloc() function. #include<stdio.h> #include<stdlib.h> Chethan Raj C, Assistant Professor, Dept. of CSE Page 49
50 int n,i,*ptr,sum=0; printf("enter number of elements: "); scanf("%d",&n); ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc if(ptr==null) printf("sorry! unable to allocate memory"); exit(0); printf("enter elements of array: "); for(i=0;i<n;++i) scanf("%d",ptr+i); sum+=*(ptr+i); printf("sum=%d",sum); free(ptr); Output: Enter elements of array: 3 Enter elements of array: Sum=30 calloc() function The calloc() function allocates multiple block of requested memory. It initially initialize all bytes to zero. It returns NULL if memory is not sufficient. The syntax of calloc() function is given below: ptr=(cast-type*)calloc(number, byte-size) Example of calloc() function. #include<stdio.h> #include<stdlib.h> int n,i,*ptr,sum=0; printf("enter number of elements: "); scanf("%d",&n); ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc if(ptr==null) printf("sorry! unable to allocate memory"); exit(0); printf("enter elements of array: "); for(i=0;i<n;++i) scanf("%d",ptr+i); sum+=*(ptr+i); printf("sum=%d",sum); free(ptr); Chethan Raj C, Assistant Professor, Dept. of CSE Page 50
51 Output: Enter elements of array: 3 Enter elements of array: Sum=30 Program to represent Dynamic Memory Allocation(using calloc()) #include <stdio.h> #include <stdlib.h> int i, n; int *element; printf("enter total number of elements: "); scanf("%d", &n);\ //returns a void pointer(which is type-casted to int*) pointing to the first block of the allocated space. element = (int*) calloc(n,sizeof(int)); // If it fails to allocate enough space as specified it returns a NULL pointer. if(element == NULL) printf("error.not enough space available"); exit(0); for(i = 0; i < n; i++) // storing elements from the user in the allocated space scanf("%d", element+i); for(i = 1; i < n; i++) if(*element > *(element+i)) *element = *(element+i); printf("smallest element is %d", *element); Output: Enter total number of elements: Smallest element is 1 realloc() function If memory is not sufficient for malloc() or calloc(), user can reallocate the memory by realloc() function. In short, it changes the memory size. The syntax of realloc() function: ptr=realloc(ptr, new-size) Ex: #include <stdio.h> #include <stdlib.h> int *ptr, i, n1, n2; Chethan Raj C, Assistant Professor, Dept. of CSE Page 51
52 printf("enter size of array: "); scanf("%d", &n1); ptr = (int*) malloc(n1 * sizeof(int)); printf("address of previously allocated memory: "); for(i = 0; i < n1; ++i) printf("%u\t",ptr + i); printf("\nenter new size of array: "); scanf("%d", &n2); ptr = realloc(ptr, n2); for(i = 0; i < n2; ++i) printf("%u\t", ptr + i); free() function The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit. The syntax of free() function: free(ptr); Diffrence between malloc() and calloc() calloc() calloc() initializes the allocated memory with 0 value. malloc() malloc() initializes the allocated memory with garbage values. Number of arguments is 2 Number of argument is 1 Syntax : (cast_type *)calloc(blocks, size_of_block); Syntax : (cast_type *)malloc(size_in_bytes); Representation of Linear Arrays in Memory (Pointers and 2-D Array) User visualize the 2-D array as a matrix. For example: int arr[3][4] = 11,22,33,44, 55,66,77,88, 11,66,77,44 ; The above 2-D array can be visualized as following: The terms like rows and column are used in 2d array for theoretical process, but in computer memory representation is linear and there are no rows and columns format. The 2-D arrays are stored in memory as row-major order. i.e first row 0 is stored, then next to it row 1 is stored, next to it row 2 is stored and so on. The following figure shows how a 2-D array is stored in the memory. Chethan Raj C, Assistant Professor, Dept. of CSE Page 52
53 A 2-D array is actually a 1-D array in which each element is itself a 1-D array. So arr is an array of 3 elements where each element is a 1-D array of 4 integers. The name of a 1-D array is a constant pointer to the 0th element. In the case, of a 2-D array, 0th element is a 1-D array. Hence in the above example, the type or base type of arr is a pointer to an array of 4 integers. Since pointer arithmetic is performed relative to the base size of the pointer. In the case of arr, if arr points to address 2000 then arr + 1 points to address 2016 (i.e *4). The name of the array in case of a 2-D array represents a pointer to the 0th 1-D array. Therefore in this case arr is a pointer to an array of 4 elements. If the address of the 0th 1-D is 2000, then according to pointer arithmetic (arr + 1) will represent the address 2016, similarly (arr + 2) will represent the address Note: arr points to 0th 1-D array. (arr + 1) points to 1st 1-D array. (arr + 2) points to 2nd 1-D array. In general,: (arr + i) points to i th 1-D array. The dereferencing a pointer to an array gives the base address of the array. So dereferencing arr user will get *arr, base type of *arr is (int*). Similarly, on dereferencing arr+1 user will get *(arr+1). In general, *(arr+i) points to the base address of the ith 1-D array. Again it is important to note that type (arr + i) and *(arr+i) points to same address but their base types are completely different. The base type of (arr + i) is a pointer to an array of 4 integers, while the base type of *(arr + i) is a pointer to int or (int*). The user can use arr to access individual elements of a 2-D array Since *(arr + i) points to the base address of every ith 1-D array and it is of base type pointer to int, by using pointer arithmetic user should able to access elements of ith 1-D array. *(arr + i) points to the address of the 0th element of the 1-D array. So, *(arr + i) + 1 points to the address of the 1st element of the 1-D array *(arr + i) + 2 points to the address of the 2nd element of the 1-D array *(arr + i) + j points to the base address of jth element of ith 1-D array. On dereferencing *(arr + i) + j user will get the value of jth element of ith 1-D array. *(*(arr + i) + j) by using this expression user can find the value of jth element of ith 1-D array.furthermore, the pointer notation ((arr + i) + j) is equivalent to the subscript notation. The following program demonstrates how to access values and address of elements of a 2-D array using pointer notation. Ex: #include<stdio.h> int arr[3][4] = Chethan Raj C, Assistant Professor, Dept. of CSE Page 53
54 11,22,33,44, 55,66,77,88, 11,66,77,44 ; int i, j; for(i = 0; i < 3; i++) printf("address of %d th array %u \n",i, *(arr + i)); for(j = 0; j < 4; j++) printf("arr[%d][%d]=%d\n", i, j, *( *(arr + i) + j) ); printf("\n\n"); Output: Address of 0 th array arr[0][0]=11 arr[0][1]=22 arr[0][2]=33 arr[0][3]=44 Address of 1 th array arr[1][0]=55 arr[1][1]=66 arr[1][2]=77 arr[1][3]=88 Address of 2 th array arr[2][0]=11 arr[2][1]=66 arr[2][2]=77 arr[2][3]=44 Assigning 2-D Array to a Pointer Variable User can assign the name of the array to a pointer variable, but unlike 1-D array user need pointer to an array instead of pointer to int or (int *). Ex: int arr[2][3] = 33, 44, 55, 11, 99, 66 ; Always remember a 2-D array is actually a 1-D array where each element is a 1-D array. So arr as an array of 2elements where each element is a 1-D arr of 3 integers. Hence to store the base address of arr, user need a pointer to an array of 3 integers. Similarly, If a 2-D array has 3 rows and 4 cols i.e int arr[3][4], then user need a pointer to an array of 4integers. int (*p)[3]; Here p is a pointer to an array of 3 integers. So according to pointer arithmetic p+i points to the ith 1-D array, in other words, p+0 points to the 0th 1-D array, p+1 points to the 1st 1-D array and so on. The base type of (p+i) is a pointer to an array of 3 integers. If user dereference (p+i) then user will get the base address of ith 1-D array but now the base type of *(p + i) is a pointer to int or (int *). Again to access the address of jth element ith 1-D array, user just have to add j to *(p + i). So *(p + i) + j points Chethan Raj C, Assistant Professor, Dept. of CSE Page 54
55 to the address of jth element of ith 1-D array. Therefore the expression *(*(p + i) + j) gives the value of jth element of ith 1-D array. The following program demonstrates how to access elements of a 2-D array using a pointer to an array. #include<stdio.h> int arr[3][4] = 11,22,33,44, 55,66,77,88, 11,66,77,44 ; int i, j; int (*p)[4]; p = arr; for(i = 0; i < 3; i++) printf("address of %d th array %u \n",i, p + i); for(j = 0; j < 4; j++) printf("arr[%d][%d]=%d\n", i, j, *( *(p + i) + j) ); printf("\n\n"); Output: Address of 0 th array arr[0][0]=11 arr[0][1]=22 arr[0][2]=33 arr[0][3]=44 Address of 1 th array arr[1][0]=55 arr[1][1]=66 arr[1][2]=77 arr[1][3]=88 Address of 2 th array arr[2][0]=11 arr[2][1]=66 arr[2][2]=77 arr[2][3]=44 Dynamically allocated arrays An array is a powerful and easy-to-use data structure. Arrays provide easy access to their elements and entire arrays can be manipulated easily using loops. However, there are some drawbacks/limitations of arrays: 1. Inability to resize an array at run-time: As the memory for arrays is allocated at compile time, it is not possible to change the array size during program execution. Thus, if the declared array size is insufficient in some situation, the executable program is not effective and efficient, hence user need to modify the source code suitably and recompile the program. Chethan Raj C, Assistant Professor, Dept. of CSE Page 55
56 2. Memory wastage: As array size cannot be increased at run-time, a programmer tends to declare arrays much larger than usually required to cater to some unforeseen situations. This leads to wastage of memory in most of the executions. To overcome these limitations, user can implement the dynamic arrays using the dynamic memory allocation feature. This allows a programmer to allocate only the required memory for arrays. Ex:#include <stdio.h> #include <stdlib.h> int i, n; int *arr; printf("\n Enter the number of elements "); scanf ("%d", &n); arr= (int*)malloc(n * sizeof(int)); if(arr ==NULL) printf("\n Memory Allocation Failed"); exit(0); for(i=0;i<n;i++) printf("\n Enter the value %d of the array: ",i ); scanf("%d", &arr[i]); printf("\n The array contains \n"); for (i=0; i<n; i++) printf(" \n \t%d \t", arr[i]); /*another way is to write *(arr+i) */ Output: In addition to dynamically allocating single values, user can also dynamically allocate arrays of variables. Unlike a fixed array, where the array size must be fixed at compile time, dynamically allocating an array allows us to choose an array length at runtime. To allocate an array dynamically, user use the array form of malloc and calloc in C, new and delete in c++ (often called new[] and delete[]): Accessing structure member through pointer using dynamic memory allocation To access structure member using pointers, memory can be allocated dynamically using malloc() function defined under "stdlib.h" header file. Chethan Raj C, Assistant Professor, Dept. of CSE Page 56
57 Syntax to use malloc(): ptr = (cast-type*) malloc(byte-size); Example to use structure's member through pointer using malloc() function. #include <stdio.h> #include <stdlib.h> struct person int age; float weight; char name[30]; ; struct person *ptr; int i, num; printf("enter number of persons: "); scanf("%d", &num); ptr = (struct person*) malloc(num * sizeof(struct person));/*above statement allocates the memory for n structures with pointer personptr pointing to base address */ for(i = 0; i < num; ++i) printf("enter name, age and weight of the person respectively:\n"); scanf("%s%d%f", &(ptr+i)->name, &(ptr+i)->age, &(ptr+i)->weight); printf("displaying Infromation:\n"); for(i = 0; i < num; ++i) printf("%s\t%d\t%.2f\n", (ptr+i)->name, (ptr+i)->age, (ptr+i)->weight); Output: Enter number of persons: 2 Enter name, age and weight of the person respectively: A Enter name, age and weight of the person respectively: E Displaying Information: A E The Dynamic Memory Allocation for Structure #include <stdio.h> #include<stdlib.h> struct course int marks; char subject[30]; ; struct course *ptr; Chethan Raj C, Assistant Professor, Dept. of CSE Page 57
58 int i, noofrecords; printf("enter number of records: "); scanf("%d", &noofrecords); // Allocates the memory for noofrecords structures with pointer ptr pointing to the base address. ptr = (struct course*) malloc (noofrecords * sizeof(struct course)); for(i = 0; i < noofrecords; ++i) printf("enter name of the subject and marks respectively:\n"); scanf("%s %d", &(ptr+i)->subject, &(ptr+i)->marks); printf("displaying Information:\n"); for(i = 0; i < noofrecords ; ++i) printf("%s\t%d\n", (ptr+i)->subject, (ptr+i)->marks); Output: Enter number of records: 2 Enter name of the subject and marks respectively: Programming 22 Enter name of the subject and marks respectively: Structure 33 Displaying Information: Programming 22 Structure 33 USER-DEFINED DATA TYPES (typedef) The typedef feature allows users to define new data types that are equivalent to existing data types. In general terms, a user-defined structure type can be written as Syntax: typedef struct member 1; member 2: member m; new-type; new-type var1,var2,...;//user can declare var1 to n of new-type. The typedef feature can be used repeatedly, to define one data type in terms of other user-defined data types. TYPEDEF is an alternative way for structure declaration: typedef struct student int mark [2]; char name [10]; float average; status; To declare structure variable, we can use the below statements. status record1; /* record 1 is structure variable */ status record2; /* record 2 is structure variable */ Example: #include <stdio.h> Chethan Raj C, Assistant Professor, Dept. of CSE Page 58
59 #include <string.h> typedef struct int id; char name[20]; float percentage; status; status record; record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); Passing Struct to function A structure can be passed to any function from main function or from any sub function. Structure definition will be available within the function only. Structure is not available to other functions unless it is passed to those functions by value or by address(reference) or else user have to declare structure variable as global variable. i.e, structure variable should be declared outside the main function. Hence the structure will be visible to all the functions in a C program The different ways to create a 2D array on heap (or dynamically allocate a 2D array). Using a single pointer: A simple way is to allocate memory block of size r*c and access elements using simple pointer arithmetic. #include <stdio.h> #include <stdlib.h> int main() int r = 3, c = 4; int *arr = (int *)malloc(r * c * sizeof(int)); int i, j, count = 0; for (i = 0; i < r; i++) for (j = 0; j < c; j++) *(arr + i*c + j) = ++count; for (i = 0; i < r; i++) for (j = 0; j < c; j++) printf("%d ", *(arr + i*c + j)); Output: Using an array of pointers User can create an array of pointers of size r with variable sized arrays. After creating an array of pointers, user can dynamically allocate memory for every row. #include <stdio.h> #include <stdlib.h> Chethan Raj C, Assistant Professor, Dept. of CSE Page 59
60 int r = 3, c = 4, i, j, count; int *arr[r]; for (i=0; i<r; i++) arr[i] = (int *)malloc(c * sizeof(int)); // Note that arr[i][j] is same as *(*(arr+i)+j) count = 0; for (i = 0; i < r; i++) for (j = 0; j < c; j++) arr[i][j] = ++count; // Or *(*(arr+i)+j) = ++count for (i = 0; i < r; i++) for (j = 0; j < c; j++) printf("%d ", arr[i][j]); Output: Polynomials A polynomial p(x) is the expression in variable x which is in the form (axn + bxn jx+ k), where a, b, c., k are of real numbers and 'n' is non negative integer, which is called the degree of polynomial. A polynomial is an expression that contains more than two terms. A term is made up of coefficient and exponent. An example of polynomial is, P(x) = 4x3+6x2+7x+9 An essential characteristic of the polynomial is that each term in the polynomial expression consists of two parts(term), One is the coefficient Other is the exponent Polynomial operations Representation Addition Multiplication Example: 10x2 + 26x, here 10 and 26 are coefficients and 2, 1 is its exponential value. Representation of Polynomial Polynomial can be represented as By the use of arrays By the use of Linked List Array representation assumes that the exponents of the given expression are arranged from 0 to the highest value (degree), which is represented by the subscript of the array beginning with 0. The coefficients of the respective exponent are placed at an appropriate index in the array. The array representation for the above polynomial expression is given below: Chethan Raj C, Assistant Professor, Dept. of CSE Page 60
61 A polynomial may also be represented using a linked list. A structure may be defined such that it contains two parts- one is the coefficient and second is the corresponding exponent. The structure definition may be given as shown below: struct polynomial int coefficient; int exponent; struct polynomial *next; ; Addition of two Polynomials: Adding of two polynomials using arrays is straightforward method, since both the arrays are added by element wise beginning from 0 to n-1, resulting in addition of two polynomials. Addition of two polynomials using linked list requires comparing the exponents, and wherever the exponents are found to be same, the coefficients are added up. For terms with different exponents, the complete term is simply added to the result thereby making it a part of addition result. Ex: Program to add the two polynomial #include<stdio.h> #include<math.h> /* This structure is used to store a polynomial term. An array of such terms represents a Polynomial. The "coeff" element stores the coefficient of a term in the polynomial, while the "exp" element stores the exponent. */ struct poly float coeff; int exp; ; struct poly a[50],b[50],c[50],d[50]; //declaration of polynomials int i; int deg1,deg2; //stores degrees of the polynomial int k=0,l=0,m=0; printf("enter the highest degree of polynomial1:"); scanf("%d",°1); //taking polynomial terms from the user for(i=0;i<=deg1;i++) printf("\nenter the coeff of x^%d :",i); //entering values in coefficient of the polynomial terms scanf("%f",&a[i].coeff); Chethan Raj C, Assistant Professor, Dept. of CSE Page 61
62 a[k++].exp = i; //entering values in exponent of the polynomial terms printf("\nenter the highest degree of polynomial2:"); //taking second polynomial from the user scanf("%d",°2); for(i=0;i<=deg2;i++) printf("\nenter the coeff of x^%d :",i); scanf("%f",&b[i].coeff); b[l++].exp = i; printf("\nexpression 1 = %.1f",a[0].coeff); //printing first polynomial for(i=1;i<=deg1;i++) printf("+ %.1fx^%d",a[i].coeff,a[i].exp); printf("\nexpression 2 = %.1f",b[0].coeff); //printing second polynomial for(i=1;i<=deg2;i++) printf("+ %.1fx^%d",b[i].coeff,b[i].exp); if(deg1>deg2) //Adding the polynomials for(i=0;i<=deg2;i++) c[m].coeff = a[i].coeff + b[i].coeff; c[m].exp = a[i].exp; m++; for(i=deg2+1;i<=deg1;i++) c[m].coeff = a[i].coeff; c[m].exp = a[i].exp; m++; else for(i=0;i<=deg1;i++) c[m].coeff = a[i].coeff + b[i].coeff; c[m].exp = a[i].exp; m++; for(i=deg1+1;i<=deg2;i++) c[m].coeff = b[i].coeff; c[m].exp = b[i].exp; m++; printf("\nexpression after addition = %.1f",c[0].coeff); //printing the sum of the two polynomials for(i=1;i<m;i++) Chethan Raj C, Assistant Professor, Dept. of CSE Page 62
63 printf("+ %.1fx^%d",c[i].coeff,c[i].exp); output: Enter the highest degree of polynomial1:3 Enter the coeff of x^0 :2 Enter the coeff of x^1 :3 Enter the coeff of x^2 :5 Enter the coeff of x^3 :1 Enter the highest degree of polynomial2:2 Enter the coeff of x^0 :7 Enter the coeff of x^1 :8 Enter the coeff of x^2 :5 Expression 1 = x^1+ 5.0x^2+ 1.0x^3 Expression 2 = x^1+ 5.0x^2 Expression after addition = x^ x^2+ 1.0x^3 Multiplication of two polynomial Multiplication of two polynomials requires manipulation of each node such that the exponents are added up and the coefficients are multiplied. After each term of first polynomial is operated upon with each term of the second polynomial, then the result has to be added up by comparing the exponents and adding the coefficients for similar exponents and including terms as such with dissimilar exponents in the result. /*Program to multiply the two polynomial, /* This structure is used to store a polynomial term. An array of such terms represents a polynomial. The "coeff" element stores the coefficient of a term in the polynomial, while the "exp" element stores the exponent.*/ #include<stdio.h> #include<math.h> struct poly float coeff; int exp; ; struct poly a[50],b[50],c[50],d[50]; //declaration of polynomials int i; int deg1,deg2; //stores degrees of the polynomial int k=0,l=0,m=0; printf("enter the highest degree of polynomial1:"); scanf("%d",°1); //taking polynomial terms from the user for(i=0;i<=deg1;i++) printf("\nenter the coeff of x^%d :",i); //entering values in coefficient of the polynomial terms scanf("%f",&a[i].coeff); //entering values in exponent of the polynomial terms a[k++].exp = i; printf("\nenter the highest degree of polynomial2:"); //taking second polynomial from the user scanf("%d",°2); for(i=0;i<=deg2;i++) printf("\nenter the coeff of x^%d :",i); scanf("%f",&b[i].coeff); Chethan Raj C, Assistant Professor, Dept. of CSE Page 63
64 b[l++].exp = i; printf("\nexpression 1 = %.1f",a[0].coeff); //printing first polynomial for(i=1;i<=deg1;i++) printf("+ %.1fx^%d",a[i].coeff,a[i].exp); printf("\nexpression 2 = %.1f",b[0].coeff); //printing second polynomial for(i=1;i<=deg2;i++) printf("+ %.1fx^%d",b[i].coeff,b[i].exp); if(deg1>deg2) //Multiply the polynomials for(i=0;i<=deg2;i++) c[m].coeff = a[i].coeff * b[i].coeff; c[m].exp = a[i].exp; m++; for(i=deg2+1;i<=deg1;i++) c[m].coeff = a[i].coeff; c[m].exp = a[i].exp; m++; else for(i=0;i<=deg1;i++) c[m].coeff = a[i].coeff * b[i].coeff; c[m].exp = a[i].exp; m++; for(i=deg1+1;i<=deg2;i++) c[m].coeff = b[i].coeff; c[m].exp = b[i].exp; m++; printf("expression after multiplication = %.1f",c[0].coeff); //printing the product of the two polynomials for(i=1;i<m;i++) printf("+ %.1fx^%d",c[i].coeff,c[i].exp); output : Enter the highest degree of polynomial1:2 Enter the coeff of x^0 :2 Enter the coeff of x^1 :3 Enter the coeff of x^2 :4 Chethan Raj C, Assistant Professor, Dept. of CSE Page 64
65 Enter the highest degree of polynomial2:3 Enter the coeff of x^0 :5 Enter the coeff of x^1 :6 Enter the coeff of x^2 :7 Enter the coeff of x^3 :2 Expression 1 = x^1+ 4.0x^2 Expression 2 = x^1+ 7.0x^2+ 2.0x^3 Expression after multiplication = x^ x^2+ 2.0x^3 Sparse Matrices. Sparse matrix is a matrix which has more zero elements than nonzero elements i.e less number of nonzero elements. Sparse Matrix Representations: A sparse matrix can be represented by using TWO representations Triplet Representation 2. Linked Representation Triplet Representation In this representation, user consider only non-zero values along with their row and column index values. Each non zero value is a triplet of the form <R,C,Value) where R represents the row in which the value appears, C represents the column in which the value appears and Value represents the nonzero value itself. In this representation, the 0th row stores total rows, total columns and total non-zero values in the matrix. For example, consider a matrix of size 5 X 6 containing 6 number of non-zero values. This matrix can be represented as shown below. In above example matrix, there are only 6 non-zero elements ( those are 9, 8, 4, 2, 5 & 2) and matrix size is 5 X 6. User represent this matrix as shown in the above image. Here the first row in the right side table is filled with values 5, 6 & 6 which indicates that it is a sparse matrix with 5 rows, 6 columns & 6 non-zero values. Second row is filled with 0, 4, & 9 which indicates the value in the matrix at 0th row, 4th column is 9. In the same way the remaining non-zero values also follows the similar pattern.. Linked Representation In linked representation, user use linked list data structure to represent a sparse matrix. In this linked list, user use two different nodes namely header node and element node. Header node consists of three fields and element node consists of five fields as shown below: Consider the above same sparse matrix used in the Triplet representation. This sparse matrix can be represented using linked representation as shown below. In the representation, H0, H1,...,H5 indicates the header nodes which are used to represent indexes. Remaining nodes are used to represent non-zero elements in the matrix, except the very first node which is used to represent abstract information of the sparse matrix (i.e., It is a matrix of 5 X 6 with 6 non-zero elements). Chethan Raj C, Assistant Professor, Dept. of CSE Page 65
66 In this representation, in each row and column, the last node right field points to it's respective header node. Basic operations on Sparse Matrix o Reading a sparse matrix o Displaying a sparse matrix o Searching for a non zero element in a sparse matrix Ex: Program to determine given matrix is a sparse matrix. #include <stdio.h> void main () static int array[10][10]; int i, j, m, n; int counter = 0; printf("enter the order of the matix \n"); scanf("%d %d", &m, &n); printf("enter the co-efficients of the matix \n"); for (i = 0; i < m; ++i) for (j = 0; j < n; ++j) scanf("%d", &array[i][j]); if (array[i][j] == 0) ++counter; Chethan Raj C, Assistant Professor, Dept. of CSE Page 66
67 if (counter > ((m * n) / 2)) printf("the given matrix is sparse matrix \n"); else printf("the given matrix is not a sparse matrix \n"); printf("there are %d number of zeros", counter); Output: $ gcc pgm.c $ a.out 1) Enter the order of the matix 3 3 Enter the co-efficients of the matix The given matrix is not a sparse matrix There are 0 number of zeros $ a.out 2) Enter the order of the matix 3 3 Enter the co-efficients of the matix The given matrix is sparse matrix There are 6 number of zeros Strings: Basic Terminology A string is a collection/sequence of characters, stored in an array followed by null ('\0') character with in an double quotes. Null character represents the end of string. Address of first element is random (depends on Computer), address of next element depend upon the type of array. Here, the type is character and character takes one byte in memory, therefore every next address will increment by one. Index of array will always starts with zero Declaration of String or Character array Declaration of array means creating sequential blocks of memory to hold fixed number of values. Syntax for string declaration: char String-name[size of String ]; Note: Strings can also be declared using pointer. Chethan Raj C, Assistant Professor, Dept. of CSE Page 67
IV Unit Second Part STRUCTURES
STRUCTURES IV Unit Second Part Structure is a very useful derived data type supported in c that allows grouping one or more variables of different data types with a single name. The general syntax of structure
More informationComputer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];
Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data
More informationModule 6: Array in C
1 Table of Content 1. Introduction 2. Basics of array 3. Types of Array 4. Declaring Arrays 5. Initializing an array 6. Processing an array 7. Summary Learning objectives 1. To understand the concept of
More informationExample: Structure, Union. Syntax. of Structure: struct book { char title[100]; char author[50] ]; float price; }; void main( )
Computer Programming and Utilization ( CPU) 110003 Structure, Union 1 What is structure? How to declare a Structure? Explain with Example Structure is a collection of logically related data items of different
More information'C' Programming Language
F.Y. Diploma : Sem. II [DE/EJ/ET/EN/EX] 'C' Programming Language Time: 3 Hrs.] Prelim Question Paper Solution [Marks : 70 Q.1 Attempt any FIVE of the following : [10] Q.1(a) Define pointer. Write syntax
More informationWrite a C program using arrays and structure
03 Arrays and Structutes 3.1 Arrays Declaration and initialization of one dimensional, two dimensional and character arrays, accessing array elements. (10M) 3.2 Declaration and initialization of string
More informationDarshan Institute of Engineering & Technology for Diploma studies Unit 4
Pointer A pointer is a variable that contains address or location of another variable. Pointer is a derived data type in C. Pointers contain memory address as their values, so they can also be used to
More informationStructure, Union. Ashishprajapati29.wordpress.com. 1 What is structure? How to declare a Structure? Explain with Example
Structure, Union 1 What is structure? How to declare a Structure? Explain with Example Structure s a collection of logically related data items of different data types grouped together under a single name.
More informationDarshan Institute of Engineering & Technology for Diploma Studies Unit 5
1 What is structure? How to declare a Structure? Explain with Example Structure is a collection of logically related data items of different data types grouped together under a single name. Structure is
More informationGovernment Polytechnic Muzaffarpur.
Government Polytechnic Muzaffarpur. Name of the Lab: COMPUTER PROGRAMMING LAB (MECH. ENGG. GROUP) Subject Code: 1625408 Experiment: 1 Aim: Programming exercise on executing a C program. If you are looking
More informationSAE1A Programming in C. Unit : I - V
SAE1A Programming in C Unit : I - V Unit I - Overview Character set Identifier Keywords Data Types Variables Constants Operators SAE1A - Programming in C 2 Character set of C Character set is a set of
More informationARRAYS(II Unit Part II)
ARRAYS(II Unit Part II) Array: An array is a collection of two or more adjacent cells of similar type. Each cell in an array is called as array element. Each array should be identified with a meaningful
More informationUnit 1 - Arrays. 1 What is an array? Explain with Example. What are the advantages of using an array?
1 What is an array? Explain with Example. What are the advantages of using an array? An array is a fixed-size sequenced collection of elements of the same data type. An array is derived data type. The
More informationCSE101-Lec#18. Multidimensional Arrays Application of arrays. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming
CSE101-Lec#18 Multidimensional Arrays Application of arrays Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Defining and processing 1D array 2D array Applications of arrays 1-D array A
More informationProcedural programming with C
Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical
More informationDC54 DATA STRUCTURES DEC 2014
Q.2 a. Write a function that computes x^y using Recursion. The property that x^y is simply a product of x and x^(y-1 ). For example, 5^4= 5 * 5^3. The recursive definition of x^y can be represented as
More informationUnit 3 Decision making, Looping and Arrays
Unit 3 Decision making, Looping and Arrays Decision Making During programming, we have a number of situations where we may have to change the order of execution of statements based on certain conditions.
More informationSubject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100
Code: DC-05 Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 NOTE: There are 11 Questions in all. Question 1 is compulsory and carries 16 marks. Answer to Q. 1. must be written in the space
More informationUnit IV & V Previous Papers 1 mark Answers
1 What is pointer to structure? Pointer to structure: Unit IV & V Previous Papers 1 mark Answers The beginning address of a structure can be accessed through the use of the address (&) operator If a variable
More informationLecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)
Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) In this lecture, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of
More informationPESIT Bangalore South Campus Hosur road, 1km before ElectronicCity, Bengaluru -100 Department of Basic Science and Humanities
INTERNAL ASSESSMENT TEST-3 Date : 12-05-2016 Marks: 40 Subject & Code : Programming in C and data structures (15PCD23) Sec : F,G,H,I,J,K Name of faculty :Dr J Surya Prasad/Mr.Sreenath M V/Ms.Monika/ Time
More informationUNIT-V. Structures. The general syntax of structure is given below: Struct <tagname> { datatype membername1; datatype membername2; };
UNIT-V Structures Structure is a very useful derived data type supported in c that allows grouping one or more variables of different data types with a single name. The general syntax of structure is given
More informationMemory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)
Memory Allocation Memory What is memory? Storage for variables, data, code etc. How is memory organized? Text (Code) Data (Constants) BSS (Global and static variables) Text Data BSS Heap Stack (Local variables)
More informationCOMPUTER APPLICATION
Total No. of Printed Pages 16 HS/XII/A.Sc.Com/CAP/14 2 0 1 4 COMPUTER APPLICATION ( Science / Arts / Commerce ) ( Theory ) Full Marks : 70 Time : 3 hours The figures in the margin indicate full marks for
More informationMulti-Dimensional arrays
Multi-Dimensional arrays An array having more then one dimension is known as multi dimensional arrays. Two dimensional array is also an example of multi dimensional array. One can specify as many dimensions
More informationstruct structure_name { //Statements };
Introduction to Structure http://www.studytonight.com/c/structures-in-c.php Structure is a user-defined data type in C which allows you to combine different data types to store a particular type of record.
More informationA. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS
Syllabus: Pointers and Preprocessors: Pointers and address, pointers and functions (call by reference) arguments, pointers and arrays, address arithmetic, character pointer and functions, pointers to pointer,initialization
More informationC Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee
C Language Part 2 (Minor modifications by the instructor) 1 Scope Rules A variable declared inside a function is a local variable Each local variable in a function comes into existence when the function
More informationUNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.
UNIT 2 ARRAYS Arrays Structure Page Nos. 2.0 Introduction 23 2.1 Objectives 24 2.2 Arrays and Pointers 24 2.3 Sparse Matrices 25 2.4 Polynomials 28 2.5 Representation of Arrays 30 2.5.1 Row Major Representation
More informationCSCI 171 Chapter Outlines
Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures
More informationClassification s of Data Structures
Linear Data Structures using Sequential organization Classification s of Data Structures Types of Data Structures Arrays Declaration of arrays type arrayname [ arraysize ]; Ex-double balance[10]; Arrays
More informationITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University
ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 10: Arrays Readings: Chapter 9 Introduction Group of same type of variables that have same
More informationNCS 301 DATA STRUCTURE USING C
NCS 301 DATA STRUCTURE USING C Unit-1 Part-3 Arrays Hammad Mashkoor Lari Assistant Professor Allenhouse Institute of Technology www.ncs301ds.wordpress.com Introduction Array is a contiguous memory of homogeneous
More informationTo declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows
Unti 4: C Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type An array is used to store a collection of data, but it is often more useful
More informationUNIT-I Fundamental Notations
UNIT-I Fundamental Notations Introduction to Data Structure We know that data are simply values or set of values and information is the processed data. And actually the concept of data structure is much
More informationLecture 04 FUNCTIONS AND ARRAYS
Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions
More informationPOINTERS, STRUCTURES AND INTRODUCTION TO DATA STRUCTURES
1 POINTERS, STRUCTURES AND INTRODUCTION TO DATA STRUCTURES 2.1 POINTERS Pointer is a variable that holds the address of another variable. Pointers are used for the indirect manipulation of the variable.
More informationC PROGRAMMING Lecture 4. 1st semester
C PROGRAMMING Lecture 4 1st semester 2017-2018 Structures Structure: Collection of one or more variables a tool for grouping heterogeneous elements together (different types) Array: a tool for grouping
More informationQ 1. Attempt any TEN of the following:
Subject Code: 17212 Model Answer Page No: 1 / 26 Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. 2) The
More informationCS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010
CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please
More informationBinary Representation. Decimal Representation. Hexadecimal Representation. Binary to Hexadecimal
Decimal Representation Binary Representation Can interpret decimal number 4705 as: 4 10 3 + 7 10 2 + 0 10 1 + 5 10 0 The base or radix is 10 Digits 0 9 Place values: 1000 100 10 1 10 3 10 2 10 1 10 0 Write
More informationDecimal Representation
Decimal Representation Can interpret decimal number 4705 as: 4 10 3 + 7 10 2 + 0 10 1 + 5 10 0 The base or radix is 10 Digits 0 9 Place values: 1000 100 10 1 10 3 10 2 10 1 10 0 Write number as 4705 10
More informationPDS Class Test 2. Room Sections No of students
PDS Class Test 2 Date: October 27, 2016 Time: 7pm to 8pm Marks: 20 (Weightage 50%) Room Sections No of students V1 Section 8 (All) Section 9 (AE,AG,BT,CE, CH,CS,CY,EC,EE,EX) V2 Section 9 (Rest, if not
More informationGuide for The C Programming Language Chapter 4
1. What is Structure? Explain the syntax of Structure declaration and initialization with example. A structure is a collection of one or more variables, possibly of different types, grouped together under
More informationMODULE V: POINTERS & PREPROCESSORS
MODULE V: POINTERS & PREPROCESSORS INTRODUCTION As you know, every variable is a memory-location and every memory-location has its address defined which can be accessed using ampersand(&) operator, which
More informationCS201 Spring2009 Solved Sunday, 09 May 2010 14:57 MIDTERM EXAMINATION Spring 2009 CS201- Introduction to Programming Question No: 1 ( Marks: 1 ) - Please choose one The function of cin is To display message
More informationComputer Programming Unit 3
POINTERS INTRODUCTION Pointers are important in c-language. Some tasks are performed more easily with pointers such as dynamic memory allocation, cannot be performed without using pointers. So it s very
More informationIMPORTANT QUESTIONS IN C FOR THE INTERVIEW
IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.
More informationFundamentals of Computer Programming Using C
CHARUTAR VIDYA MANDAL S SEMCOM Vallabh Vidyanagar Faculty Name: Ami D. Trivedi Class: FYBCA Subject: US01CBCA01 (Fundamentals of Computer Programming Using C) *UNIT 3 (Structured Programming, Library Functions
More informationB.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University
Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are
More informationMaltepe University Computer Engineering Department. BİL 133 Algoritma ve Programlama. Chapter 8: Arrays and pointers
Maltepe University Computer Engineering Department BİL 133 Algoritma ve Programlama Chapter 8: Arrays and pointers Basics int * ptr1, * ptr2; int a[10]; ptr1 = &a[2]; ptr2 = a; // equivalent to ptr2 =
More informationAdvanced C Programming and Introduction to Data Structures
FYBCA Semester II (Advanced C Programming and Introduction to Data Structures) Question Bank Multiple Choice Questions Unit-1 1. Which operator is used with a pointer to access the value of the variable
More informationIECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.
Subject code - CCP01 Chapt Chapter 1 INTRODUCTION TO C 1. A group of software developed for certain purpose are referred as ---- a. Program b. Variable c. Software d. Data 2. Software is classified into
More informationUNIT - I. Introduction to C Programming. BY A. Vijay Bharath
UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been
More informationSingle Dimension Arrays
ARRAYS Single Dimension Arrays Array Notion of an array Homogeneous collection of variables of same type. Group of consecutive memory locations. Linear and indexed data structure. To refer to an element,
More informationSubject: Fundamental of Computer Programming 2068
Subject: Fundamental of Computer Programming 2068 1 Write an algorithm and flowchart to determine whether a given integer is odd or even and explain it. Algorithm Step 1: Start Step 2: Read a Step 3: Find
More informationUNIT - V STRUCTURES AND UNIONS
UNIT - V STRUCTURES AND UNIONS STRUCTURE DEFINITION A structure definition creates a format that may be used to declare structure variables. Let us use an example to illustrate the process of structure
More informationAE52/AC52/AT52 C & Data Structures JUNE 2014
Q.2 a. Write a program to add two numbers using a temporary variable. #include #include int main () int num1, num2; clrscr (); printf( \n Enter the first number : ); scanf ( %d, &num1);
More informationArrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)
1 Arrays General Questions 1. What will happen if in a C program you assign a value to an array element whose subscript exceeds the size of array? A. The element will be set to 0. B. The compiler would
More informationUnit 7. Functions. Need of User Defined Functions
Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have
More informationMODULE 3: Arrays, Functions and Strings
MODULE 3: Arrays, Functions and Strings Contents covered in this module I. Using an Array II. Functions in C III. Argument Passing IV. Functions and Program Structure, locations of functions V. Function
More informationArrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur
Arrays CS10001: Programming & Data Structures Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Array Many applications require multiple data items that have common
More informationDEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS 1. Define global declaration? The variables that are used in more
More informationITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University
ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 12: Structures Readings: Chapter 11 Structures (1/2) A structure is a collection of one
More informationFOR Loop. FOR Loop has three parts:initialization,condition,increment. Syntax. for(initialization;condition;increment){ body;
CLASSROOM SESSION Loops in C Loops are used to repeat the execution of statement or blocks There are two types of loops 1.Entry Controlled For and While 2. Exit Controlled Do while FOR Loop FOR Loop has
More informationVariation of Pointers
Variation of Pointers A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before
More informationFundamentals of Programming. Lecture 12: C Structures, Unions, Bit Manipulations and Enumerations
Fundamentals of Programming Lecture 12: C Structures, Unions, Bit Manipulations and Enumerations Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu Sharif University of Technology Computer Engineering Department
More informationCSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011
CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011 Date: 01/18/2011 (Due date: 01/20/2011) Name and ID (print): CHAPTER 6 USER-DEFINED FUNCTIONS I 1. The C++ function pow has parameters.
More informationUNIT III (PART-II) & UNIT IV(PART-I)
UNIT III (PART-II) & UNIT IV(PART-I) Function: it is defined as self contained block of code to perform a task. Functions can be categorized to system-defined functions and user-defined functions. System
More informationArrays a kind of data structure that can store a fixedsize sequential collection of elements of the same type. An array is used to store a collection
Morteza Noferesti Arrays a kind of data structure that can store a fixedsize sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful
More informationb. array s first element address c. base address of an array d. all elements of an array e. both b and c 9. An array elements are always stored in a.
UNIT IV 1. Appropriately comment on the following declaration int a[20]; a. Array declaration b. array initialization c. pointer array declaration d. integer array of size 20 2. Appropriately comment on
More informationModel Viva Questions for Programming in C lab
Model Viva Questions for Programming in C lab Title of the Practical: Assignment to prepare general algorithms and flow chart. Q1: What is a flowchart? A1: A flowchart is a diagram that shows a continuous
More informationQuestions Bank. 14) State any four advantages of using flow-chart
Questions Bank Sub:PIC(22228) Course Code:-EJ-2I ----------------------------------------------------------------------------------------------- Chapter:-1 (Overview of C Programming)(10 Marks) 1) State
More informationCode No: R Set No. 1
Code No: R05010106 Set No. 1 1. (a) Draw a Flowchart for the following The average score for 3 tests has to be greater than 80 for a candidate to qualify for the interview. Representing the conditional
More informationProcedural Programming
Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Procedural Programming Session Five: Arrays Name: First Name: Tutor: Matriculation-Number: Group-Number: Date: Prof. Dr.Ing. Axel Hunger Dipl.-Ing.
More informationPrinciples of C and Memory Management
COMP281 Lecture 9 Principles of C and Memory Management Dr Lei Shi Last Lecture Today Pointer to Array Pointer Arithmetic Pointer with Functions struct Storage classes typedef union String struct struct
More informationProgramming and Data Structure Solved. MCQs- Part 2
Programming and Data Structure Solved MCQs- Part 2 Programming and Data Structure Solved MCQs- Part 2 Unsigned integers occupies Two bytes Four bytes One byte Eight byte A weather forecasting computation
More informationPointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island
Pointers and Structure Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island 1 Pointer Variables Each variable in a C program occupies space in
More information1. INTRODUCTION TO DATA STRUCTURE
1. INTRODUCTION TO DATA STRUCTURE 1.1 What is Data Structure? Data Structure: Data structure is a way to storing and organizing data in a computer so that it can be used efficiently. Data structure is
More informationPointers. Introduction
Pointers Spring Semester 2007 Programming and Data Structure 1 Introduction A pointer is a variable that represents the location (rather than the value) of a data item. They have a number of useful applications.
More informationAn array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.
Data Structures Introduction An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type. Representation of a large number of homogeneous
More informationVariables Data types Variable I/O. C introduction. Variables. Variables 1 / 14
C introduction Variables Variables 1 / 14 Contents Variables Data types Variable I/O Variables 2 / 14 Usage Declaration: t y p e i d e n t i f i e r ; Assignment: i d e n t i f i e r = v a l u e ; Definition
More informationHow to declare an array in C?
Introduction An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type. Representation of a large number of homogeneous values.
More informationUNIT-IV. Structure is a user-defined data type in C language which allows us to combine data of different types together.
UNIT-IV Unit 4 Command Argument line They are parameters/arguments supplied to the program when it is invoked. They are used to control program from outside instead of hard coding those values inside the
More informationUNIT-1. Chapter 1(Introduction and overview) 1. Asymptotic Notations 2. One Dimensional array 3. Multi Dimensional array 4. Pointer arrays.
UNIT-1 Chapter 1(Introduction and overview) 1. Asymptotic Notations 2. One Dimensional array 3. Multi Dimensional array 4. Pointer arrays. Chapter 2 (Linked lists) 1. Definition 2. Single linked list 3.
More informationINDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Stamp / Signature of the Invigilator
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Stamp / Signature of the Invigilator EXAMINATION ( End Semester ) SEMESTER ( Spring ) Roll Number Section Name Subject Number C S 1 0 0 0 1 Subject Name Programming
More informationChapter 3: Arrays and More C Functionality
Chapter 3: Arrays and More C Functionality Objectives: (a) Describe how an array is stored in memory. (b) Define a string, and describe how strings are stored. (c) Describe the implications of reading
More informationIntroduction to Scientific Computing and Problem Solving
Introduction to Scientific Computing and Problem Solving Lecture #22 Pointers CS4 - Introduction to Scientific Computing and Problem Solving 2010-22.0 Announcements HW8 due tomorrow at 2:30pm What s left:
More informationONE DIMENSIONAL ARRAYS
LECTURE 14 ONE DIMENSIONAL ARRAYS Array : An array is a fixed sized sequenced collection of related data items of same data type. In its simplest form an array can be used to represent a list of numbers
More informationBasics of Programming
Unit 2 Basics of Programming Problem Analysis When we are going to develop any solution to the problem, we must fully understand the nature of the problem and what we want the program to do. Without the
More informationSRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY, VIRUDHUNAGAR Department of CSE & IT Internal Test I
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY, VIRUDHUNAGAR Department of CSE & IT Internal Test I Year & Sem: I B.E (CSE) & II Date of Exam: 21/02/2015 Subject Code & Name: CS6202 & Programming & Data
More informationGabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming
1 2 3 CMPE 013/L and Strings Gabriel Hugh Elkaim Spring 2013 4 Definition are variables that can store many items of the same type. The individual items known as elements, are stored sequentially and are
More informationQuestion Bank (SPA SEM II)
Question Bank (SPA SEM II) 1. Storage classes in C (Refer notes Page No 52) 2. Difference between function declaration and function definition (This question is solved in the note book). But solution is
More informationF.Y. Diploma : Sem. II [CO/CD/CM/CW/IF] Programming in C
F.Y. Diploma : Sem. II [CO/CD/CM/CW/IF] Programming in C Time : 3 Hrs.] Prelim Question Paper Solution [Marks : 70 Q.1 Attempt any FIVE of the following : [10] Q.1 (a) List any four relational operators.
More informationData Types and Variables in C language
Data Types and Variables in C language Basic structure of C programming To write a C program, we first create functions and then put them together. A C program may contain one or more sections. They are
More informationNCS 301 DATA STRUCTURE USING C
NCS 301 Data Structure Using C NCS 301 DATA STRUCTURE USING C Unit-1 Part-1 Intro to Data Structures Hammad Mashkoor Lari Assistant Professor Allenhouse Institute of Technolgy www.ncs301ds.wordpress.com
More informationPointers and Arrays A QUICK PREVIEW OF FOR CHAPTERS 10 AND 11 CMPE13. Cyrus Bazeghi
Pointers and Arrays A QUICK PREVIEW OF FOR CHAPTERS 10 AND 11 Cyrus Bazeghi POINTERS AND ARRAYS We have briefly seen these before, here are the details Pointer Array Address of a variable in memory Allows
More informationComputer Science & Engineering 150A Problem Solving Using Computers
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 06 - Stephen Scott Adapted from Christopher M. Bourke 1 / 30 Fall 2009 Chapter 8 8.1 Declaring and 8.2 Array Subscripts 8.3 Using
More informationData Structure & Algorithms Laboratory Manual (CS 392)
Institute of Engineering & Management Department of Computer Science & Engineering Data Structure Laboratory for 2 nd year 3 rd semester Code: CS 392 Data Structure & Algorithms Laboratory Manual (CS 392)
More informationContents ARRAYS. Introduction:
UNIT-III ARRAYS AND STRINGS Contents Single and Multidimensional Arrays: Array Declaration and Initialization of arrays Arrays as function arguments. Strings: Initialization and String handling functions.
More information