266
Certificate in C/C++ Programming Rasan Samarasinghe ESOFT Computer Studies (pvt) Ltd. No 68/1, Main Street, Pallegama, Embilipitiya.

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

Embed Size (px)

Citation preview

Page 1: Esoft Metro Campus - Certificate in c / c++ programming

Certificate in C/C++ Programming

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

Page 2: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 3: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 4: Esoft Metro Campus - Certificate in c / c++ programming

What you can create with C?

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

Page 5: Esoft Metro Campus - Certificate in c / c++ programming

What you need to program with C

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

Page 6: Esoft Metro Campus - Certificate in c / c++ programming

1. Structure of a Program

Page 7: Esoft Metro Campus - Certificate in c / c++ programming

C Hello World Example

#include <stdio.h>

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

main.c

Page 8: Esoft Metro Campus - Certificate in c / c++ programming

C Hello World Example

A C program basically consists of:

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

Page 9: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 10: Esoft Metro Campus - Certificate in c / c++ programming

Whitespaces

Whitespaces are used to separate tokens.

• Blanks• Tabs• Newline character• Comments

Page 11: Esoft Metro Campus - Certificate in c / c++ programming

Semicolon

Each individual statement must be ended with a semicolon

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

Page 12: Esoft Metro Campus - Certificate in c / c++ programming

Comments

Helping text in your program and ignored by the compiler

//this is a single line comment

/* This is a multilinecomment */

Page 13: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 14: Esoft Metro Campus - Certificate in c / c++ programming

keywords

These reserved words are not allowed to use as identifier names

Page 15: Esoft Metro Campus - Certificate in c / c++ programming

2. Variables & Data types

Page 16: Esoft Metro Campus - Certificate in c / c++ programming

Type classification in C

Page 17: Esoft Metro Campus - Certificate in c / c++ programming

Integer types

Page 18: Esoft Metro Campus - Certificate in c / c++ programming

Floating point types

Page 19: Esoft Metro Campus - Certificate in c / c++ programming

Void types

Page 20: Esoft Metro Campus - Certificate in c / c++ programming

Variables

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

Page 21: Esoft Metro Campus - Certificate in c / c++ programming

Variable definition in C

Variable definitiontype variable_list;

Variable definition and initializationtype variable_name = value;

Page 22: Esoft Metro Campus - Certificate in c / c++ programming

Variable declaration

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

extern type variable_list;

Page 23: Esoft Metro Campus - Certificate in c / c++ programming

3. Constants

Page 24: Esoft Metro Campus - Certificate in c / c++ programming

Constants

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

• These fixed values are also called literals.

Page 25: Esoft Metro Campus - Certificate in c / c++ programming

Literals

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

Page 26: Esoft Metro Campus - Certificate in c / c++ programming

Defining Constants

• Using #define preprocessor. • Using const keyword.

Page 27: Esoft Metro Campus - Certificate in c / c++ programming

Using #define preprocessor

Syntax:#define identifier value

Ex:#define PI 3.14

Page 28: Esoft Metro Campus - Certificate in c / c++ programming

Using const keyword

Syntax:const type variable = value;

Ex:const int LENGTH = 10;

Page 29: Esoft Metro Campus - Certificate in c / c++ programming

4. Operators

Page 30: Esoft Metro Campus - Certificate in c / c++ programming

Arithmetic Operators

A = 10, B = 20

Page 31: Esoft Metro Campus - Certificate in c / c++ programming

Comparison OperatorsA = 10, B = 20

Page 32: Esoft Metro Campus - Certificate in c / c++ programming

Logical Operators

A = 1, B = 0

Page 33: Esoft Metro Campus - Certificate in c / c++ programming

Bitwise OperatorsA = 60, B = 13

Page 34: Esoft Metro Campus - Certificate in c / c++ programming

Truth table

Page 35: Esoft Metro Campus - Certificate in c / c++ programming

Bitwise Operators

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

A = 60, B = 13

Page 36: Esoft Metro Campus - Certificate in c / c++ programming

Assignment Operators

Page 37: Esoft Metro Campus - Certificate in c / c++ programming

