UNIT-I Fundamental Notations

Size: px
Start display at page:

Download "UNIT-I Fundamental Notations"

Transcription

1 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 broader than the data type. A data structure is an arrangement of data in a computer's memory or even disk storage. Actually it s an agreement about: how to store and represent a set of elements in memory, what operations we can perform on that data, the algorithms for those operations, and how time and space efficient those algorithms are. Therefore a data structure is defined as a specific way of arranging data and a set of operations performed on the data that make it behave in a certain way. In other words you can say that a data structure is a logical way of organizing information so that we can find, update, add, and delete portions of it efficiently. Data Structure a specific way of organizing and storing information, so that it can be accessed and worked with in appropriate ways For designing any data structure there are three different levels that must be followed by the programmer: Abstract (logical) level : Initially the programmer has to decide how the elements ( data items) are related to each other and what operations are needed. Therefore it is necessary to first understand the problem very carefully. For example, you must have clear idea to which one is used either a contiguous list or a linked list when you deal with a number of data because some operations are easier for contiguous lists and other for linked lists. Implementation level: On the implementation level, the data structure is represented in computer memory and its various operations are defined. It means that at implementation level we convert our algorithm into a computer program after deciding which one is the better way to implement it. Suppose you want to create a memory space for 100 numbers then it is the programmer who decides whether to allocate memory space either by using static memory allocation or dynamic memory allocation. Application Level : On this level the data structure is used practically. For example, stack is used to convert the postfix expression into infix expression and a queue is used to hold the processes that are waiting for different resources of the computer system in a multiprogramming operating system. Data Structure Types Generally there are two types of data structures: Primitive (Built in) Data Structures Non-Primitive (User defined) Data Structures

2 1.1Problem Solving Concepts A computer is not intelligent. It cannot analyze a problem and come up with a solution. A human (the programmer) must analyze the problem carefully, develop the instructions for solving the problem, and then have the computer carry out the instructions. To write a program for a computer to follow, one must go through a two phase s process: problem solving phase and an implementation phase. Top-down and Bottom up Design If a problem is simple then it can be handled easily. However if the problem is large and complex then it is not an easy task to handle it directly. The modularization approach involves breaking a problem into a set of sub-problems, followed by breaking each sub-problem into a set of tasks, then breaking each task into a set of actions. Top down design a technique in which a large problem is broken up into a set of sub-problems, followed by breaking each sub-problem into a set of tasks, then breaking each task into a set of actions. Let us understand this concept by considering following three problems: Problem 1 - Add 100 and 35 Solution 1 Easy, no further refinement is required. Problem 2 - Turn on a light bulb Solution 2 - Sub-problem 1: locate bulb switch (one task, one action) Sub-problem 2: depress switch Problem 3 - Given a list of students test scores, find the highest and lowest score and the average score. Solution 3 - Sub-problem 1: read students scores Sub-problem 2: find highest score Sub-problem 3: find lowest score Here Problem 1 can be considered as one action and therefore needs no further refinement. Problems 2 and 3 however can be further divided into a group of actions. This breaking up of a large problem into smaller ones, as shown in figure 1.2, is called top down technique. Large and Complex Problem SubProblem SubProblem SubProblem SubSubProblem SubSubProblem

3 Figure 1.2 Top Down Approach Each subproblem can be easily solved independently of the others. These subproblems are also called as modules. That s why the top-down approach is also called as modular programming. Advantages of Top-Down Design Method 1. It is easier to solve a smaller and less complicated problem than a large and complex problem. 2. It is easier to test smaller module, rather than the entire program solution at once 3. It is often possible to simplify the logical steps of each sub-problem, so that when taken as a whole, the entire solution has less complex logic and hence easier to develop. 4. A simplified solution takes less time to develop and will be more readable. 5. The program will be easier to maintain. Another interesting approach is bottom-up approach. This approach works inversely of topdown. In bottom-up approach the idea is that we start out with a set of fixed small elements and a way of combining those elements into new large elements. Bottom up design a technique in which smaller tasks are collected and combined to solve a big task Experience suggests that the top-down approach should be followed when creating a program. Structured Programming Structured programming is an organized programming approach that assist the programmer in writing effective and error free programs. It has four basic control structures: 1. Sequential 2. Conditional (if-else) 3. Repetition (iteration, looping) 4. Procedures (modules). The sequential structure is composed of statements executed one after another. In this all the statements are executed in the order in which they are written. The conditional structure (also know as selection structure) executes different set of statements depending upon certain condition. The repetitive structures repeat a set of statements while certain conditions are met. The procedure enables us to replace a set of statements with a single statement. Figure 1.3 shows these basic structures of programming languages. Structured Programming a technique which helps a programmer to write an efficient, error free, easy to understand and modify programs 1.2 Concept of Data types, Constants and Variables Computers manipulate data. When you write a program for a computer, it is necessary to specify the properties of the data and the operations that can be applied to it. Data comes in

4 many different forms: letters, words, integer numbers, real numbers, and so on. Each kind of data in the computer is said to have a specific data type. In this section we will study various data types, variables and constants available in C language Data Type A data type is a term, which is used to refer the kinds of data that variables may hold in a programming language. In other words the general form of a class of data items is known as data type. The data type determines how the data are represented in memory and set of operations that are performed on this data. Data Type the general form of a class of data items that specifies how data is represented in the computer and the set of operations that can be applied to it Data can be either primary (basic) data type or secondary (user-defined) data type. Primary data type The data types that are built into a programming language are called primary data type. Primary data types are also known as basic or primitive data types. Primary Data Types the data types which are provided by a computer language automatically The C language provides four basic data types: char a character in the C character set int an integer (a whole number that has no fractional part) float a single precision floating point number (a number with a decimal point) double a double precision floating point number Difference between float and double The float and double data types differ in the precision, means the number of significant digits after the decimal point. Table-1.1 shows the size of all the basic data types. Data Type Size in bits Range char to +127 int 16-32,768 to 32,767 long int 32-2,147,483,648 to +2,147,483,647 float E-38 to +3.4E+38 double E-308 to +1.7E+308 long double E-4932 to +1.1E+4932 Table 1.1 Basic Data Types

5 Secondary data type The data types, which are composed of primary data types, are called as secondary data type. Normally these are defined by the programmer that s why these are sometimes called user defined data types. Secondary Data Types the data types which are defined by the user for its own use In C secondary data types are arrays, structures, pointers, unions, enum etc Constants A constant is a number, character, or string literal that can not be changed during the execution of a program. You can not modify the value of a constant once it is defined. Constants entities that do not change during the execution of a program C provides four types of constants - Integer constants, Real (floating point) constants, Character constants and String constants Integer Constants An integer constant is a sequence of digits (0 to 9), but without a decimal point. No white space characters are used to separate the digits of an integer constant. Followings are the valid integer constants: Followings are the invalid integer constants: /* no space between digit 2 and 3 */ 1_45 /* no hyphen */ /* no decimal point */ Floating Point Constants A floating-point constant comes into two forms: (i) Decimal form In decimal form it consists of at least one digit along with a decimal point. Like integer constant, no white space characters are allowed to separate digits in floating point constants. Here are some valid decimal floating-point numbers: (ii) Exponential form Floating point constants can also be written without the decimal point by using the exponent. The exponent consists of exponent symbol (E or e) followed by a simple constant integer value, which may be either positive or negative. Here are some valid exponential floating-point numbers: e1-3.2e-5 567e e+12

