Esoft Metro Campus - Certificate in c / c++ programming

Preview:

Citation preview

Certificate in C/C++ Programming

Rasan SamarasingheESOFT Computer Studies (pvt) Ltd.No 68/1, Main Street, Pallegama, Embilipitiya.

Programme Structure

1. Structure of a program

2. Variables & Data types

3. Constants

4. Operators

5. Basic Input/output

6. Control Structures

7. Functions

8. Arrays

9. Character Sequences

10. Pointers and Dynamic Memory

11. Unions

12. Other Data Types

13. Input/output with files

14. Searching

15. Sorting

16. Introduction to data structures

C Language Overview

• A general purpose language.• Originally developed by Dennis M. Ritchie to

develop Unix operating system.• It is a structured programming language.• It can handle low level activities.• It produces efficient programs.• It can be compiled on variety of platforms.• A widely used System Programming Language.

What you can create with C?

• Operating Systems• Language Compilers• Assemblers• Text Editors• Print Spoolers• Network Drivers• Modem Programs• Databases• Language Interpreters• Utilities

What you need to program with C

• C/C++ Compiler• Text Editor• Command Prompt

1. Structure of a Program

C Hello World Example

#include <stdio.h>

int main(){ printf("Hello world!"); return 0;}

main.c

C Hello World Example

A C program basically consists of:

• Preprocessor Commands• Functions• Variables• Statements & Expressions• Comments

Tokens in C

#include <stdio.h>

int main(){ printf("Hello world!"); return 0;}

A program consists of tokens is either a keyword, an identifier, a string literal, a constant or a symbol

Whitespaces

Whitespaces are used to separate tokens.

• Blanks• Tabs• Newline character• Comments

Semicolon

Each individual statement must be ended with a semicolon

printf("Hello world!");return 0;

Comments

Helping text in your program and ignored by the compiler

//this is a single line comment

/* This is a multilinecomment */

Identifiers

An identifier is a name used to identify a variable, function or any other user defined item

• Starts with a letter a to z or A to Z or _.• Followed by zero or more letters, underscores

and digits.• Does not allow any symbols and spaces.• Case sensitive.

keywords

These reserved words are not allowed to use as identifier names

2. Variables & Data types

Type classification in C

Integer types

Floating point types

Void types

Variables

Variables are temporary memory locations in C programs which consisting known or unknown values.

Variable definition in C

Variable definitiontype variable_list;

Variable definition and initializationtype variable_name = value;

Variable declaration

Provides assurance to the compiler that there is one variable existing with the given type and name.

extern type variable_list;

3. Constants

Constants

• Constants refer to fixed values that the program may not alter during its execution.

• These fixed values are also called literals.

Literals

• Integer literals • Floating-point literals • Character literals • String literals

Defining Constants

• Using #define preprocessor. • Using const keyword.

Using #define preprocessor

Syntax:#define identifier value

Ex:#define PI 3.14

Using const keyword

Syntax:const type variable = value;

Ex:const int LENGTH = 10;

4. Operators

Arithmetic Operators

A = 10, B = 20

Comparison OperatorsA = 10, B = 20

Logical Operators

A = 1, B = 0

Bitwise OperatorsA = 60, B = 13

Truth table

Bitwise Operators

A = 00111100 B = 00001101 A&B = 00001100 A|B = 00111101 A^B = 00110001 ~A = 11000011

A = 60, B = 13

Assignment Operators

Misc Operators

Operators Precedence in C

5. Basic Input/output

getchar() function

int getchar(void) function reads the next available character from the screen and returns it as an integer.

int c; printf("Enter a value :"); c = getchar();

putchar() function

int putchar(int c) function puts the passed character on the screen and returns the same character.

printf( "You entered: "); putchar(c);

gets() function

char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF.

char str[100]; printf("Enter a value :"); gets(str);

puts() function

int puts(const char *s) function writes the string s and a trailing newline to stdout.

printf("You entered: "); puts(str);

scanf() function

int scanf(const char *format, ...) function reads input from the standard input stream stdin and scans that input according to format provided.

char str[100]; int i; printf("Enter a value :"); scanf("%s %d", str, &i);

printf() function

int printf(const char *format, ...) function writes output to the standard output stream stdout and produces output according to a format provided.

printf( "\nYou entered: %s, %d ", str, i);

6. Control Structures

If Statement

if(Boolean_expression){ //Statements will execute if the

Boolean expression is true}

Boolean Expression

Statements

True

False

If… Else Statement

if(Boolean_expression){ //Executes when the Boolean expression is

true}else{ //Executes when the Boolean

expression is false}

Boolean Expression

Statements

True

False

Statements

If… Else if… Else Statement