Misc Operators

Page 38: Esoft Metro Campus - Certificate in c / c++ programming

Operators Precedence in C

Page 39: Esoft Metro Campus - Certificate in c / c++ programming

5. Basic Input/output

Page 40: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 41: Esoft Metro Campus - Certificate in c / c++ programming

putchar() function

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

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

Page 42: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 43: Esoft Metro Campus - Certificate in c / c++ programming

puts() function

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

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

Page 44: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 45: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 46: Esoft Metro Campus - Certificate in c / c++ programming

6. Control Structures

Page 47: Esoft Metro Campus - Certificate in c / c++ programming

If Statement

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

Boolean expression is true}

Boolean Expression

Statements

True

False

Page 48: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 49: Esoft Metro Campus - Certificate in c / c++ programming

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.}

Page 50: Esoft Metro Campus - Certificate in c / c++ programming

If… Else if… Else Statement

Boolean expression 1

False

Statements

Boolean expression 2

Boolean expression 3

Statements

Statements

False

False

Statements

True

True

True

Page 51: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 52: Esoft Metro Campus - Certificate in c / c++ programming

Switch Statement

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

Page 53: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 54: Esoft Metro Campus - Certificate in c / c++ programming

While Loop

while(Boolean_expression){ //Statements}

Boolean Expression

Statements

True

False

Page 55: Esoft Metro Campus - Certificate in c / c++ programming

Do While Loop

do{ //Statements}while(Boolean_expression);

Boolean Expression

Statements

True

False

Page 56: Esoft Metro Campus - Certificate in c / c++ programming

For Loop

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

Boolean Expression

Statements

True

False

Update

Initialization

Page 57: Esoft Metro Campus - Certificate in c / c++ programming

break Statement

Boolean Expression

Statements

True

False

break

Page 58: Esoft Metro Campus - Certificate in c / c++ programming

continue Statement

Boolean Expression

Statements

True

False

continue

Page 59: Esoft Metro Campus - Certificate in c / c++ programming

Nested Loop

Boolean Expression

True

False

Boolean Expression

Statements

True

False

Page 60: Esoft Metro Campus - Certificate in c / c++ programming

7. Functions

Page 61: Esoft Metro Campus - Certificate in c / c++ programming

Functions

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

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

Page 62: Esoft Metro Campus - Certificate in c / c++ programming

Defining a Function

return_type function_name( parameter list ) { body of the function

}

Page 63: Esoft Metro Campus - Certificate in c / c++ programming

Example

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

Page 64: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 65: Esoft Metro Campus - Certificate in c / c++ programming

Calling a Function

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

Page 66: Esoft Metro Campus - Certificate in c / c++ programming

Function Arguments

• Function call by value • Function call by reference

Page 67: Esoft Metro Campus - Certificate in c / c++ programming

Function call by value

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

Page 68: Esoft Metro Campus - Certificate in c / c++ programming

Function call by value

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

Page 69: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 70: Esoft Metro Campus - Certificate in c / c++ programming

Function call by reference

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

Page 71: Esoft Metro Campus - Certificate in c / c++ programming

Function call by reference

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

Page 72: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 73: Esoft Metro Campus - Certificate in c / c++ programming

8. Arrays

Page 74: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 75: Esoft Metro Campus - Certificate in c / c++ programming

Single dimensional arrays

Page 76: Esoft Metro Campus - Certificate in c / c++ programming

Declaring Arrays

type arrayName [ arraySize ];

Ex:

double balance[10];

Page 77: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 78: Esoft Metro Campus - Certificate in c / c++ programming

Accessing Array Elements

An element is accessed by indexing the array name.

double salary = balance[0];

Page 79: Esoft Metro Campus - Certificate in c / c++ programming

Multi-dimensional Arrays

C programming language allows multidimensional arrays.

Here is the general form of a multidimensional array declaration:

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

Page 80: Esoft Metro Campus - Certificate in c / c++ programming

Use of Multi-dimensional Arrays

Page 81: Esoft Metro Campus - Certificate in c / c++ programming

Two-Dimensional Arrays

Declaring a two dimensional array of size x, y

type arrayName [ x ][ y ];

Page 82: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 83: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 84: Esoft Metro Campus - Certificate in c / c++ programming

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[]) { }

Page 85: Esoft Metro Campus - Certificate in c / c++ programming

Return array from function

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

Page 86: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 87: Esoft Metro Campus - Certificate in c / c++ programming

9. Character Sequences

Page 88: Esoft Metro Campus - Certificate in c / c++ programming

C Strings

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

Page 89: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 90: Esoft Metro Campus - Certificate in c / c++ programming

String functions in string.h

Page 91: Esoft Metro Campus - Certificate in c / c++ programming

10. Pointers and Dynamic Memory

Page 92: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 93: Esoft Metro Campus - Certificate in c / c++ programming

What Are Pointers?

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

pointer variable declaration:

type *var-name;

Page 94: Esoft Metro Campus - Certificate in c / c++ programming

What Are Pointers?

Page 95: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 96: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 97: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 98: Esoft Metro Campus - Certificate in c / c++ programming

NULL Pointers in C

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

Page 99: Esoft Metro Campus - Certificate in c / c++ programming

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++; }