6 Character Constants A character constant is formed by enclosing a single alphanumeric character or any special character within single quotation ( ). Within single quotes escape sequences must be treated as a single character and is therefore valid in a character constant. Here are some valid character constants: a + $ And remember that the maximum length of a character constant should be 1. Following are some invalid character constants: Are 12 Sacrifice 34 String Constants A string constant is a sequence of zero or set of characters surrounded by double quotation marks ( ). The characters may consist of letters, numbers, escape sequences and spaces. Following are the valid string constants: Sachin Tendulkar You are in string constant Enter any positive number Variables A variable is a data type that may vary during the execution of a program. Variables entities that may change during the execution of a program Like constants, we have variables of four basic data types int (integer), char (character), float and double. A variable name must begin with a letter or an underscore (_), which may be followed by a sequence of letters or digits or an underscore (_). All the variables must be declared before their use. In C, it is necessary declare a variable before using it. The syntax of declaring a variable in C language is as: datatype list_of_variables; ; Here the list_of_variables are the name of variables, which are separated by comma. Consider the following declaration statements: int length ; float radius ; char ch ; The first statement declares an integer variable length, second statement declares a float variable radius and last statement declares a character variable ch. Values can be assigned to variables in two ways at the time of declaration and anywhere in the program after the declaration and before use. For example, the following statement int n = 10;

7 assigns a value 10 to integer variable n at the time of declaration. Similarly the following statements: int n; n = 10; assigns the value 10 to n after its declaration. 1.3 Concept of Pointer Variables In C language, the pointers are used to refer the memory location of variables. Every variable starts at a particular address and that address is called as address of that variable. This address can be obtained by pointer variable. Pointer an address of a data item When we declare a variable as: int num = 10; Three things happen: (i) (ii) (iii) compiler reserves space in memory for an integer value a name is associated with the memory location, which is num in this case and a value 10 is stored at this memory location Location name num Location contents Memory address In figure : is a memory address which is reserved by the C compiler to hold an integer value, num is the name associated with this address and 10 is the value stored at

8 address This memory address is not a number to be depend upon, because some other time the computer may choose a different location for storing the value 10. C provides the facility of availing the address of any primary data type by using pointer variable. Pointer Variables A pointer variable is defined as the variable that holds an address of a variable or a function. A pointer variable is declared as: datatype *pointername; Here pointername is the name of a pointer variable and datatype is any valid C data type (either primary data type or secondary data type). Here the asterisk (*) operator in the declaration statement indicates that the value of the pointer variable will be an address of variable of that type rather than value of that type. Pointer variable a variable that contains an address of variable For example, the declarations: int *iptr; float *fptr; char *cptr; declares three pointer variables iptr, fptr and cptr. Here iptr is a pointer to an integer, fptr is a pointer to a float and cptr is a pointer to a character. Here the type of iptr is not simply a pointer but pointer to an integer. Like ordinary variables, multiple pointers can also be declared in one line as: int *iptr1, *iptr2, *iptr3; To obtain a variable s address, the address of & operator is used. This operator applies only to objects in memory such as variables, structures, and array elements. It cannot be applied to

9 expressions or constants. While using pointers, one must remember that all pointers should be suitably initialized with a specific (meaningful) address in the program prior to their use. Consider the following statements: int num; int *iptr = &num; Here the last statement assigns a meaningful value (address of variable num , in this case) to iptr. Dereferencing Pointers Dereferencing is an operation performed to access and manipulates the data contained in memory location. The operator * is used to dereference pointers. The dereference operator is applied as a prefix to a pointer variable. When * is applied to a pointer (say address), it accesses the object the pointer points to. Thus the notation *iptr in a statement refers to the integer at the location referenced by the pointer iptr. Thus the following statement: printf( %d, *iptr); displays the value stored at address (since the value of iptr is 64428). Let us see a simple program that illustrates this concept. #include <stdio.h> void main() int num=10; int *iptr; iptr = &num; printf( \nvalue = %d \t Address =, num, &num);

10 printf( \nvalue = %d \t Address =, *iptr, iptr); The output of this program is as. Value = 10 Address = Value = 10 Address = Note that while dereferencing a pointer variable, one must never apply the indirection operator to it until it points to a valid object. Also each data type in C has its own associated pointer type. It means that an integer pointer can hold an address of an integer variable; a float pointer can hold an address of a float variable and so on. There is an exception to this rule, except void pointer. Very Short Question Answers Q.1 What is Computer program? Ans. The logical sequence of steps followed by a computer is known as a computer program. Q.2 What is an algorithm? Ans. An algorithm is a finite sequence of steps, when followed, performs a well defined task. Q.3 What is problem definition phase? Ans. The phase in which the problem is defined carefully and a general solution (algorithm) is developed and tested is called as problem definition phase. Q.4 What do you mean by code implementation? Ans. Translation of an algorithm into a programming language, such as C, Pascal, is called as code implementation. Q.5 What is bottom-up methodology? Ans. Bottom-up approach chooses to solve different parts of the problem directly in his programming language and then combine these pieces into a complete program. Q.6 What is program testing? Ans. Program testing is the process of running the program on sample data chosen to find errors, if they are present. Q.7 What do you mean by debugging? Ans. Program debugging is the process of isolating and correcting the errors. If a program has some errors then it is necessary to determine exactly where the errors are. Q.8 What is documentation?

11 Ans. Documentation is the written text and comments that makes a program easier for others to understand, use and modify. Q.9 Define data type. Ans. A data type is a term, which is used to refer the kinds of data that variables may hold in a programming language. In other words the general form of a class of data items is known as data type. Q.10 Define variable and constant. Ans. A variable is an entity that might change during the execution of a program. On the other hand, a constant is an entity that do not change during the execution of a program. UNIT-II Arrays In computer programming, an array is one of the simplest data structures. An array is a collection of similar data elements which are stored contiguously in memory locations, usually of the same size and data type. Individual elements are accessed by their position in the array. The position is given by an index, which is also called a subscript. The index usually uses a consecutive range of integers, such as 1,2,3 etc. In this chapter, we work with onedimensional arrays and two-dimensional arrays. 2.1 Concept of Arrays A general variable is used to store one value only at a time. But what will you do if somebody tells you to store 100 integer values or 100 real values or 100 characters? The obvious solution to such problem is arrays. Arrays are useful when the numbers of elements are fixed. An array is a finite set of similar elements stored in adjacent memory locations. Arrays provide a way to store a large number of variables of same type under the same name. Each variable, called an element, in an array must have the same data type, and they are distinguished from each other by an array index. Array a set of similar data items which are stored in contiguous memory locations Figure 2.1 show the representation of an array ] Figure 2.1 An array of 10 integers An array containing n number of elements is referenced using an index that varies from 0 to n- 1. For example, the elements of an array num[n] containing n elements are denoted by num[0], num[1], num[2],., num[n-1], where 0 is the lower bound and n-1 is the upper bound. An array is further categorized as: 1. One-dimensional array