if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true}else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true}else if(Boolean_expression 3){ //Executes when the Boolean expression 3 is true}else { //Executes when the none of the above condition is true.}

If… Else if… Else Statement

Boolean expression 1

False

Statements

Boolean expression 2

Boolean expression 3

Statements

Statements

False

False

Statements

True

True

True

Nested If Statement

if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true if(Boolean_expression 2){ //Executes when the Boolean expression 2 is

true }}

Boolean Expression 1

True

False

StatementsBoolean Expression 2

True

False

Switch Statement

switch (value){ case constant: //statements break; case constant: //statements break; default: //statements}

The ? : Operator

Exp1 ? Exp2 : Exp3;

Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire expression.

If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.

While Loop

while(Boolean_expression){ //Statements}

Boolean Expression

Statements

True

False

Do While Loop

do{ //Statements}while(Boolean_expression);

Boolean Expression

Statements

True

False

For Loop

for(initialization; Boolean_expression; update){ //Statements}

Boolean Expression

Statements

True

False

Update

Initialization

break Statement

Boolean Expression

Statements

True

False

break

continue Statement

Boolean Expression

Statements

True

False

continue

Nested Loop

Boolean Expression

True

False

Boolean Expression

Statements

True

False

7. Functions

Functions

• Function is a group of statements that together perform a task.

• Every C program has at least one function, which is main()

Defining a Function

return_type function_name( parameter list ) { body of the function

}

Example

int max(int num1, int num2) { int result; if (num1 > num2){ result = num1; }else{ result = num2; } return result; }

Function Declarations

A function declaration tells the compiler about a function name and how to call the function.

return_type function_name( parameter list );

Ex:int max(int num1, int num2); int max(int, int);

Calling a Function

int a = 100; int b = 200; int ret; /* calling a function to get max value */ ret = max(a, b);

Function Arguments

• Function call by value • Function call by reference

Function call by value

passing arguments to a function copies the actual value of an argument into the formal parameter of the function.

Function call by value

void swap(int x, int y) { int temp; temp = x; x = y; y = temp; return; }

Function call by value #include <stdio.h> void swap(int x, int y);

int main () { int a = 100, b = 200; printf("Before swap, value of a : %d\n", a ); printf("Before swap, value of b : %d\n", b ); swap(a, b); printf("After swap, value of a : %d\n", a ); printf("After swap, value of b : %d\n", b ); return 0; }

Function call by reference

passing arguments to a function copies the address of an argument into the formal parameter.

Function call by reference

void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; return; }

Function call by reference #include <stdio.h> void swap(int *x, int *y); int main () { int a = 100; int b = 200; printf("Before swap, value of a : %d\n", a ); printf("Before swap, value of b : %d\n", b ); swap(&a, &b); printf("After swap, value of a : %d\n", a ); printf("After swap, value of b : %d\n", b ); return 0; }

8. Arrays

Arrays

• An Array is a data structure which can store a fixed size sequential collection of elements of the same type.

• An array is used to store a collection of data.

Single dimensional arrays

Declaring Arrays

type arrayName [ arraySize ];

Ex:

double balance[10];

Initializing Arrays

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

If you omit the size of the array, an array just big enough to hold the initialization is created.

double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};

Accessing Array Elements

An element is accessed by indexing the array name.

double salary = balance[0];

Multi-dimensional Arrays

C programming language allows multidimensional arrays.

Here is the general form of a multidimensional array declaration:

type name[size1][size2]...[sizeN];

Use of Multi-dimensional Arrays

Two-Dimensional Arrays

Declaring a two dimensional array of size x, y

type arrayName [ x ][ y ];

Initializing Two-Dimensional Arrays

int a[3][4] = { {0, 1, 2, 3} , {4, 5, 6, 7} , {8, 9, 10, 11} };

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements

An element in two dimensional array is accessed by using row index and column index of the array.

int val = a[2][3];

Passing Arrays as Function Arguments

Formal parameters as a pointervoid myFunction(int *param) { }

Formal parameters as a sized arrayvoid myFunction(int param[10]) { }

Formal parameters as an unsized arrayvoid myFunction(int param[]) { }

Return array from function

int * myFunction() { static int demo[5] = {20, 40, 50, 10, 60}; return demo; }

Pointer to an Array

double balance[5] = {20.50, 65.00, 35.75, 74.25, 60.00};double *ptr;ptr = balance;int i;

printf("Array values using pointer\n");for(i=0; i<=4; i++){printf("balance[%d] = %.2f \n", i, *(ptr+i));}printf("Array values using balance\n");for(i=0; i<=4; i++){printf("balance[%d] = %.2f \n", i, *(balance+i));}

9. Character Sequences

C Strings

The string in C programming language is actually a one-dimensional array of characters which is terminated by a null character '\0'.

C Strings

The following declaration and initialization create a string consisting of the word "Hello“

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Using array initializer

char greeting[] = "Hello";

String functions in string.h

10. Pointers and Dynamic Memory

Variable Address

every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator.

int var1; char var2[10]; printf("Address of var1 variable: %x\n", &var1 ); printf("Address of var2 variable: %x\n", &var2 );

What Are Pointers?

A pointer is a variable whose value is the address of another variable.

pointer variable declaration:

type *var-name;

What Are Pointers?

What Are Pointers?

int *ip; // pointer to an integer double *dp; // pointer to a double float *fp; // pointer to a float char *ch // pointer to a character

How to use Pointers?

1. Define a pointer variable.2. Assign the address of a variable to a pointer.3. Access the value at the address available in

the pointer variable.

How to use Pointers?

int var = 20; int *ip; ip = &var;

printf("Address of var variable: %x\n", &var ); printf("Address stored in ip variable: %x\n", ip ); printf("Value of *ip variable: %d\n", *ip );

NULL Pointers in C

int *ptr = NULL; printf("The value of ptr is : %x\n", &ptr );

Incrementing a Pointer

int var[] = {10, 100, 200}; int i, *ptr; ptr = var; for ( i = 0; i <= 2; i++) { printf("Address of var[%d] = %x\n", i, ptr ); printf("Value of var[%d] = %d\n", i, *ptr ); ptr++; }

Decrementing a Pointer

int var[] = {10, 100, 200}; int i, *ptr; ptr = &var[2]; for ( i = 2; i > 0; i--) { printf("Address of var[%d] = %x\n", i, ptr ); printf("Value of var[%d] = %d\n", i, *ptr ); ptr--; }

Pointer Comparisons

int var[] = {10, 100, 200}; int i, *ptr; ptr = var; i = 0; while ( ptr <= &var[2] ) { printf("Address of var[%d] = %x\n", i, ptr ); printf("Value of var[%d] = %d\n", i, *ptr ); ptr++; i++; }

Array of pointers

int var[] = {10, 100, 200}; int i, *ptr[3]; for ( i = 0; i <= 2; i++) { ptr[i] = &var[i]; } for ( i = 0; i < 2; i++) { printf("Value of var[%d] = %d\n", i, *ptr[i] ); }

Pointer to Pointer

When we define a pointer to a pointer, the first pointer contains the address of the second

pointer.

Pointer to Pointer

int var; int *ptr; int **pptr; var = 3000;ptr = &var;pptr = &ptr;printf("Value of var = %d\n", var ); printf("Value available at *ptr = %d\n", *ptr ); printf("Value available at **pptr = %d\n", **pptr);

Passing pointers to functions

void getSeconds(long *hours) { *hours = *hours * 60 * 60; return; }

int main () { long hours; getSeconds( &hours ); printf("Number of seconds: %d\n", hours ); return 0; }

Return pointer from functionsint * getNumber( ) { static int r[5] = {20, 40, 50, 10, 60}; return r; }

int main () { int *p; int i; p = getNumber(); for ( i = 0; i < 5; i++ ) { printf("*(p + [%d]) : %d\n", i, *(p + i) ); } return 0; }

Memory Management

• C language provides several functions for memory allocation and management.

• These functions can be found in the <stdlib.h> header file.

Allocating Memory Dynamically

#include <stdio.h>#include <stdlib.h>#include <string.h>

int main(){char *description;description = malloc(100 * sizeof(char)); // allocating memory dynamically

if(description == NULL){printf("unable to allocate required memory\n");}else{strcpy(description, "my name is khan");}

printf("description = %s", description);return 0;}

Resizing and Releasing Memory #include <stdio.h>#include <stdlib.h>#include <string.h>

int main(){char *description;description = malloc(10 * sizeof(char)); // allocating memory dynamicallydescription = realloc( description, 100 * sizeof(char) ); // resizing memory

if(description == NULL){printf("unable to allocate required memory\n");}else{strcpy(description, "my name is khan, and i'm not a terrorist");}

printf("description = %s", description);free(description); // releasing memoryreturn 0;}

11. Unions

Unions

• A union is a special data type available in C that enables you to store different data types in the same memory location.

• You can define a union with many members, but only one member can contain a value at any given time.

• Unions provide an efficient way of using the same memory location for multipurpose.

Defining a Union

union [union tag] { member definition; member definition; ... member definition; } [one or more union variables];

Defining a Union

union Data { int i; float f; char str[20]; } data;

• You can specify one or more union variables but it is optional.

• The union tag is optional when there are union variable definition.

Assigning values to Union

data.i = 10; data.f = 220.5; strcpy( data.str, “Hello world”);

Accessing Union Members

union Data data; printf( "Memory size occupied by data : %d\n", sizeof(data)); printf( "data.i : %d\n", data.i); printf( "data.f : %f\n", data.f); printf( "data.str : %s\n", data.str);

12. Other Data Types

Structures

• Structure is another user defined data type which allows you to combine data items of different kinds.

• Structures are used to represent a record.

Defining a Structure

struct [structure tag] { member definition; member definition; ... member definition; } [one or more structure variables];

Defining a Structure

struct Books { char title[50]; char author[50]; char category[100]; int book_id; } book;

• You can specify one or more structure variables but it is optional.

• The structure tag is optional when there are structure variable definition.

Assigning values to Structure

struct Books Book1; /* Declare Book1 of type Book */

strcpy( Book1.title, “Tom Sawyer”); strcpy( Book1.author, “Mark Twain”); strcpy( Book1.category, “Novel”); Book1.book_id = 64954;

Accessing Structure Members

printf( "Book 1 title : %s\n", Book1.title); printf( "Book 1 author : %s\n", Book1.author); printf( "Book 1 category : %s\n", Book1.category); printf( "Book 1 book_id : %d\n", Book1.book_id);

Structures as Function Arguments

// function definitionvoid printBook( struct Books book ) { printf( "Book title : %s\n", book.title); printf( "Book author : %s\n", book.author); printf( "Book category : %s\n", book.category); printf( "Book book_id : %d\n", book.book_id); }

// calling functionprintBook( Book1 );

Pointers to Structures

//define pointer to structurestruct Books *struct_pointer;

//store the address of a structure variable in the pointer struct_pointer = &Book1;

//access the members of a structurestruct_pointer->title;

Bit Fields

Bit fields offers a better way to utilize the memory space occupied by a Structure.

Bit Field Declaration

struct { type [member_name] : width ; };

• Width is the number of bits in the bit-field.

• The width must be less than or equal to the bit width of the specified type.

Bit Field example

struct { unsigned int widthValidated; unsigned int heightValidated; } status1;

struct { unsigned int widthValidated : 1; unsigned int heightValidated : 1; } status2;

printf( "Memory size occupied by status : %d\n", sizeof(status)); printf( "Memory size occupied by status2 : %d\n", sizeof(status2));

13. Input/output with files

Opening Files

FILE *fopen( const char * filename, const char * mode );

File access modes

Closing a File

int fclose( FILE *fp );

Writing a File

// write individual characters to a stream

int fputc( int c, FILE *fp );

// writes the string s to the output stream referenced by fp

int fputs( const char *s, FILE *fp );

Reading a File

// read a single character from a file

int fgetc( FILE * fp );

// reads up to n - 1 characters from the input stream referenced by fp

char *fgets( char *buf, int n, FILE *fp );

// scans a file according to format provided.

int fscanf(FILE *fp, const char *format, ...)

14. Searching

Searching Algorithms

• Linear Search• Binary Search

Linear Search

Linear search start at the beginning and walk to the end, testing for a match at each item.

Linear Searchint size = 6;int points[6] = {20, 50, 30, 60, 10, 80};int key = 60;

int i;for(i = 0; i <= size-1; i++){if(points[i] == key){printf("Value found at index %d", i);break;}}

if(i == size){printf("Value not found");}

Binary Search

Binary search is an efficient algorithm for finding an item from an ordered list of items.

It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one.

Binary Searchint size = 6;int points[6] = {10, 20, 30, 40, 50, 60};int key = 20;int low = 0, high = size-1;

while(high>=low){int mid = (low+high)/2;if(key < points[mid]){high = mid-1;}else if(key > points[mid]){low = mid+1;}else{printf("Value found at index %d", mid);break;}}

if(low>high){printf("Value not found");}

15. Sorting

Sorting Algorithms

• Bubble Sort• Selection Sort• Insertion Sort

Bubble Sort

Bubble Sort C Implementation

int abc[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };int c, i;

for (c = 1; c <= 9; c++){for (i = 0; i <= 7; i++){if (abc[i] > abc[i + 1]){int temp = abc[i];abc[i] = abc[i + 1];abc[i + 1] = temp;}}}

Selection Sort

Selection Sort C Implementation

int abc[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };

int minindex, i, c;for (c = 0; c <= 8; c++){minindex = c;for (i = c; i <= 8; i++){if (abc[i] < abc[minindex]){minindex = i;}}int temp = abc[c];abc[c] = abc[minindex];abc[minindex] = temp;}

Insertion Sort

Insertion Sort C Implementation

int abc[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };

int c, i, index;

for (c = 1; c <= 8; c++){index = abc[c];for (i = c; ((abc[i - 1] > index) && (i>0)); i--){abc[i] = abc[i - 1];}abc[i] = index;}

Comparison of Sorting Algorithms Bubble Sort Selection Sort Insertion SortData structure Array Array ArrayWorst case performance

O(n2) О(n2) О(n2)

Best case performance

O(n) О(n2) O(n)

Average case performance

O(n2) О(n2) О(n2)

Worst case space complexity

O(1) auxiliary О(n) total, O(1) auxiliary

О(n) total, O(1) auxiliary

Comparison Exchange two adjacent elements if they are out of order. Repeat until array is sorted. This is a slow algorithm.

Find the largest element in the array, and put it in the proper place. Repeat until array is sorted. This is also slow.

Scan successive elements for out of order item, and then insert the item in the proper place. Sort small array fast, big array very slowly.

16. Introduction to data structures

An introduction to Data Structures

In computer science, a data structure is a particular way of organizing data in a computer so that it can be used efficiently.

An introduction to Data Structures

Organized Data + Operations = Data Structure

Algorithm + Data Structure = Computer Program

Classifications of data structures

Frequently used data structures

• Stack• Queue• Linked List• Tree• Graph

Stack

• A stack is a data structure in which all the access is restricted to the most recently inserted item.

• If we remove this item, then we can access the next to last item inserted, and etc.

• Stack is a first in last out data structure.

Operations on Stack

• PUSH: The process of inserting a new element to the top of the stack.

• POP: The process of deleting an element from the top of stack

Operations on Stack

Algorithm for push

1. If TOP = SIZE – 1, then:a) Display “The stack is in overflow condition”b) Exit

2. TOP = TOP + 13. STACK [TOP] = ITEM4. Exit

Algorithm for pop

1. If TOP < 0, thena) Display “The Stack is empty”b) Exit