Page 100: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 101: Esoft Metro Campus - Certificate in c / c++ programming

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++; }

Page 102: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 103: Esoft Metro Campus - Certificate in c / c++ programming

Pointer to Pointer

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

pointer.

Page 104: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 105: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 106: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 107: Esoft Metro Campus - Certificate in c / c++ programming

Memory Management

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

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

Page 108: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 109: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 110: Esoft Metro Campus - Certificate in c / c++ programming

11. Unions

Page 111: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 112: Esoft Metro Campus - Certificate in c / c++ programming

Defining a Union

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

Page 113: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 114: Esoft Metro Campus - Certificate in c / c++ programming

Assigning values to Union

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

Page 115: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 116: Esoft Metro Campus - Certificate in c / c++ programming

12. Other Data Types

Page 117: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 118: Esoft Metro Campus - Certificate in c / c++ programming

Defining a Structure

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

Page 119: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 120: Esoft Metro Campus - Certificate in c / c++ programming

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;

Page 121: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 122: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 123: Esoft Metro Campus - Certificate in c / c++ programming

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;

Page 124: Esoft Metro Campus - Certificate in c / c++ programming

Bit Fields

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

Page 125: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 126: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 127: Esoft Metro Campus - Certificate in c / c++ programming

13. Input/output with files

Page 128: Esoft Metro Campus - Certificate in c / c++ programming

Opening Files

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

Page 129: Esoft Metro Campus - Certificate in c / c++ programming

File access modes

Page 130: Esoft Metro Campus - Certificate in c / c++ programming

Closing a File

int fclose( FILE *fp );

Page 131: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 132: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 133: Esoft Metro Campus - Certificate in c / c++ programming

14. Searching

Page 134: Esoft Metro Campus - Certificate in c / c++ programming

Searching Algorithms

• Linear Search• Binary Search

Page 135: Esoft Metro Campus - Certificate in c / c++ programming

Linear Search

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

Page 136: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 137: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 138: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 139: Esoft Metro Campus - Certificate in c / c++ programming

15. Sorting

Page 140: Esoft Metro Campus - Certificate in c / c++ programming

Sorting Algorithms

• Bubble Sort• Selection Sort• Insertion Sort

Page 141: Esoft Metro Campus - Certificate in c / c++ programming

Bubble Sort

Page 142: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 143: Esoft Metro Campus - Certificate in c / c++ programming

Selection Sort

Page 144: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 145: Esoft Metro Campus - Certificate in c / c++ programming

Insertion Sort

Page 146: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 147: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 148: Esoft Metro Campus - Certificate in c / c++ programming

16. Introduction to data structures

Page 149: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 150: Esoft Metro Campus - Certificate in c / c++ programming

An introduction to Data Structures

Organized Data + Operations = Data Structure

Algorithm + Data Structure = Computer Program

Page 151: Esoft Metro Campus - Certificate in c / c++ programming

Classifications of data structures

Page 152: Esoft Metro Campus - Certificate in c / c++ programming