12 2. Multi-dimensional array A multi-dimensional array can be a 2-D array, 3-D array, 4-D array, etc. Following examples show this: num[5] num[4][5] a 1-D array of holding 10 elements a 2-D array with 4 rows and 5 columns holding 20 (4x5) elements num[3][4][5] a 3-D array with three 2-D arrays each of which is having 4 rows and 5 columns, thus holding total 60 (3x4x5) elements Single Dimensional Array A single-dimensional array is a collection of similar data items whose individual item can be accessed by using an index that indicates the position of the item within the collection. The syntax of defining a single-dimensional array is as: datatype arrayname [size ]; For example, if we want to store 100 integer values then its array declaration will be as: int a [100] ; Here a is an array of 100 integer elements. The individual element of an array a is accessed with the help of a subscript (index). Here the elements of a array are denoted by a[0], a[1], a[2], a[3],., a[99]. The number k in a[k] is called a subscript and a[k] is called a subscripted variable. In C language, the subscript starts from 0. Subscript a notation (variable) used in array to access an individual element The above things are represented as: a[0] a[1] a[2] a[3] a[97] a[98] a[99] If we want to access say 40th location in array a [ ], then we will use following notation item = a [39] ; And if we want to store an integer 28 at 60 th location then we will assign it as:

13 a [59] = 28; Reading data items into Array We place data items into an array of size using for loop as: for (i = 0; i < size ; i++ ) scanf ( %d, &a[i]); The first data item in array a [ ] is placed into location &a [0], that s why i has 0 initial value and this process will be repeated until i reaches (size 1). Displaying data items of an Array In the same fashion if we want to display the data items of array a[ ], we will use the following for loop: for (i = 0; i < size ; i++ ) printf ( %d, a[i]); Initializing a Single-dimensional Arrays Single dimensional arrays are initialized when they are declared. For example, int a[10] = 12, 26, 83, 54, 15, 96, 47, 18, 39, 20; Here 12 is assigned to a[0], 26 is assigned to a[1], 83 is assigned to a[2] and so on. Here one should remember that when a single dimensional array is initialized then it is optional to mention the size of the array, as follows: int a[ ] = 12, 26, 83, 54, 15, 96, 47, 18, 39, 20; Declaring array size is optional Memory representation of Single Dimensional Array

14 As studied earlier, elements of a single dimensional array are stored contiguously in memory. For example, int a[10] = 12, 26, 83, 54, 15, 96, 47, 18, 39, 20; This array is represented in memory as: Value Addr Figure 2.2 Memory Representation of Single Dimensional Array The starting address of the very first data item in an array is called as base address of the array. If we have n number of data items in an array along with its base address, then we can easily find out the address of any data item. In single-dimensional array, the address of any data item, say A[I], can be calculated as: Address of A[I] = BaseAddress + w * (I LB) Here BaseAddress is the address of very first element, w is the size of data item in bytes (2 for integer, 4 for float, 1 for character) and LB is the lower bound of the array (in C language the value of LB is always 0) Two Dimensional Arrays Two-dimensional arrays are useful for representing games like chess, tic-tac-toe, or Scrabble. The two-dimensional array is declared as: datatype arrayname [rows] [columns] here rows and columns represent total number of rows and columns respectively in a twodimensional array named arrayname and datatype is the type of the element that arrayname contains. Two dimensional Arrays a set of similar data items which are stored in contiguous memory locations and each element is accessed by two subscripts one for the row and another for the column

15 For example, if you want to declare an array of int that has 4 numbers of rows and 6 numbers of columns then it is declared as: int a[4][6]; Accessing Two-dimensional Array Elements An element in a two-dimensional array is accessed by specifying the respective row and column numbers in it. Thus each element is accessed by a pair of subscripts which represent the element s position within each dimension. Each subscript has its own set of braces. Let you want to refer an element which is at i th position in a row and j th position in a column of array a then we use the notation - a[i][j]. For example a[2][4] would refer to the integer value in the third row and the fifth column. Reading and Writing Two-dimensional Arrays We can enter data into an using a nested for loop as: for(int i=0; i<4; i++) for(intj=0; j<j; j++) scanf( %d, &a[i][j]); Similarly we can read back data from a two-dimensional array by using a nested for loop as: for(int i=0; i<4; i++) for(intj=0; j<j; j++) printf( %d, a[i][j]); Initializing a Two-dimensional Arrays

16 Like single dimensional arrays, we can also initialize a two-dimensional array as: int a[4][4] = 4, 5, 7, 9, 2, 6, 2, 1, 6, 1, 3, 5, 2, 8, 9, 3 ; If any of the inner initializers list have fewer initializers than defined in array dimensions then the remaining elements are initialized to zero. 2.2 Storage Representation of Two Dimensional Array Basically there are two types of representation of two-dimensional array: (a) Row major order (b) Column major order Row major order In this the elements of two-dimensional array are stored row by row, that is first row of twodimensional array is stored first, then second, third, fourth. And so on. Row major order is used most notably by statically-declared arrays in C. Figure shows the row major order of (3 * 4) matrix th Row 1 st Row 2 nd Row Figure- Row Major Order Representation

17 In general for an array A[M, N], the address of element A[I, J] is: A[ I,J ] ( Address of [I, J] ) = Base address + w ( I x N + J) Here Base address = base address of a two dimensional array w = size of element in bytes ( 1 char, 2 int, 4 float) N = total number of columns Let us take an example of address calculation. If we have an array A [4][5] Of real numbers having its base address and we want to find out the address of A [2][1]. In this example Base address = Size = 4 N = 5 I = 2 J = 1 Address of A [2][1] = (2x5+1) = (11) = Column major order In this the elements of two-dimensional array are stored column by column, that is first column of two-dimensional array is stored first, then second, third, fourth. And so on. Row major order is used most notably in FORTRAN. Figure shows the row major order of (3 * 4) matrix.

18 th Col 1 st Col 2 nd Col 3 rd Col Figure-2. Column Major Order Representation The basic formula for calculating the address of element A[I, J] in an array of (M x N) elements in column order as : A[ I,J ] ( Address of [I, J] ) = Base address + w ( J x M + I) Where Base address = base address of a two dimensional array w = size of element in bytes ( 1 char, 2 for int, 4 float) M = total number of columns Let us take an example of address calculation. If we have an array A [4][5] Of real numbers having its base address and we want to find out the address of A [2][1]. In this example Base address = Size = 4 M = 4 I = 2 J = 1 Address of A [2][1] = (4x2+1) = (9) = 64116