2. Else remove the Top most element3. DATA = STACK[TOP]4. TOP = TOP – 15. Exit

Queue

• Queue is a linear data structure that add data items to the rear of it and remove from the front.

• Queue is a first in first out data structure.

Operations on Queue

• PUSH: Insert an element to the queue

• POP: Delete an element from a queue

Operations on Queue

Operations on Queue

Operations on Queue

Algorithm for push

1. Initialize front=0 rear = –12. Input the value to be inserted and assign to variable

“data”3. If (rear >= SIZE)

a) Display “Queue overflow”b) Exit

4. Elsea) Rear = rear +1

5. Q[rear] = data6. Exit

Algorithm for pop

1. If (rear< front)a) Front = 0, rear = –1b) Display “The queue is empty”c) Exit

2. Elsea) Data = Q[front]

3. Front = front +14. Exit

Limitations in Queue

Suppose a queue Q has maximum size 5, say 5 elements pushed and 2 elements popped.

Even though 2 queue cells are free, new elements cannot be pushed.

Circular Queue

• In circular queues the elements Q[0],Q[1],Q[2] .... Q[n – 1] is represented in a circular fashion.

• In a circular queue push and pop operation can be performed on circular.

Circular Queue

Circular Queue

Circular Queue

Algorithm for push in Circular Queue1. Initialize FRONT = – 1; REAR = 12. REAR = (REAR + 1) % SIZE3. If (FRONT is equal to REAR)