Frequently used data structures

• Stack• Queue• Linked List• Tree• Graph

Page 153: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 154: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 155: Esoft Metro Campus - Certificate in c / c++ programming

Operations on Stack

Page 156: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 157: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 158: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 159: Esoft Metro Campus - Certificate in c / c++ programming

Operations on Queue

• PUSH: Insert an element to the queue

• POP: Delete an element from a queue

Page 160: Esoft Metro Campus - Certificate in c / c++ programming

Operations on Queue

Page 161: Esoft Metro Campus - Certificate in c / c++ programming

Operations on Queue

Page 162: Esoft Metro Campus - Certificate in c / c++ programming

Operations on Queue

Page 163: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 164: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 165: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 166: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 167: Esoft Metro Campus - Certificate in c / c++ programming

Circular Queue

Page 168: Esoft Metro Campus - Certificate in c / c++ programming

Circular Queue

Page 169: Esoft Metro Campus - Certificate in c / c++ programming

Circular Queue

Page 170: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 171: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 172: Esoft Metro Campus - Certificate in c / c++ programming

Linked List

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

Page 173: Esoft Metro Campus - Certificate in c / c++ programming

Representation of Linked List

Page 174: Esoft Metro Campus - Certificate in c / c++ programming

Representation of Linked List

Page 175: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 176: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 177: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 178: Esoft Metro Campus - Certificate in c / c++ programming

Operations on Singly Linked List

Page 179: Esoft Metro Campus - Certificate in c / c++ programming

Operations on Singly Linked List

Page 180: Esoft Metro Campus - Certificate in c / c++ programming

Algorithm for inserting a node

Page 181: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 182: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 183: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 184: Esoft Metro Campus - Certificate in c / c++ programming

Algorithm for deleting a node

Page 185: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 186: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 187: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 188: Esoft Metro Campus - Certificate in c / c++ programming

Tree

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

hierarchical relationship.• Very flexible, versatile and powerful.

Page 189: Esoft Metro Campus - Certificate in c / c++ programming

Tree

Page 190: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 191: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 192: Esoft Metro Campus - Certificate in c / c++ programming

Binary tree

Page 193: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 194: Esoft Metro Campus - Certificate in c / c++ programming

Expression tree

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

Page 195: Esoft Metro Campus - Certificate in c / c++ programming

Left skewed and Right skewed Trees

Left Skewed Tree Right Skewed Tree

Page 196: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 197: Esoft Metro Campus - Certificate in c / c++ programming

Binary Tree Representation

• Sequential representation using arrays• Linked list representation

Page 198: Esoft Metro Campus - Certificate in c / c++ programming

Array representation

Father of a node having index n:

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

Page 199: Esoft Metro Campus - Certificate in c / c++ programming

Array representation

Left child of a node having index n:

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

Page 200: Esoft Metro Campus - Certificate in c / c++ programming

Array representation

Right child of a node having array index n:

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

Page 201: Esoft Metro Campus - Certificate in c / c++ programming

Array representation

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

Page 202: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 203: Esoft Metro Campus - Certificate in c / c++ programming

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)

Page 204: Esoft Metro Campus - Certificate in c / c++ programming

Linked list representation

Page 205: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 206: Esoft Metro Campus - Certificate in c / c++ programming

Traversing binary tree

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

Page 207: Esoft Metro Campus - Certificate in c / c++ programming

Pre Order Traversal

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

Page 208: Esoft Metro Campus - Certificate in c / c++ programming

Pre Order Traversal

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

Page 209: Esoft Metro Campus - Certificate in c / c++ programming

Pre Order Traversal recursively

void preorder (Node * Root){

If (Root != NULL){

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

}}

Page 210: Esoft Metro Campus - Certificate in c / c++ programming

In Order Traversal

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

Page 211: Esoft Metro Campus - Certificate in c / c++ programming

In Order Traversal

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

Page 212: Esoft Metro Campus - Certificate in c / c++ programming

In Order Traversal recursively

void inorder (NODE *Root){

If (Root != NULL){

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

}}