19 2.3 Operation on Single Dimensional Arrays There are several operations that are performed on single dimensional arrays. Some main operations are: 1. Traversing 2. Inserting 3. Deleting 4. Searching where as other major operations, such as: 1. Sorting 2. Merging are discussed in chapter-6. Now let us look at main operations that are performed on single dimensional array Traversing One Dimensional Array Traversing refers to processing of each and every element of array exactly once and to apply some processing on that element. Here is the traversing algorithm. Algorithm : Traverse Traverse (A, Start, Final) 1. Set I = Start 2. Repeat through Step-4 while (I< Final) 3. Process element A[I] 4. Increment the value of I as I = I+1 5. Exit The traversing algorithm is implemented as: Implementation : Traverse Traverse (int a[], int start, int final) int i; for (i = start; i < final; i++) printf ( \n %d, a[i]) ; /* displaying array elements on screen */

20 2.3.2 Searching into One Dimensional Array In this an element is searched from a set of numbers. It is started from initial (starting) value to the final value. If item is found at any location then there is no need to go further in the array. If item is not found at any location then it displays the message Item not found. This searching technique is called as linear searching technique. Here is the searching algorithm: Algorithm : Search Search (A, N, Item) Here A is an array of N number of elements and Item be the data item to be searched 1. Initialize Flag = 0 2. Initialize I = 0 3. Repeat through Step-6 while (I< N) 4. If Item = A[I] then go to Step 5; otherwise go to Step 6 5. Set Flag = 1 and go to Step-7 6. Increment the value of I as I = I+1 7. If Flag = 1 then display the message Item found ; Otherwise display the message Item not found 8. Exit The searching algorithm is implemented is as: Implementation : Search Search (int a [], int n, int item) int flag = 0, i ; for (i = 0 ; i <= n-1; i++ ) if (item == a[i] ) flag = 1; break; if (flag == 1 ) printf ( Item %d found, item) ; else printf ( Item %d not found, item) ;

21 By inserting we mean addition of a new element into an array at any specific location. Let we have an array of 10 elements as shown in figure and we want to insert a new element 22 at 6 th location then we have to move each elements of the array from position 6 to 9 to one position down New element In other words a[9] is shifted to a[10], a[8] is shifted to a[9], a[7] is shifted to a[8] and in last a[6] is shifted to a[7]. After this we will insert the new element as a [6] = 22; After insertion the size of array is also increased by one. Here is the insertion algorithm. Algorithm : Insertion Insertion (A, M, N, Pos, Item) Here A is an array of size N, M is number of elements present in an array. Item is the data item to be inserted at position Pos. Perform the following steps if the array is not full i.e. M <> N: 1. Initialize J = M 2. If Pos >= J then insert the element at the end of the array as A[J] = Item; and go to Step-8 Otherwise go to Step-4 3. Insert the item at proper position 4. Repeat through Step-6 while (J >= Pos ) 5. Update A[J] as A[J] = A[J-1] ; 6. Decrement the value of temp as J = J - 1; 7. Insert the Item at Pos-1 as: A[Pos-1] = item; 8. Increment the value of M as M = M+1 9. Exit

22 The insertion algorithm is implemented as: Implementation : Insertion Insertion(int a [], int *m, int n, int pos, int item) /* Here m is passed by reference as its value changes after the insertion of new element */ int j; if (pos >0 && pos <n) if (*m == n) printf("\narray full. Item can not be inserted."); getch(); return; else j = *m; if (pos >= j) a[j] = item; printf("\nitem is inserted at the end.") ; else while (j >= pos ) a [j] = a[j-1] ; j--; a[pos-1] = item; printf ("\nitem is inserted successfully."); (*m)++; else printf("\nyou have entered wrong position. "); printf("\nplease enter correct dimension."); Deletion of an element is very simple, if it is deleted at end. But if an element is deleted in the mid or any specific location, say i th location, then we have to shift some elements upwards. Let we have an array of 10 elements as shown in figure 2.3. Now if we want to delete an element of

23 6 th location then we have to move each elements of the array from position 6 to 9 to one position upward. In other words a[9] is shifted to a[8], a[8] is shifted to a[7], and in last a[7] is shifted to a [6]. After deletion, the size of array is decreased by one Deleted Item Here is the deletion algorithm. Algorithm : Deletion Deletion (A, M, Pos) Here A is an array, M is number of elements present in an array and Pos is the location of data item to be deleted. 1. Initialize Flag = 0 2. If Pos >= M then go to Step-3; Otherwise go to Step Update Flag = 1 4. Set J = Pos-1 5. Access the Item stored at J as Item = A[J] 6. Repeat through Step-8 while (J < M ) 7. Set A[J] = A[J+1] ; 8. Increment the value of J - J = J+1; 9. Decrement the value of M M = M If Flag = 1 then display the message Item deleted successfully Otherwise display the message Item not deleted successfully 11. Exit The deletion algorithm is implemented as: Implementation : Deletion Deletion (int a[ ], int *m, int pos)

24 /* Here m is passed by reference as its value changes after the deletion of element */ int j, item, flag =0; if (pos < *m) flag = 1; j = pos-1; item= a [j]; while (j < *m) a [j] = a[j+1] ; j++; (*m)- - ; if (flag == 1) printf ( \ndeleted item = %d, item); else printf ( \nitem can not be deleted ); Note that the first statement of display () function display (int arr[], int n); Here int arr[] and int *iptr are treated as same when they are using as formal parameters in the definition of a function.

25 Very Short Question Answers Q.1 What do you mean by an array? Ans. An array is collection of similar elements which are stored contiguously in memory locations. Q.2 Write down the types of arrays. Ans. Arrays are of two types single dimensional arrays and multi-dimensional arrays. Q.3 How do you declare a single dimensional array? Ans. A single dimensional array is declared as: datatype arrayname[size]; Here datatype describes the data type of array elements, arrayname is the name associated with the set of values and size is a positive integer constant which instructs the C compiler that how many spaces should be reserved. Q.4 If you have an array A of 50 float (real) elements having its base address 64820, then what will be the address of A [8]? Ans. Address of A[8] = (8 * 4) = Q.5 List various operations associated with single-dimensional array. Ans. Various operations performed on single-dimensional array are insertion, deletion, traversing, searching and sorting. Q.7 How two-dimensional arrays are stored in memory? Ans. There are two types of storage allocation for two-dimensional array: (a) Row major order (b) Column major order