a) Display “Queue is full”b) Exit

4. Elsea) Input the value to be inserted and assign to variable “DATA”

5. If (FRONT is equal to – 1)a) FRONT = 0b) REAR = 0

6. Q[REAR] = DATA7. Repeat steps 2 to 5 if we want to insert more elements8. Exit

Algorithm for pop in Circular Queue

1. If (FRONT is equal to – 1)a) Display “Queue is empty”b) Exit

2. Elsea) DATA = Q[FRONT]

3. If (REAR is equal to FRONT)a) FRONT = –1b) REAR = –1

4. Elsea) FRONT = (FRONT +1) % SIZE

5. Repeat the steps 1, 2 and 3 if we want to delete more elements

6. Exit

Linked List

• A linked list is a collection of specially designed data elements called nodes storing data and linked to other nodes.

Representation of Linked List

Representation of Linked List

Advantages of Linked List

• Linked list are dynamic data structure. They can grow or shrink during the execution of a program.

• Efficient memory utilization. Memory is not pre allocated. Memory is allocated whenever it is required. And it is de allocated when it is not needed.

• Insertion and deletion are easier and efficient.

Operations on Linked List

• Creation - linked list is created with one node

• Insertion– At the beginning of the linked list– At the end of the linked list– At any specified position

• Deletion– Beginning of a linked list– End of a linked list– Specified location of the linked list