Page 213: Esoft Metro Campus - Certificate in c / c++ programming

Post Order Traversal

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

Page 214: Esoft Metro Campus - Certificate in c / c++ programming

Post Order Traversal

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

Page 215: Esoft Metro Campus - Certificate in c / c++ programming

Post Order Traversal recursively

void postorder (NODE *Root){

If (Root != NULL){

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

}}

Page 216: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 217: Esoft Metro Campus - Certificate in c / c++ programming

Binary Search Tree

Page 218: Esoft Metro Campus - Certificate in c / c++ programming

Operations on BST

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

Page 219: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 220: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 221: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 222: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 223: Esoft Metro Campus - Certificate in c / c++ programming

The node to be deleted has no children

5

3 18

41

5

3 18

4

1 2

Page 224: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 225: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 226: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 227: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 228: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 229: Esoft Metro Campus - Certificate in c / c++ programming

Graph

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

and solving games and puzzles.

Page 230: Esoft Metro Campus - Certificate in c / c++ programming

Graph

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

Page 231: Esoft Metro Campus - Certificate in c / c++ programming

Graph

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

Page 232: Esoft Metro Campus - Certificate in c / c++ programming

Directed graph

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

Page 233: Esoft Metro Campus - Certificate in c / c++ programming

Directed graph

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

Page 234: Esoft Metro Campus - Certificate in c / c++ programming

Directed graphIn edge (a, b)

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

Page 235: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 236: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 237: Esoft Metro Campus - Certificate in c / c++ programming

Undirected graph

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

Page 238: Esoft Metro Campus - Certificate in c / c++ programming

Isomorphic graph

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

Page 239: Esoft Metro Campus - Certificate in c / c++ programming

Degree of vertex

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

Page 240: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 241: Esoft Metro Campus - Certificate in c / c++ programming

Disconnected graph

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

Disconnected graph Connected graph

Page 242: Esoft Metro Campus - Certificate in c / c++ programming

Complete graph

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

Page 243: Esoft Metro Campus - Certificate in c / c++ programming

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

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

twice.

Page 244: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 245: Esoft Metro Campus - Certificate in c / c++ programming

Representation of a graph

• Sequential representation using adjacent• Linked representation using linked list

Page 246: Esoft Metro Campus - Certificate in c / c++ programming

Adjacency matrix representation

Page 247: Esoft Metro Campus - Certificate in c / c++ programming

Adjacency matrix representation

Page 248: Esoft Metro Campus - Certificate in c / c++ programming

Adjacency matrix representation

Page 249: Esoft Metro Campus - Certificate in c / c++ programming

Linked list representation

Page 250: Esoft Metro Campus - Certificate in c / c++ programming

Linked list representation

Page 251: Esoft Metro Campus - Certificate in c / c++ programming

Operations on graph

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

Page 252: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 253: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 254: Esoft Metro Campus - Certificate in c / c++ programming

Traversing a graph

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

Page 255: Esoft Metro Campus - Certificate in c / c++ programming

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

Page 256: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 257: Esoft Metro Campus - Certificate in c / c++ programming

Breadth First Traversal (BFT)

Page 258: Esoft Metro Campus - Certificate in c / c++ programming

Breadth First Traversal (BFT)

Display: A

Page 259: Esoft Metro Campus - Certificate in c / c++ programming

Breadth First Traversal (BFT)

Display: A, B, C

Page 260: Esoft Metro Campus - Certificate in c / c++ programming

Breadth First Traversal (BFT)

Display: A, B, C, D, E

Page 261: Esoft Metro Campus - Certificate in c / c++ programming

Breadth First Traversal (BFT)

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

Page 262: Esoft Metro Campus - Certificate in c / c++ programming

Breadth First Traversal (BFT)

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

Page 263: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 264: Esoft Metro Campus - Certificate in c / c++ programming

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.

Page 265: Esoft Metro Campus - Certificate in c / c++ programming

Depth First Traversal (DFT)

I I GH

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

GH

GE

GE

GD

GD

G

F FD

G

Page 266: Esoft Metro Campus - Certificate in c / c++ programming

The End

http://twitter.com/rasansmn