26 UNIT-III Linked lists 3.1 Introduction to linked list Linked list is a very common data structure often used to similar data in memory. In a linked list elements are stored anywhere in memory. The order of the elements of a linked list is maintained by explicit links between them. The linked list is a collection of elements, called nodes, where a node contains two pieces of information an element of the list (Data) and a Link. Linked List a collection of element, called as nodes, in which each element contains a pointer or index to the "next" element, along with the data represented by the element Figure-3.1 shows a linked list of an ordered sequence of nodes with links being represented by arrows. data link data link data link data link NULL Figure-3.1 Linked List of 4 nodes A link is a pointer or an address that indicates the location of next node in the linked list. The link field of last node contains a special value, known as NULL that indicates that this is the last node of the list. The entire list is accessed from an external pointer, say first, that points (contains the address of) the first node in the list, as shown in figure 3.2 (a). It is important to note that first is not a node, rather the address of the first node of the list. first data link data link data link data link NULL (a) Singly Linked List left data right left data right left data right left data right first NULL NULL (b) Doubly Linked List Figure-3.2 Types of Linked Lists The linked list, as shown in figure 3.2(a) is known as singly linked list, because traversing is possible in single direction only. The limitation of such a single linked list is that if we are at a node number 6 then we cannot reach at node number 3. This limitation is overcome by doubly linked list.

27 In a double linked list, each node contains two pointers one to its predecessor and another to its successor. Each node of a doubly linked list contains three pieces of information Data field, that contains the information of the node, and Right and Left fields that contains pointers to the successor and predecessor nodes respectively, as shown in figure 3.2(b). Doubly Linked List a special type of linked list in which each element contains two pointers, one to the previous element and one to the next element, along with the data represented by the element Notations Used in Algorithms Let us study some notations for use in algorithms (but not in C programs). For Singly Linked List Let P is a pointer to a node then NODE(P) - refers to the node pointed to by P, Data(P) - refers to the data (information) field of node P, and Link(P) - refers to the node next to node P For Doubly Linked List Let P is a pointer to a node then NODE(P) - refers to the node pointed to by P, Data(P) - refers to the data (information) field of node P, and Left(P) - refers to the predecessor (Left) node of node P Right(P) - refers to the successor (right) node of node P 3.2 Representation of Linked Lists in Memory A linked list can be represented in memory in two ways - using arrays and using dynamic variables (Pointers) Implementation of Linked Lists Using Array A linked list is defined as a collection of nodes that can be traversed starting at the first node. A linked list is a collection of similar nodes; therefore it can be naturally implemented with the help of an array. Since array is a static data structure and it requires a contiguous memory locations for its elements and linked lists are very useful in situations where the program needs to manage memory very carefully and a contiguous block of memory is not needed. Therefore array representation of linked list is not a good choice. To overcome this limitation, we use dynamic nodes, rather than static nodes. A dynamic node is created when needed and destroyed when it is no longer needed. The main advantage of using dynamic nodes is that there is no need to mention the predefined limits on the number of nodes in the list. As long as memory space is available, we can create a dynamic node any time. Now let us see how a linked list is implemented using dynamic variables.

28 3.3.2 Implementation of Linked Lists Using Dynamic Variables (Pointers) The second way for implementing a linked list in memory is to use a structure (node) which is called as self-referential structure. Nodes are created dynamically, when needed, using malloc() function and destroyed using free(), when no longer needed. The link field of the last node contains sentinel value, define as NULL in C. Comparison between Linked List and Array The following table shows the comparison between linked list and arrays. S.No. Linked List Array 1 Linked list is dynamic in Array is static in nature nature 2 Linked list elements can be stored anywhere in memory Array elements are always stored in contiguous memory locations 3 Insertion and deletion of Insertion and deletion of elements are simple elements are difficult Let us study the representation and implementation of various types of linked lists using dynamic variables and how various operations are implemented on them. 3.4 Linear Linked Lists A linear linked list, also called singly linked list or one-way list, is defined as a collection of elements, called nodes. Each node has two fields - information field (data field) and address of next node (link). Such a node can be declared in C using self-referential structure. Self Referential Structure a structure whose one member is a pointer that points to the structure itself A typical node of a linear linked list is declared as: struct node int data; struct node *link; ; Here the member - struct node *link points to the structure itself and it is represented as: Data Node Link To maintain a linear linked list we use a pointer variable first, also known as an external pointer variable. The first pointer contains an address of first node in the list. Here the name first is just an user-defined identifier. You can also use other names, such as start, or head etc. if the

29 list is empty then the value of this external pointer variable must contain a NULL value. Figure- 3.3 represents a linear linked list of 4 nodes. first data link data link data link data link NULL Figure 3.3 A simple linked list of 4 nodes The link field of last contains a NULL value to indicate that this is the last node of the list. Let us see how this list is created. Since this list has four nodes, therefore firstly we create four dynamic nodes as: node1 = (struct node *) malloc (sizeof(struct node)); node2 = (struct node *) malloc (sizeof(struct node)); node3 = (struct node *) malloc (sizeof(struct node)); node4 = (struct node *) malloc (sizeof(struct node)); Here sizeof() is an operator which returns the number of bytes required for a structure type struct node. The node1, node2, node3 and node4 are declared as: struct node *node1, *node2, *node3, *node4; node1?? node2?? node3?? node4?? The data fields of all these four nodes are set as: node1->data = 21; node2->data = 38; node3->data = 18; node4->data = 62; Now we have four dynamic nodes as shown in following figure: node1 21? node2 38? node3 18? node4 62?

30 Now we create links between these four nodes as: node1->link = node2; node2->link = node3; node3->link = node4; node4->link = NULL; We store NULL in the link field of node4 in order to indicate the end of the list. Finally all these five nodes are represented as shown in Figure-3.4. Now if we store the address of first node node1 in an external pointer variable first we can easily access all four nodes by walking through one node to next by using the link field of a node. first 1 21 node2 38 node3 18 node4 62 NULL Figure-3.4 Representation of 4 linked nodes 3.3 Basic Operations on Linear Linked Lists Generally we perform following operations on linear linked lists: Traverse() Traversing a linear linked list Insertion() Inserting an element into a linear linked list Deletion () Deleting an element from a linear linked lists However some other operations are also possible on lists, such as searching, reversing, concatenating, disposing, etc. In all these operations, we will pass an address of external pointer first to allow it change during the initialization of a linked list. Initially first is assign to NULL indicating an empty list, as follows: struct node *first = NULL; Remind that the pointer variable first contains either a NULL value (if the list is empty) or the address of first node of the linked list.

31 3.3.1 Traversing a Linear Linked List When we want to traverse a linear linked list we access each node of it and make use of pointer field of each node while moving from one node to next. Firstly we will check whether the list is empty or not. If the list is empty then it just displays an error message and the control is returned back. If the list is not empty then we start accessing of nodes from first node. Algorithm : Traverse Traverse(First) Perform the following step if First is not NULL 1. Set Temp = First 2. Repeat through Step-4 while Temp <> NULL 3. Process the data of Temp node Data(Temp) 4. Update the link of Temp node Temp = Link(Temp) 5. Exit Here is the C implementation of this algorithm. Implementation : Traverse Traverse(struct node *first) struct node *temp; temp = first; while (first!= NULL) printf("%d\n",first->data); first = first->link; Searching a Linear Linked List If we are given a linked list and we want to search an item in that list then we will move from one node to next until the node is searched or the entire list is searched. Firstly we will check whether the list is empty or not. If the list is empty then it just displays an error message and the control is returned back. If the list is not empty then we start searching from first node. Algorithm : Search Search(First, Item) Perform the following step if First is not NULL 1. Set Current = First 2. Repeat through Step-4 while Current <> NULL 3. Compare Item with Data(Current) If Data(Current) = Item then Display Item is found and go to Step-6; Otherwise go to Step-5 4. Update the value of Current Current = Link(Current)