Operations on Linked List

• Traversing - process of going through all the nodes from one end to another end.

• Searching - Search for a node

• Concatenation - process of appending the second list to the end of the first list.

Operations on Singly Linked List

Operations on Singly Linked List

Algorithm for inserting a node

Insert a Node at the beginning

1. Input DATA to be inserted2. Create a NewNode3. NewNode → DATA = DATA4. If (SATRT equal to NULL)

a) NewNode → Link = NULL5. Else

a) NewNode → Link = START6. START = NewNode7. Exit

Insert a Node at the end

1. Input DATA to be inserted2. Create a NewNode3. NewNode → DATA = DATA4. NewNode → Next = NULL5. If (SATRT equal to NULL)

a) START = NewNode6. Else

a) TEMP = STARTb) While (TEMP → Next not equal to NULL)

i. TEMP = TEMP → Next

c) TEMP → Next = NewNode 7. Exit

Insert a Node at any specified position1. Input DATA and POS to be inserted2. Initialize TEMP = START; and k = 03. Repeat the step 3 while( k is less than POS)

a) TEMP = TEMP Nextb) If (TEMP is equal to NULL)

i. Display “Node in the list less than the position”ii. Exit

c) k = k + 14. Create a New Node5. NewNode → DATA = DATA6. NewNode → Next = TEMP → Next7. TEMP → Next = NewNode8. Exit

