UNIT-I Fundamental Notations

Similar documents
Darshan Institute of Engineering & Technology for Diploma studies Unit 4

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

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

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

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

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

INTRODUCTION 1 AND REVIEW

Fundamental of Programming (C)

Basic Elements of C. Staff Incharge: S.Sasirekha

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

C Language, Token, Keywords, Constant, variable

Fundamentals of Programming

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

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

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

Module 6: Array in C

Full file at

DECLARAING AND INITIALIZING POINTERS

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?

DC54 DATA STRUCTURES DEC 2014

Unit 7. Functions. Need of User Defined Functions

Review of the C Programming Language

UNIT- 3 Introduction to C++

Types of Data Structures

Review of the C Programming Language for Principles of Operating Systems

Write a C program using arrays and structure

Data Types and Variables in C language

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

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

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

MODULE 5: Pointers, Preprocessor Directives and Data Structures

Model Viva Questions for Programming in C lab

Unit 3 Decision making, Looping and Arrays

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

Pointers. Introduction

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

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

Basics of Programming

PDS Class Test 2. Room Sections No of students

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

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

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

CSI33 Data Structures

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

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

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS

VARIABLES AND CONSTANTS

UNIT-1. Chapter 1(Introduction and overview) 1. Asymptotic Notations 2. One Dimensional array 3. Multi Dimensional array 4. Pointer arrays.

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

NCS 301 DATA STRUCTURE USING C

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

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

3. Java - Language Constructs I

CSc Introduction to Computing

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

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

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

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

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

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

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

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

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

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

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

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

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

Decimal Representation

ARRAYS(II Unit Part II)

Chapter-8 DATA TYPES. Introduction. Variable:

Computer Programming C++ (wg) CCOs

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

Syntax and Variables

Introduction to Computer Science Midterm 3 Fall, Points

[0569] p 0318 garbage

C++ for Java Programmers

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

C-LANGUAGE CURRICULAM

1 Lexical Considerations

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

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

CSCI 171 Chapter Outlines

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

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

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

Assist. Prof. Dr. Caner ÖZCAN

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

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

CS201- Introduction to Programming Current Quizzes

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

Introduction to C Final Review Chapters 1-6 & 13

Procedural programming with C

C: How to Program. Week /Mar/05

Programming for Electrical and Computer Engineers. Pointers and Arrays

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

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

Goals of this Lecture

A Fast Review of C Essentials Part I

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

Transcription:

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

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

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

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. 1.2.1 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 8-128 to +127 int 16-32,768 to 32,767 long int 32-2,147,483,648 to +2,147,483,647 float 32-3.4E-38 to +3.4E+38 double 64-1.7E-308 to +1.7E+308 long double 80-3.4E-4932 to +1.1E+4932 Table 1.1 Basic Data Types

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. 1.2.2 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: 1200 23456-19 13 187 Followings are the invalid integer constants: 12 34 /* no space between digit 2 and 3 */ 1_45 /* no hyphen */ 1.9876 /* 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: 12.9876 0.234 1223.90 (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: 2.4876e1-3.2e-5 567e-2 21.87e+12

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 1.2.3 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;

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 10 6442 8 Location contents Memory address In figure : 64428 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

address 64428. This memory address 64428 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

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 - 64428, 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 64428 (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);

printf( \nvalue = %d \t Address =, *iptr, iptr); The output of this program is as. Value = 10 Address = 64428 Value = 10 Address = 64428 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?

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. 34 28] 65 30 18 57 43 29 85 10 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

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 2.1.1 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:

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

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 12 26 83 54 15 96 47 18 39 20 6400 6402 6404 6406 6408 6410 6412 6414 6416 6418 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). 2.1.2 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

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

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. 4 9 7 8 2 5 11 14 15 6 1 3 0 th Row 1 st Row 2 nd Row Figure- Row Major Order Representation

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 64080 and we want to find out the address of A [2][1]. In this example Base address = 64080 Size = 4 N = 5 I = 2 J = 1 Address of A [2][1] = 64080 + 4 (2x5+1) = 64080 + 4 (11) = 64124 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.

4 2 15 9 5 6 7 11 1 8 14 3 0 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 64080 and we want to find out the address of A [2][1]. In this example Base address = 64080 Size = 4 M = 4 I = 2 J = 1 Address of A [2][1] = 64080 + 4 (4x2+1) = 64080 + 4 (9) = 64116

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. 2.3.1 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 */

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) ;

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. 0 15 15 1 21 21 2 17 17 3 25 25 4-40 -40 5 54 54 6 29 22 New element 7 17 29 8 20 17 9 45 20 45 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

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

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. 0 15 15 1 21 21 2 17 17 3 25 25 4-40 -40 5 54 54 6 29 Deleted Item 17 7 17 20 8 20 45 9 45 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-10 3. 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 1 10. 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)

/* 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.

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] = 64820 + (8 * 4) = 64852 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

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 21 38 18 62 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 21 38 18 62 NULL (a) Singly Linked List left data right left data right left data right left data right first NULL 21 38 18 62 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.

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) 3.3.1 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.

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

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 21 38 18 62 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?

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.

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; 3.3.1 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)

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); 3.3.3. 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.

First 21 38 18 62 NULL (a) Before Insertion of a node First 21 38 18 62 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 21 38 18 62 NULL

(a) Before Insertion of a node First 21 38 18 62 55 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;

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 21 38 18 62 NULL (a) Before Insertion of a node Current First 21 38 18 62 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-10 3. 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 + 1 10. 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.

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; 3.3.4 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 21 38 18 62 NULL

(a) Before deletion of first node Current First 21 38 18 62 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);