32 5. Display Item is not found in the list 6. Exit Here is the C implementation of this algorithm. Implementation : Search Search(int item) struct node *current; current = first; while (current!= NULL) If (current->data == item) printf("%d\n is found in the list", current->data); return; else current = current->link; printf("%d\n is not found in the list", current->data); Insertion into a Linear Linked List Insertion in a linked list is possible in three ways: 1. Insertion at first position 2. Insertion at last position 3. Insertion at any position Insertion at first position - When we insert a new node as a first node then firstly we create a new node Temp and then set the data field and assign the value of the first pointer variable to the link field of temp node as: Data(Temp) = 55 Link(Temp) = First and finally we update the value of external pointer variable First as: First = Temp. Figure-3.5 illustrates a linear linked list before and after inserting a new node.

33 First NULL (a) Before Insertion of a node First NULL 55 Temp Algorithm : InsertionFirst InsertionFirst (Item) (b) After Insertion of a node Figure-3.5 Insertion of node as a first node 1. Create a new node Node(Temp) 2. Set Data field of Temp node Data(temp) = Item 3. Set Link field of Temp node Link(Temp) = First 4. Update the value of First First = Temp 5. Exit Here is the C implementation of this algorithm. Implementation : InsertionFirst InsertionFirst(int item) struct node *temp; temp = (struct node *)malloc(sizeof(struct node)); temp->data=item; temp->link = first; first=temp; Insertion at last position - When insert a new node at last position we will create a new dynamic node first and update the external pointer variable, first, if the list is empty; otherwise we store the address of this newly created node in the link field of last node. Figure-3.6 illustrates a linear linked list before and after inserting a new node as last node. First NULL

34 (a) Before Insertion of a node First NULL Temp Algorithm : InsertionLast InsertionLast (Item) (b) After Insertion of a node Figure-3.6 Insertion of node as a last node 1. Create a new node Node(Temp) 2. Set Data field of Temp node Data(temp) = Item 3. Set Link field of Temp node Link(Temp) = NULL 4. If First = NULL then Update the value of First First = Temp and goto Step-7 5. Set Current = First 6. Repeat through Step-7 While Link(Current) <> NULL 7. Update the value of Current Current = Link(Current) 8. Update the value of Link(Current) Link(Current) = Temp 9. Exit Here is the C implementation of this algorithm. Implementation : InsertionLast InsertionLast (int item) struct node *temp, *current; temp = (struct node *)malloc(sizeof(struct node)); temp->data=item; temp->link=null; if (first==null) first = temp; else current = first; while (current->link!= NULL) current = current->link; current->link = temp;

35 Insertion at any position - When we insert a new node at any specific position we take two pointer variables current and previous. The current pointer holds the address of current node and previous pointer holds the address of previous node of current node. Now we move from one node to next until we come at proper position. After this we insert the new node between previous node and current node. However if we do not get proper position and entire list gets exhausted then this new node is inserted as last node. Figure-3.7 illustrates a linear linked list before and after inserting a new node at 4 th position. First NULL (a) Before Insertion of a node Current First NULL Previous 55 Algorithm : InsertionAny InsertionLast (Item, Pos) Temp (b) Before Insertion of a node Figure-3.7 Insertion of node at 3rd Position 1. Create a new node Node(Temp) 2. If First = NULL or Pos = 1 then Insert this new node as a first node and go to Step Set Previous = First 4. Set Current = Link(First) 5. Initialize I = 1 6. Repeat through Step-9 While Current <> NULL 7. If I + 1 = Pos then goto Step-10; Otherwise go to Step-8 8. Update Previous and Current Previous = Current Current = Link(Current) 9. Increment I I Set Data field of Temp node Data(Temp) = Item 11. Set Link field of Temp node Link(Temp) = Current 12. Update the value of Link(Previous) Link(Previous) = Temp 13. Exit Here is the C implementation of this algorithm.

36 Implementation : InsertionAny InsertionAny(int item, int pos) struct node *current, *previous, *temp; int i; temp = (struct node *)malloc(sizeof(struct node)); if ((first == NULL) (pos==1)) temp->data = item; temp->link = first; first = temp; return; current = first->link; previous = first; i = 1 while (current!= NULL) if ( (i+1) == pos ) break; else previous = current; current = current->link; i = i + 1; temp->data = item; temp->link = current; previous->link = temp; Deletion from a Linear Linked List Deletion from a linked list may be possible in three ways: 1. Deletion at first position 2. Deletion at last position 3. Deletion at any position Deleting at First Position When we delete first node, if the list is not empty. Figure-3.8 illustrates a linear linked list of deleting first node. First NULL

37 (a) Before deletion of first node Current First NULL (b) After deletion of first node Figure-3.8 Deletion of first node Initially we assign the value of First to Current as: Current = First Now the Current points to first node of the list. So process the data field of current node and update the value of First as: First = Link(First) And finally we free the space occupied by the Current node. Algorithm : DeletionFirst DeletionFirst ( ) 1. Set Current = First 2. Process Data field of Current node - Data(Current) 3. Update the value of First First = Link(First) 4. Free the memory occupied by Current node 5. Exit Here is the C implementation of this algorithm. Implementation : DeletionFirst DeletionFirst( ) struct node *current; if (first == NULL) printf("\nlist is empty. "); else current = first; printf( \ndeleted item = %d, current->data); first = first->link; free (current);

Darshan Institute of Engineering & Technology for Diploma studies Unit 4

Darshan 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 information

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Computer 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 information

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

FOR Loop. FOR Loop has three parts:initialization,condition,increment. Syntax. for(initialization;condition;increment){ body;

FOR 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 information

Arrays. 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 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 information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

INTRODUCTION 1 AND REVIEW

INTRODUCTION 1 AND REVIEW INTRODUTION 1 AND REVIEW hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Programming: Advanced Objectives You will learn: Program structure. Program statements. Datatypes. Pointers. Arrays. Structures.

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Basic Elements of C. Staff Incharge: S.Sasirekha

Basic Elements of C. Staff Incharge: S.Sasirekha Basic Elements of C Staff Incharge: S.Sasirekha Basic Elements of C Character Set Identifiers & Keywords Constants Variables Data Types Declaration Expressions & Statements C Character Set Letters Uppercase

More information

The time and space are the two measure for efficiency of an algorithm.

The time and space are the two measure for efficiency of an algorithm. There are basically six operations: 5. Sorting: Arranging the elements of list in an order (either ascending or descending). 6. Merging: combining the two list into one list. Algorithm: The time and space

More information

C Language, Token, Keywords, Constant, variable

C Language, Token, Keywords, Constant, variable C Language, Token, Keywords, Constant, variable A language written by Brian Kernighan and Dennis Ritchie. This was to be the language that UNIX was written in to become the first "portable" language. C

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables

More information

First of all, it is a variable, just like other variables you studied

First of all, it is a variable, just like other variables you studied Pointers: Basics What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the address (rather than the value)

More information

Technical Questions. Q 1) What are the key features in C programming language?