Algorithm for deleting a node

Algorithm for deleting a node1. Input the DATA to be deleted2. if ((START → DATA) is equal to DATA)

a) TEMP = STARTb) START = START → Nextc) Set free the node TEMP, which is deletedd) Exit

3. HOLD = START4. while ((HOLD → Next → Next) not equal to NULL))

a) if ((HOLD → NEXT → DATA) equal to DATA)I. TEMP = HOLD → NextII. HOLD → Next = TEMP → NextIII. Set free the node TEMP, which is deletedIV. Exit

b) HOLD = HOLD → Next5. if ((HOLD → next → DATA) == DATA)

a) TEMP = HOLD → Nextb) Set free the node TEMP, which is deletedc) HOLD → Next = NULLd) Exit

6. Display “DATA not found”7. Exit

Algorithm for searching a node

1. Input the DATA to be searched2. Initialize TEMP = START; POS =1;3. Repeat the step 4, 5 and 6 until (TEMP is equal to NULL)4. If (TEMP → DATA is equal to DATA)

a) Display “The data is found at POS”b) Exit

5. TEMP = TEMP → Next6. POS = POS+17. If (TEMP is equal to NULL)

a) Display “The data is not found in the list”8. Exit

Algorithm for display all nodes

1. If (START is equal to NULL)a) Display “The list is Empty”b) Exit

2. Initialize TEMP = START3. Repeat the step 4 and 5 until (TEMP == NULL )4. Display “TEMP → DATA”5. TEMP = TEMP → Next6. Exit

Tree

• Tree is a non-liner data structure.• Used to represent data items possessing

hierarchical relationship.• Very flexible, versatile and powerful.

Tree

Basic Terminologies

• Root - First node in the hierarchical arrangement• Degree of a node - Number of sub trees of a node• Degree of a tree - Maximum degree of a node in a

tree• Levels - Root node is level 0. Rest are 1, 2, 3 and

so on• Depth of a tree - Maximum height of a tree• Leaf node - Node has no child

Binary Tree

• Tree data structure in which each node has at most two child nodes.

• It is possible to having one node as the child or nothing.

• Child nodes are defined as Left and Right.

Binary tree

Strictly binary tree

• Every non leaf has non-empty left and right sub trees.

• Strictly binary tree with n leaves always contains 2n - 1 nodes.

Expression tree

E = ( a + b ) / ( (c - d ) * e )

Left skewed and Right skewed Trees

Left Skewed Tree Right Skewed Tree

Complete binary tree

• A complete binary tree is a strictly binary tree, where all the leaves are at same level.

• A binary tree of depth d, and d > 0, has 2d - 1 nodes in it.

Binary Tree Representation

• Sequential representation using arrays• Linked list representation

Array representation

Father of a node having index n:

= (n – 1) / 2= 3 – 1 / 2= 2 / 2= 1

Array representation

Left child of a node having index n:

= (2n +1)= 2*2 + 1= 4 + 1= 5

Array representation

Right child of a node having array index n:

= (2n + 2)= 2*1 + 2= 4

Array representation

If the left child is at array index n, then its right brother is at (n+1)

Array representation

Since there is no left child for node C is vacant. Eventhough memory is allocated for A[5] it is not used, so wasted unnecessarily.

Linked list representation

In linked list, every element is represented as nodes. A node consists of three fields such as :

• Left Child (LChild)• Information of the Node (Info)• Right Child (RChild)

Linked list representation

Operations on Binary Tree• Create an empty binary tree• Traversing binary tree• Inserting an new node• Deleting a node• Searching for a node• Copying the mirror image of a tree• Determining total no: of nodes• Determine the total no: non-leaf Nodes• Find the smallest element in a Node• Finding the largest element• Find the Height of the tree• Finding the Father/Left Child/Right Child/Brother of an

arbitrary node

Traversing binary tree

1. Pre Order Traversal (Node-left-right)2. In order Traversal (Left-node-right)3. Post Order Traversal (Left-right-node)

Pre Order Traversal

1. Visit the root node2. Traverse the left sub tree in preorder3. Traverse the right sub tree in preorder

Pre Order Traversal

The preorder traversal of a binary tree:A, B, D, E, H, I, C, F, G, J

Pre Order Traversal recursively

void preorder (Node * Root){

If (Root != NULL){

printf (“%d\n”,Root → Info);preorder(Root → L child);preorder(Root → R child);

}}

In Order Traversal

1. Traverse the left sub tree in order2. Visit the root node3. Traverse the right sub tree in order

In Order Traversal

The in order traversal of a binary tree:D, B, H, E, I, A, F, C, J, G

In Order Traversal recursively

void inorder (NODE *Root){

If (Root != NULL){

inorder(Root → L child);printf (“%d\n”,Root → info);inorder(Root → R child);

}}

Post Order Traversal

1. Traverse the left sub tree in post order2. Traverse the right sub tree in post order3. Visit the root node

Post Order Traversal

The post order traversal of a binary tree:D, H, I, E, B, F, J, G, C, A

Post Order Traversal recursively

void postorder (NODE *Root){

If (Root != NULL){

postorder(Root → Lchild);postorder(Root → Rchild);printf (“%d\n”,Root info);

}}

Binary Search Tree

A Binary Search tree satisfies the following properties

• Every node has a value and all the values are unique.

• Left child or left sub tree value is less than the value of the root.

• Right child or right sub tree value is larger than the value of the root.

Binary Search Tree

Operations on BST

• Inserting a node• Searching a node• Deleting a node

Algorithm for inserting a node to BST1. Input the DATA to be pushed and ROOT node of the tree.2. NEWNODE = Create a New Node.3. If (ROOT == NULL)

a) ROOT=NEW NODE4. Else If (DATA < ROOT → Info)

a) ROOT = ROOT → Lchildb) GoTo Step 4

5. Else If (DATA > ROOT → Info)a) ROOT = ROOT → Rchildb) GoTo Step 4

6. If (DATA < ROOT → Info)a) ROOT → LChild = NEWNODE

7. Else If (DATA > ROOT → Info)a) ROOT → RChild = NEWNODE

8. Elsea) Display (“DUPLICATE NODE”)b) EXIT

9. NEW NODE → Info = DATA10. NEW NODE → LChild = NULL11. NEW NODE → RChild = NULL12. EXIT

Algorithm for searching a node in BST1. Input the DATA to be searched and assign the address of the root

node to ROOT.2. If (DATA == ROOT → Info)

a) Display “The DATA exist in the tree”b) GoTo Step 6

3. If (ROOT == NULL)a) Display “The DATA does not exist”b) GoTo Step 6

4. If(DATA > ROOT→Info)a) ROOT = ROOT→RChildb) GoTo Step 2

5. If(DATA < ROOT→Info)a) ROOT = ROOT→Lchildb) GoTo Step 2

6. Exit

Deleting a node on BST

Special cases

• The node to be deleted has no children• The node has exactly one child • The node has two children

The node to be deleted has no children

If N has no children then simply delete the node and place its parent node by the NULL pointer.

The node to be deleted has no children

5

3 18

41

5

3 18

4

1 2

The node has exactly one child

1. If it is a right child, then find the smallest element from the corresponding right sub tree.

2. Then replace the smallest node information with the deleted node.

3. If N has a left child, find the largest element from the corresponding left sub tree.

4. Then replace the largest node information with the deleted node.

The node has exactly one child 5

2 18

3-4 21

19 25

5

2 18

3-4 21

19 25

1 2

3

5

2 19

3-4 21

25

The node has two children

1. Use the in order successor of the node to be deleted. In order successor is the left most child of it’s right sub tree.

2. Then in order successor replace the node value and then node is deleted.

3. Else if no right sub tree exist, replace the node to be deleted with it’s left child.

The node has two children5

2

3-4

12

9 21

19 25

5

2

3-4

12

9 21

19 25

5

2

3-4

19

9 21

25

1 2

3

Algorithm for deleting a node on BST1. Find the location NODE of the DATA to be deleted.2. If (NODE = NULL)

a) Display “DATA is not in tree”b) Exit

3. If(NODE → Lchild = NULL)a) LOC = NODEb) NODE = NODE → RChild

4. If(NODE → RChild= =NULL)a) LOC = NODEb) NODE = NODE → LChild

5. If((NODE → Lchild not equal to NULL) && (NODE → Rchild not equal to NULL))a) LOC = NODE → RChild