Technical Questions. Q 1) What are the key features in C programming language? Technical Questions Q 1) What are the key features in C programming language? Portability Platform independent language. Modularity Possibility to break down large programs into small modules. Flexibility

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - 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 information

Module 6: Array in C

Module 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 information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

DECLARAING AND INITIALIZING POINTERS

DECLARAING AND INITIALIZING POINTERS DECLARAING AND INITIALIZING POINTERS Passing arguments Call by Address Introduction to Pointers Within the computer s memory, every stored data item occupies one or more contiguous memory cells (i.e.,

More information

DC104 DATA STRUCTURE JUNE Q.2 a. If you are using C language to implement the heterogeneous linked list, what pointer type will you use?

DC104 DATA STRUCTURE JUNE Q.2 a. If you are using C language to implement the heterogeneous linked list, what pointer type will you use? Q.2 a. If you are using C language to implement the heterogeneous linked list, what pointer type will you use? The heterogeneous linked list contains different data types in its nodes and we need a link

More information

DC54 DATA STRUCTURES DEC 2014

DC54 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 information

Unit 7. Functions. Need of User Defined Functions

Unit 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 information

Review of the C Programming Language

Review of the C Programming Language Review of the C Programming Language Prof. James L. Frankel Harvard University Version of 11:55 AM 22-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Reference Manual for the

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Types of Data Structures

Types of Data Structures DATA STRUCTURES material prepared by: MUKESH BOHRA Follow me on FB : http://www.facebook.com/mukesh.sirji4u The logical or mathematical model of data is called a data structure. In other words, a data

More information

Review of the C Programming Language for Principles of Operating Systems

Review of the C Programming Language for Principles of Operating Systems Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights

More information

Write a C program using arrays and structure

Write 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 information

Data Types and Variables in C language

Data 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 information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis

More information

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

Subject: 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 information

MODULE 5: Pointers, Preprocessor Directives and Data Structures

MODULE 5: Pointers, Preprocessor Directives and Data Structures MODULE 5: Pointers, Preprocessor Directives and Data Structures 1. What is pointer? Explain with an example program. Solution: Pointer is a variable which contains the address of another variable. Two

More information

Model Viva Questions for Programming in C lab

Model 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 information

Unit 3 Decision making, Looping and Arrays

Unit 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 information

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Lecture 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 information

Pointers. Introduction

Pointers. 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 information

COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR. VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS

COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR.  VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS S.LAWRENCE CHRISTOPHER, M.C.A., B.Ed., LECTURER IN COMPUTER SCIENCE PONDICHERRY

More information

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA. DECLARATIONS Character Set, Keywords, Identifiers, Constants, Variables Character Set C uses the uppercase letters A to Z. C uses the lowercase letters a to z. C uses digits 0 to 9. C uses certain Special

More information

Basics of Programming

Basics 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 information

PDS Class Test 2. Room Sections No of students

PDS 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 information

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS Contents Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS 1.1. INTRODUCTION TO COMPUTERS... 1 1.2. HISTORY OF C & C++... 3 1.3. DESIGN, DEVELOPMENT AND EXECUTION OF A PROGRAM... 3 1.4 TESTING OF PROGRAMS...

More information

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency Introduction Fundamentals Declaring arrays Indexing arrays Initializing arrays Arrays and functions Multidimensional arrays Sorting and algorithm efficiency An array is a sequence of values of the same

More information

1 P a g e A r y a n C o l l e g e \ B S c _ I T \ C \

1 P a g e A r y a n C o l l e g e \ B S c _ I T \ C \ BSc IT C Programming (2013-2017) Unit I Q1. What do you understand by type conversion? (2013) Q2. Why we need different data types? (2013) Q3 What is the output of the following (2013) main() Printf( %d,

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2018 Outline Outline 1 Chapter 8: A C++ Introduction For Python Programmers Expressions and Operator Precedence

More information

BoredGames Language Reference Manual A Language for Board Games. Brandon Kessler (bpk2107) and Kristen Wise (kew2132)

BoredGames Language Reference Manual A Language for Board Games. Brandon Kessler (bpk2107) and Kristen Wise (kew2132) BoredGames Language Reference Manual A Language for Board Games Brandon Kessler (bpk2107) and Kristen Wise (kew2132) 1 Table of Contents 1. Introduction... 4 2. Lexical Conventions... 4 2.A Comments...

More information

Lab 3. Pointers Programming Lab (Using C) XU Silei

Lab 3. Pointers Programming Lab (Using C) XU Silei Lab 3. Pointers Programming Lab (Using C) XU Silei slxu@cse.cuhk.edu.hk Outline What is Pointer Memory Address & Pointers How to use Pointers Pointers Assignments Call-by-Value & Call-by-Address Functions

More information

DEPARTMENT 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 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 information

VARIABLES AND CONSTANTS

VARIABLES AND CONSTANTS UNIT 3 Structure VARIABLES AND CONSTANTS Variables and Constants 3.0 Introduction 3.1 Objectives 3.2 Character Set 3.3 Identifiers and Keywords 3.3.1 Rules for Forming Identifiers 3.3.2 Keywords 3.4 Data

More information

UNIT-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. 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 information

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE TED (10)-3071 Reg. No.. (REVISION-2010) Signature. FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours (Maximum marks: 100)

More information

NCS 301 DATA STRUCTURE USING C

NCS 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 information

Chapter4: Data Structures. Data: It is a collection of raw facts that has implicit meaning.

Chapter4: Data Structures. Data: It is a collection of raw facts that has implicit meaning. Chapter4: s Data: It is a collection of raw facts that has implicit meaning. Data may be single valued like ID, or multi valued like address. Information: It is the processed data having explicit meaning.

More information

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program Syntax What the Compiler needs to understand your program 1 Pre-Processing Any line that starts with # is a pre-processor directive Pre-processor consumes that entire line Possibly replacing it with other

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

More information

CSc Introduction to Computing

CSc Introduction to Computing CSc 10200 Introduction to Computing Lecture 2 Edgardo Molina Fall 2011 - City College of New York Thursday, September 1, 2011 Introduction to C++ Modular program: A program consisting of interrelated segments

More information

Programming in C++ 4. The lexical basis of C++

Programming in C++ 4. The lexical basis of C++ Programming in C++ 4. The lexical basis of C++! Characters and tokens! Permissible characters! Comments & white spaces! Identifiers! Keywords! Constants! Operators! Summary 1 Characters and tokens A C++

More information

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

To 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 information

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Variables 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 information

V2 3/5/2012. Programming in C. Introduction to Arrays. 111 Ch 07 A 1. Introduction to Arrays

V2 3/5/2012. Programming in C. Introduction to Arrays. 111 Ch 07 A 1. Introduction to Arrays Programming in C 1 Introduction to Arrays A collection of variable data Same name Same type Contiguous block of memory Can manipulate or use Individual variables or List as one entity 2 Celsius temperatures:

More information

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

IECD 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 information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 7/e This chapter serves as an introduction to data structures. Arrays are data structures consisting of related data items of the same type. In Chapter 10, we discuss C s notion of

More information

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305 Q.1 If h is any hashing function and is used to hash n keys in to a table of size m, where n

More information

CS201- 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. 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 information

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Gabriel 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 information

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE is to be

More information

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer: Chapter-11 POINTERS Introduction: Pointers are a powerful concept in C++ and have the following advantages. i. It is possible to write efficient programs. ii. Memory is utilized properly. iii. Dynamically

More information

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space. Chapter 2: Problem Solving Using C++ TRUE/FALSE 1. Modular programs are easier to develop, correct, and modify than programs constructed in some other manner. ANS: T PTS: 1 REF: 45 2. One important requirement

More information

Binary Representation. Decimal Representation. Hexadecimal Representation. Binary to Hexadecimal

Binary 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 information

Decimal Representation

Decimal 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 information

ARRAYS(II Unit Part II)

ARRAYS(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 information

Chapter-8 DATA TYPES. Introduction. Variable:

Chapter-8 DATA TYPES. Introduction. Variable: Chapter-8 DATA TYPES Introduction To understand any programming languages we need to first understand the elementary concepts which form the building block of that program. The basic building blocks include

More information

Computer Programming C++ (wg) CCOs

Computer Programming C++ (wg) CCOs Computer Programming C++ (wg) CCOs I. The student will analyze the different systems, and languages of the computer. (SM 1.4, 3.1, 3.4, 3.6) II. The student will write, compile, link and run a simple C++

More information

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables. When a program is run, memory space is immediately reserved for the variables defined in the program. This memory space is kept by the variables until the program terminates. These variables are called

More information

Syntax and Variables

Syntax and Variables Syntax and Variables What the Compiler needs to understand your program, and managing data 1 Pre-Processing Any line that starts with # is a pre-processor directive Pre-processor consumes that entire line

More information

Introduction to Computer Science Midterm 3 Fall, Points

Introduction to Computer Science Midterm 3 Fall, Points Introduction to Computer Science Fall, 2001 100 Points Notes 1. Tear off this sheet and use it to keep your answers covered at all times. 2. Turn the exam over and write your name next to the staple. Do

More information

[0569] p 0318 garbage

[0569] p 0318 garbage A Pointer is a variable which contains the address of another variable. Declaration syntax: Pointer_type *pointer_name; This declaration will create a pointer of the pointer_name which will point to the

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

UNIT 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 information

C-LANGUAGE CURRICULAM

C-LANGUAGE CURRICULAM C-LANGUAGE CURRICULAM Duration: 2 Months. 1. Introducing C 1.1 History of C Origin Standardization C-Based Languages 1.2 Strengths and Weaknesses Of C Strengths Weaknesses Effective Use of C 2. C Fundamentals

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

APSC 160 Review. CPSC 259: Data Structures and Algorithms for Electrical Engineers. Hassan Khosravi Borrowing many questions from Ed Knorr

APSC 160 Review. CPSC 259: Data Structures and Algorithms for Electrical Engineers. Hassan Khosravi Borrowing many questions from Ed Knorr CPSC 259: Data Structures and Algorithms for Electrical Engineers APSC 160 Review Hassan Khosravi Borrowing many questions from Ed Knorr CPSC 259 Pointers Page 1 Learning Goal Briefly review some key programming

More information

Arrays. Defining arrays, declaration and initialization of arrays. Designed by Parul Khurana, LIECA.

Arrays. Defining arrays, declaration and initialization of arrays. Designed by Parul Khurana, LIECA. Arrays Defining arrays, declaration and initialization of arrays Introduction Many applications require the processing of multiple data items that have common characteristics (e.g., a set of numerical

More information

CSCI 171 Chapter Outlines

CSCI 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 information

Arrays. 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 Arrays CS10001: Programming & Data Structures Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur 1 Array Many applications require multiple data items that have common

More information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e 1992-2010 by Pearson Education, Inc. 1992-2010 by Pearson Education, Inc. 1992-2010 by Pearson Education, Inc. This chapter serves as an introduction to the important topic of data

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

Assist. Prof. Dr. Caner ÖZCAN

Assist. Prof. Dr. Caner ÖZCAN Assist. Prof. Dr. Caner ÖZCAN Memory Structure When a variable defined it is stored somewhere in memory. Memory can be thought as block consist of cells. When a variable defined, required number of cell

More information

Unit 1 - Arrays. 1 What is an array? Explain with Example. What are the advantages of using an array?

Unit 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 information

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Unit-II Programming and Problem Solving (BE1/4 CSE-2) Unit-II Programming and Problem Solving (BE1/4 CSE-2) Problem Solving: Algorithm: It is a part of the plan for the computer program. An algorithm is an effective procedure for solving a problem in a finite

More information

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler

More information

Introduction to C Final Review Chapters 1-6 & 13

Introduction to C Final Review Chapters 1-6 & 13 Introduction to C Final Review Chapters 1-6 & 13 Variables (Lecture Notes 2) Identifiers You must always define an identifier for a variable Declare and define variables before they are called in an expression

More information

Procedural programming with C

Procedural 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 information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

Programming for Electrical and Computer Engineers. Pointers and Arrays

Programming for Electrical and Computer Engineers. Pointers and Arrays Programming for Electrical and Computer Engineers Pointers and Arrays Dr. D. J. Jackson Lecture 12-1 Introduction C allows us to perform arithmetic addition and subtraction on pointers to array elements.

More information

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions

More information

Maltepe University Computer Engineering Department. BİL 133 Algorithms and Programming. Chapter 8: Arrays

Maltepe University Computer Engineering Department. BİL 133 Algorithms and Programming. Chapter 8: Arrays Maltepe University Computer Engineering Department BİL 133 Algorithms and Programming Chapter 8: Arrays What is an Array? Scalar data types use a single memory cell to store a single value. For many problems

More information

Goals of this Lecture

Goals of this Lecture C Pointers Goals of this Lecture Help you learn about: Pointers and application Pointer variables Operators & relation to arrays 2 Pointer Variables The first step in understanding pointers is visualizing

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #29 Arrays in C (Refer Slide Time: 00:08) This session will learn about arrays in C. Now, what is the word array

More information