6. While(LOC → Lchild not equal to NULL)a) LOC = LOC → Lchild

7. LOC → Lchild = NODE → Lchild8. LOC → RChild= NODE → RChild9. Exit

Graph

• Graph is an another nonlinear data structure.• Applied in subjects like geography, engineering

and solving games and puzzles.

Graph

A graph consist of• Set of vertices V (nodes).• Set of edges E.

Graph

V = {v1, v2, v3, v4......}E = {e1, e2, e3......cm}E = {(v1, v2) (v2, v3) (v1, v3) (v3, v4),(v3, v5) (v5, v6)}

Directed graph

Represented geometrically as a set of marked vertices V with a set of edges E between pairs of vertices

Directed graph

G = {a, b, c, d }, {(a, b), (a, d), (d, b), (d, d), (c, c)}

Directed graphIn edge (a, b)

Vertex a is called the initial vertexVertex b is called the terminal vertex

Directed graphIf an edge that is incident from and into the same vertex (d, d) (c, c) called a loop.

Directed graphIf a vertex has no edge incident with it, it is an isolated vertex. ( c )

Undirected graph

Represented geometrically as a set of marked vertices V with a set of Edges E between the vertices.

Isomorphic graph

If there is a one-to-one correspondence between their vertices it is an isomorphic graph

Degree of vertex

The number of edges incident on a vertex is its degree.degree (a) = 3

Weighted graphIf every edge and/or vertices assigned with some weight or value it is called weighted graphG = (V, E, WE, WV)

N NegamboC ColomboK KandyM Matara

Disconnected graph

Connected graph exist a path from any vertex to any other vertex, otherwise disconnected

Disconnected graph Connected graph

Complete graph

If there is a path from every vertex to every other vertex it is a complete (fully connected) graph

Paths in directed graphs• An elementary path does not meet the same

vertex twice.• A simple path does not meet the same edges

twice.

Paths in directed graphs• (e1, e3, e4, e5, e6, e7, e8) is an elementary path.• (e1, e3, e4, e5, e6, e7, e8, e11, e12) is a simple

path

Representation of a graph

• Sequential representation using adjacent• Linked representation using linked list

Adjacency matrix representation

Adjacency matrix representation

Adjacency matrix representation

Linked list representation

Linked list representation

Operations on graph

• Creating a graph• Searching and deleting from a graph• Traversing a graph

Creating a graph

1. Input the total number of vertices in the graph, say n.2. Allocate the memory dynamically for the vertices to

store in list array.3. Input the first vertex and the vertices through which

it has edge(s) by linking the node from list array through nodes.

4. Repeat the process by incrementing the list array to add other vertices and edges.

5. Exit.

Searching and deleting from a graph

1. Input an edge to be searched2. Search for an initial vertex of edge in list arrays by

incrementing the array index.3. Once it is found, search through the link list for

the terminal vertex of the edge.4. If found display “the edge is present in the graph”.5. Then delete the node where the terminal vertex

is found and rearrange the link list.6. Exit

Traversing a graph

• Breadth First Traversal (BFT)• Depth First Traversal (DFT)

Breadth First Traversal (BFT)

• The aim of breadth first traversal is to traverse the graph as close as possible to the root node (considered as the start)

• Queue is used implementation of BFT

Breadth First Traversal (BFT) Algorithm

1. Input the vertices of the graph and its edges 2. Input the source vertex and assign it to the variable

S.3. Add the source vertex to the queue.4. Repeat the steps 5 and 6 until the queue is empty5. Pop the front element of the queue and display it as

visited.6. Push the vertices, which is neighbor to just, popped

element, if it is not in the queue and displayed 7. Exit.

Breadth First Traversal (BFT)

Breadth First Traversal (BFT)

Display: A

Breadth First Traversal (BFT)

Display: A, B, C

Breadth First Traversal (BFT)

Display: A, B, C, D, E

Breadth First Traversal (BFT)

Display: A, B, C, D, E, F, G

Breadth First Traversal (BFT)

Display: A, B, C, D, E, F, G, H

Depth First Traversal (DFT)

• The aim of DFT algorithm is to traverse the graph in such a way that is tries to go so far from the source (start) node.

• Stack is used in the implementation of the DFT.

Depth First Traversal (DFT) Algorithm

1. Input the vertices and edges of the graph.2. Input the source vertex and assign it to the variable

S.3. Push the source vertex to the stack.4. Repeat the steps 5 and 6 until the stack is empty.5. Pop the top element of the stack and display it.6. Push the vertices which is neighbor to just popped

element, if it is not in the queue and displayed.7. Exit.

Depth First Traversal (DFT)

I I GH

Display: I, H, E, F, D, G

GH

GE

GE

GD

GD

G

F FD

G

The End

http://twitter.com/rasansmn

Recommended