SlideShare a Scribd company logo
1 of 266
Certificate in C/C++ Programming
Rasan Samarasinghe
ESOFT 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 multiline
comment */
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 definition
type variable_list;
Variable definition and initialization
type 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 Operators
A = 10, B = 20
Logical Operators
A = 1, B = 0
Bitwise Operators
A = 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
Statements
Boolean
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 : %dn", a );
printf("Before swap, value of b : %dn", b );
swap(a, b);
printf("After swap, value of a : %dn", a );
printf("After swap, value of b : %dn", 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 : %dn", a );
printf("Before swap, value of b : %dn", b );
swap(&a, &b);
printf("After swap, value of a : %dn", a );
printf("After swap, value of b : %dn", 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 pointer
void myFunction(int *param) { }
Formal parameters as a sized array
void myFunction(int param[10]) { }
Formal parameters as an unsized array
void 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 pointern");
for(i=0; i<=4; i++){
printf("balance[%d] = %.2f n", i, *(ptr+i));
}
printf("Array values using balancen");
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: %xn", &var1 );
printf("Address of var2 variable: %xn", &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: %xn", &var );
printf("Address stored in ip variable: %xn", ip );
printf("Value of *ip variable: %dn", *ip );
NULL Pointers in C
int *ptr = NULL;
printf("The value of ptr is : %xn", &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] = %xn", i, ptr );
printf("Value of var[%d] = %dn", 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] = %xn", i, ptr );
printf("Value of var[%d] = %dn", 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] = %xn", i, ptr );
printf("Value of var[%d] = %dn", 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] = %dn", 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 = %dn", var );
printf("Value available at *ptr = %dn", *ptr );
printf("Value available at **pptr = %dn", **pptr);
Passing pointers to functions
void getSeconds(long *hours)
{
*hours = *hours * 60 * 60;
return;
}
int main ()
{
long hours;
getSeconds( &hours );
printf("Number of seconds: %dn", hours );
return 0;
}
Return pointer from functions
int * 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]) : %dn", 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 memoryn");
}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 dynamically
description = realloc( description, 100 * sizeof(char) ); // resizing memory
if(description == NULL){
printf("unable to allocate required memoryn");
}else{
strcpy(description, "my name is khan, and i'm not a terrorist");
}
printf("description = %s", description);
free(description); // releasing memory
return 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 : %dn",
sizeof(data));
printf( "data.i : %dn", data.i);
printf( "data.f : %fn", data.f);
printf( "data.str : %sn", 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 : %sn", Book1.title);
printf( "Book 1 author : %sn", Book1.author);
printf( "Book 1 category : %sn", Book1.category);
printf( "Book 1 book_id : %dn", Book1.book_id);
Structures as Function Arguments
// function definition
void printBook( struct Books book )
{
printf( "Book title : %sn", book.title);
printf( "Book author : %sn", book.author);
printf( "Book category : %sn", book.category);
printf( "Book book_id : %dn", book.book_id);
}
// calling function
printBook( Book1 );
Pointers to Structures
//define pointer to structure
struct Books *struct_pointer;
//store the address of a structure variable in the pointer
struct_pointer = &Book1;
//access the members of a structure
struct_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 : %dn", sizeof(status));
printf( "Memory size occupied by status2 : %dn", 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 Search
int 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 Search
int 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 Sort
Data structure Array Array Array
Worst 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 + 1
3. STACK [TOP] = ITEM
4. Exit
Algorithm for pop
1. If TOP < 0, then
a) Display “The Stack is empty”
b) Exit
2. Else remove the Top most element
3. DATA = STACK[TOP]
4. TOP = TOP – 1
5. 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 = –1
2. Input the value to be inserted and assign to
variable “data”
3. If (rear >= SIZE)
a) Display “Queue overflow”
b) Exit
4. Else
a) Rear = rear +1
5. Q[rear] = data
6. Exit
Algorithm for pop
1. If (rear< front)
a) Front = 0, rear = –1
b) Display “The queue is empty”
c) Exit
2. Else
a) Data = Q[front]
3. Front = front +1
4. 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 Queue
1. Initialize FRONT = – 1; REAR = 1
2. REAR = (REAR + 1) % SIZE
3. If (FRONT is equal to REAR)
a) Display “Queue is full”
b) Exit
4. Else
a) Input the value to be inserted and assign to variable
“DATA”
5. If (FRONT is equal to – 1)
a) FRONT = 0
b) REAR = 0
6. Q[REAR] = DATA
7. Repeat steps 2 to 5 if we want to insert more
elements
8. Exit
Algorithm for pop in Circular Queue
1. If (FRONT is equal to – 1)
a) Display “Queue is empty”
b) Exit
2. Else
a) DATA = Q[FRONT]
3. If (REAR is equal to FRONT)
a) FRONT = –1
b) REAR = –1
4. Else
a) 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 inserted
2. Create a NewNode
3. NewNode → DATA = DATA
4. If (SATRT equal to NULL)
a) NewNode → Link = NULL
5. Else
a) NewNode → Link = START
6. START = NewNode
7. Exit
Insert a Node at the end
1. Input DATA to be inserted
2. Create a NewNode
3. NewNode → DATA = DATA
4. NewNode → Next = NULL
5. If (SATRT equal to NULL)
a) START = NewNode
6. Else
a) TEMP = START
b) While (TEMP → Next not equal to NULL)
i. TEMP = TEMP → Next
c) TEMP → Next = NewNode
7. Exit
Insert a Node at any specified position
1. Input DATA and POS to be inserted
2. Initialize TEMP = START; and k = 0
3. Repeat the step 3 while( k is less than POS)
a) TEMP = TEMP  Next
b) If (TEMP is equal to NULL)
i. Display “Node in the list less than the position”
ii. Exit
c) k = k + 1
4. Create a New Node
5. NewNode → DATA = DATA
6. NewNode → Next = TEMP → Next
7. TEMP → Next = NewNode
8. Exit
Algorithm for deleting a node
Algorithm for deleting a node
1. Input the DATA to be deleted
2. if ((START → DATA) is equal to DATA)
a) TEMP = START
b) START = START → Next
c) Set free the node TEMP, which is deleted
d) Exit
3. HOLD = START
4. while ((HOLD → Next → Next) not equal to NULL))
a) if ((HOLD → NEXT → DATA) equal to DATA)
I. TEMP = HOLD → Next
II. HOLD → Next = TEMP → Next
III. Set free the node TEMP, which is deleted
IV. Exit
b) HOLD = HOLD → Next
5. if ((HOLD → next → DATA) == DATA)
a) TEMP = HOLD → Next
b) Set free the node TEMP, which is deleted
c) HOLD → Next = NULL
d) Exit
6. Display “DATA not found”
7. Exit
Algorithm for searching a node
1. Input the DATA to be searched
2. 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 → Next
6. POS = POS+1
7. 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 = START
3. Repeat the step 4 and 5 until (TEMP == NULL )
4. Display “TEMP → DATA”
5. TEMP = TEMP → Next
6. 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. Even
though 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 node
2. Traverse the left sub tree in preorder
3. 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 (“%dn”,Root → Info);
preorder(Root → L child);
preorder(Root → R child);
}
}
In Order Traversal
1. Traverse the left sub tree in order
2. Visit the root node
3. 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 (“%dn”,Root → info);
inorder(Root → R child);
}
}
Post Order Traversal
1. Traverse the left sub tree in post order
2. Traverse the right sub tree in post order
3. 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 (“%dn”,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 BST
1. 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 NODE
4. Else If (DATA < ROOT → Info)
a) ROOT = ROOT → Lchild
b) GoTo Step 4
5. Else If (DATA > ROOT → Info)
a) ROOT = ROOT → Rchild
b) GoTo Step 4
6. If (DATA < ROOT → Info)
a) ROOT → LChild = NEWNODE
7. Else If (DATA > ROOT → Info)
a) ROOT → RChild = NEWNODE
8. Else
a) Display (“DUPLICATE NODE”)
b) EXIT
9. NEW NODE → Info = DATA
10. NEW NODE → LChild = NULL
11. NEW NODE → RChild = NULL
12. EXIT
Algorithm for searching a node in BST
1. 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→RChild
b) GoTo Step 2
5. If(DATA < ROOT→Info)
a) ROOT = ROOT→Lchild
b) 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 children
5
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 BST
1. 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 = NODE
b) NODE = NODE → RChild
4. If(NODE → RChild= =NULL)
a) LOC = NODE
b) 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 → Lchild
8. LOC → RChild= NODE → RChild
9. 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 graph
In edge (a, b)
Vertex a is called the initial vertex
Vertex b is called the terminal vertex
Directed graph
If an edge that is incident from and into the
same vertex (d, d) (c, c) called a loop.
Directed graph
If 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 graph
If every edge and/or vertices assigned with
some weight or value it is called weighted graph
G = (V, E, WE, WV)
N  Negambo
C  Colombo
K  Kandy
M  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 searched
2. 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
empty
5. 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 G
H
Display: I, H, E, F, D, G
G
H
G
E
G
E
G
D
G
D
G
F F
D
G
The End
http://twitter.com/rasansmn

More Related Content

What's hot

DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScriptRasan Samarasinghe
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesRasan Samarasinghe
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpMichael Stal
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stalMichael Stal
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language Mohamed Loey
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5thConnex
 

What's hot (20)

DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Visual c sharp
Visual c sharpVisual c sharp
Visual c sharp
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
C Theory
C TheoryC Theory
C Theory
 
C++ oop
C++ oopC++ oop
C++ oop
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
C++ theory
C++ theoryC++ theory
C++ theory
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
Perl slid
Perl slidPerl slid
Perl slid
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 

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

the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxAnkitaVerma776806
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing TutorialMahira Banu
 
C programming language
C programming languageC programming language
C programming languageAbin Rimal
 
C programming tutorial for Beginner
C programming tutorial for BeginnerC programming tutorial for Beginner
C programming tutorial for Beginnersophoeutsen2
 
unit 1 cpds.pptx
unit 1 cpds.pptxunit 1 cpds.pptx
unit 1 cpds.pptxmadhurij54
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C ProgrammingMOHAMAD NOH AHMAD
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 FocJAYA
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxvanshhans21102005
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)sachindane
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xiiSyed Zaid Irshad
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Functionimtiazalijoono
 
Chapter3
Chapter3Chapter3
Chapter3Kamran
 
C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)indrasir
 

Similar to Esoft Metro Campus - Certificate in c / c++ programming (20)

the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
C
CC
C
 
C language
C languageC language
C language
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing Tutorial
 
C programming language
C programming languageC programming language
C programming language
 
C programming tutorial for Beginner
C programming tutorial for BeginnerC programming tutorial for Beginner
C programming tutorial for Beginner
 
unit 1 cpds.pptx
unit 1 cpds.pptxunit 1 cpds.pptx
unit 1 cpds.pptx
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
 
C programming
C programmingC programming
C programming
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptx
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
 
Unit 2- Module 2.pptx
Unit 2- Module 2.pptxUnit 2- Module 2.pptx
Unit 2- Module 2.pptx
 
Chapter3
Chapter3Chapter3
Chapter3
 
C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)
 
qb unit2 solve eem201.pdf
qb unit2 solve eem201.pdfqb unit2 solve eem201.pdf
qb unit2 solve eem201.pdf
 

More from Rasan Samarasinghe

Managing the under performance in projects.pptx
Managing the under performance in projects.pptxManaging the under performance in projects.pptx
Managing the under performance in projects.pptxRasan Samarasinghe
 
Agile project management with scrum
Agile project management with scrumAgile project management with scrum
Agile project management with scrumRasan Samarasinghe
 
Application of Unified Modelling Language
Application of Unified Modelling LanguageApplication of Unified Modelling Language
Application of Unified Modelling LanguageRasan Samarasinghe
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIRasan Samarasinghe
 
Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...Rasan Samarasinghe
 
Advanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with GitAdvanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with GitRasan Samarasinghe
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationRasan Samarasinghe
 
DIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web DesigningDIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web DesigningRasan Samarasinghe
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesRasan Samarasinghe
 
DISE - Software Testing and Quality Management
DISE - Software Testing and Quality ManagementDISE - Software Testing and Quality Management
DISE - Software Testing and Quality ManagementRasan Samarasinghe
 
DISE - Introduction to Project Management
DISE - Introduction to Project ManagementDISE - Introduction to Project Management
DISE - Introduction to Project ManagementRasan Samarasinghe
 
DISE - Introduction to Software Engineering
DISE - Introduction to Software EngineeringDISE - Introduction to Software Engineering
DISE - Introduction to Software EngineeringRasan Samarasinghe
 
DITEC - Expose yourself to Internet & E-mail (second update)
DITEC - Expose yourself to Internet & E-mail (second update) DITEC - Expose yourself to Internet & E-mail (second update)
DITEC - Expose yourself to Internet & E-mail (second update) Rasan Samarasinghe
 

More from Rasan Samarasinghe (20)

Managing the under performance in projects.pptx
Managing the under performance in projects.pptxManaging the under performance in projects.pptx
Managing the under performance in projects.pptx
 
Agile project management with scrum
Agile project management with scrumAgile project management with scrum
Agile project management with scrum
 
Introduction to Agile
Introduction to AgileIntroduction to Agile
Introduction to Agile
 
IT Introduction (en)
IT Introduction (en)IT Introduction (en)
IT Introduction (en)
 
Application of Unified Modelling Language
Application of Unified Modelling LanguageApplication of Unified Modelling Language
Application of Unified Modelling Language
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
 
Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...
 
Advanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with GitAdvanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with Git
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image Manipulation
 
DIWE - File handling with PHP
DIWE - File handling with PHPDIWE - File handling with PHP
DIWE - File handling with PHP
 
DIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web DesigningDIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web Designing
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia Technologies
 
DISE - Software Testing and Quality Management
DISE - Software Testing and Quality ManagementDISE - Software Testing and Quality Management
DISE - Software Testing and Quality Management
 
DISE - Introduction to Project Management
DISE - Introduction to Project ManagementDISE - Introduction to Project Management
DISE - Introduction to Project Management
 
DISE - Database Concepts
DISE - Database ConceptsDISE - Database Concepts
DISE - Database Concepts
 
DISE - OOAD Using UML
DISE - OOAD Using UMLDISE - OOAD Using UML
DISE - OOAD Using UML
 
DISE - Programming Concepts
DISE - Programming ConceptsDISE - Programming Concepts
DISE - Programming Concepts
 
DISE - Introduction to Software Engineering
DISE - Introduction to Software EngineeringDISE - Introduction to Software Engineering
DISE - Introduction to Software Engineering
 
DITEC - Expose yourself to Internet & E-mail (second update)
DITEC - Expose yourself to Internet & E-mail (second update) DITEC - Expose yourself to Internet & E-mail (second update)
DITEC - Expose yourself to Internet & E-mail (second update)
 
DITEC - E-Commerce & ASP.NET
DITEC - E-Commerce & ASP.NETDITEC - E-Commerce & ASP.NET
DITEC - E-Commerce & ASP.NET
 

Recently uploaded

Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 

Recently uploaded (20)

Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 

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

  • 1. Certificate in C/C++ Programming Rasan Samarasinghe ESOFT Computer Studies (pvt) Ltd. No 68/1, Main Street, Pallegama, Embilipitiya.
  • 2. 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
  • 3. 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.
  • 4. What you can create with C? • Operating Systems • Language Compilers • Assemblers • Text Editors • Print Spoolers • Network Drivers • Modem Programs • Databases • Language Interpreters • Utilities
  • 5. What you need to program with C • C/C++ Compiler • Text Editor • Command Prompt
  • 6. 1. Structure of a Program
  • 7. C Hello World Example #include <stdio.h> int main() { printf("Hello world!"); return 0; } main.c
  • 8. C Hello World Example A C program basically consists of: • Preprocessor Commands • Functions • Variables • Statements & Expressions • Comments
  • 9. 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
  • 10. Whitespaces Whitespaces are used to separate tokens. • Blanks • Tabs • Newline character • Comments
  • 11. Semicolon Each individual statement must be ended with a semicolon printf("Hello world!"); return 0;
  • 12. Comments Helping text in your program and ignored by the compiler //this is a single line comment /* This is a multiline comment */
  • 13. 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.
  • 14. keywords These reserved words are not allowed to use as identifier names
  • 15. 2. Variables & Data types
  • 20. Variables Variables are temporary memory locations in C programs which consisting known or unknown values.
  • 21. Variable definition in C Variable definition type variable_list; Variable definition and initialization type variable_name = value;
  • 22. Variable declaration Provides assurance to the compiler that there is one variable existing with the given type and name. extern type variable_list;
  • 24. Constants • Constants refer to fixed values that the program may not alter during its execution. • These fixed values are also called literals.
  • 25. Literals • Integer literals • Floating-point literals • Character literals • String literals
  • 26. Defining Constants • Using #define preprocessor. • Using const keyword.
  • 27. Using #define preprocessor Syntax: #define identifier value Ex: #define PI 3.14
  • 28. Using const keyword Syntax: const type variable = value; Ex: const int LENGTH = 10;
  • 33. Bitwise Operators A = 60, B = 13
  • 35. Bitwise Operators A = 00111100 B = 00001101 A&B = 00001100 A|B = 00111101 A^B = 00110001 ~A = 11000011 A = 60, B = 13
  • 40. 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();
  • 41. putchar() function int putchar(int c) function puts the passed character on the screen and returns the same character. printf( "You entered: "); putchar(c);
  • 42. 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);
  • 43. puts() function int puts(const char *s) function writes the string s and a trailing newline to stdout. printf("You entered: "); puts(str);
  • 44. 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);
  • 45. 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);
  • 47. If Statement if(Boolean_expression){ //Statements will execute if the Boolean expression is true } Boolean Expression Statements True False
  • 48. 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
  • 49. 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. }
  • 50. If… Else if… Else Statement Boolean expression 1 False Statements Boolean expression 2 Boolean expression 3 Statements Statements False False Statements True True True
  • 51. 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 Statements Boolean Expression 2 True False
  • 52. Switch Statement switch (value){ case constant: //statements break; case constant: //statements break; default: //statements }
  • 53. 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.
  • 56. For Loop for(initialization; Boolean_expression; update){ //Statements } Boolean Expression Statements True False Update Initialization
  • 61. Functions • Function is a group of statements that together perform a task. • Every C program has at least one function, which is main()
  • 62. Defining a Function return_type function_name( parameter list ) { body of the function }
  • 63. Example int max(int num1, int num2) { int result; if (num1 > num2){ result = num1; }else{ result = num2; } return result; }
  • 64. 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);
  • 65. Calling a Function int a = 100; int b = 200; int ret; /* calling a function to get max value */ ret = max(a, b);
  • 66. Function Arguments • Function call by value • Function call by reference
  • 67. Function call by value passing arguments to a function copies the actual value of an argument into the formal parameter of the function.
  • 68. Function call by value void swap(int x, int y) { int temp; temp = x; x = y; y = temp; return; }
  • 69. 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 : %dn", a ); printf("Before swap, value of b : %dn", b ); swap(a, b); printf("After swap, value of a : %dn", a ); printf("After swap, value of b : %dn", b ); return 0; }
  • 70. Function call by reference passing arguments to a function copies the address of an argument into the formal parameter.
  • 71. Function call by reference void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; return; }
  • 72. 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 : %dn", a ); printf("Before swap, value of b : %dn", b ); swap(&a, &b); printf("After swap, value of a : %dn", a ); printf("After swap, value of b : %dn", b ); return 0; }
  • 74. 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.
  • 76. Declaring Arrays type arrayName [ arraySize ]; Ex: double balance[10];
  • 77. 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};
  • 78. Accessing Array Elements An element is accessed by indexing the array name. double salary = balance[0];
  • 79. Multi-dimensional Arrays C programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration: type name[size1][size2]...[sizeN];
  • 81. Two-Dimensional Arrays Declaring a two dimensional array of size x, y type arrayName [ x ][ y ];
  • 82. 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};
  • 83. 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];
  • 84. Passing Arrays as Function Arguments Formal parameters as a pointer void myFunction(int *param) { } Formal parameters as a sized array void myFunction(int param[10]) { } Formal parameters as an unsized array void myFunction(int param[]) { }
  • 85. Return array from function int * myFunction() { static int demo[5] = {20, 40, 50, 10, 60}; return demo; }
  • 86. 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 pointern"); for(i=0; i<=4; i++){ printf("balance[%d] = %.2f n", i, *(ptr+i)); } printf("Array values using balancen"); for(i=0; i<=4; i++){ printf("balance[%d] = %.2f n", i, *(balance+i)); }
  • 88. C Strings The string in C programming language is actually a one-dimensional array of characters which is terminated by a null character '0'.
  • 89. 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";
  • 91. 10. Pointers and Dynamic Memory
  • 92. 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: %xn", &var1 ); printf("Address of var2 variable: %xn", &var2 );
  • 93. What Are Pointers? A pointer is a variable whose value is the address of another variable. pointer variable declaration: type *var-name;
  • 95. 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
  • 96. 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.
  • 97. How to use Pointers? int var = 20; int *ip; ip = &var; printf("Address of var variable: %xn", &var ); printf("Address stored in ip variable: %xn", ip ); printf("Value of *ip variable: %dn", *ip );
  • 98. NULL Pointers in C int *ptr = NULL; printf("The value of ptr is : %xn", &ptr );
  • 99. Incrementing a Pointer int var[] = {10, 100, 200}; int i, *ptr; ptr = var; for ( i = 0; i <= 2; i++) { printf("Address of var[%d] = %xn", i, ptr ); printf("Value of var[%d] = %dn", i, *ptr ); ptr++; }
  • 100. 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] = %xn", i, ptr ); printf("Value of var[%d] = %dn", i, *ptr ); ptr--; }
  • 101. Pointer Comparisons int var[] = {10, 100, 200}; int i, *ptr; ptr = var; i = 0; while ( ptr <= &var[2] ) { printf("Address of var[%d] = %xn", i, ptr ); printf("Value of var[%d] = %dn", i, *ptr ); ptr++; i++; }
  • 102. 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] = %dn", i, *ptr[i] ); }
  • 103. Pointer to Pointer When we define a pointer to a pointer, the first pointer contains the address of the second pointer.
  • 104. Pointer to Pointer int var; int *ptr; int **pptr; var = 3000; ptr = &var; pptr = &ptr; printf("Value of var = %dn", var ); printf("Value available at *ptr = %dn", *ptr ); printf("Value available at **pptr = %dn", **pptr);
  • 105. Passing pointers to functions void getSeconds(long *hours) { *hours = *hours * 60 * 60; return; } int main () { long hours; getSeconds( &hours ); printf("Number of seconds: %dn", hours ); return 0; }
  • 106. Return pointer from functions int * 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]) : %dn", i, *(p + i) ); } return 0; }
  • 107. Memory Management • C language provides several functions for memory allocation and management. • These functions can be found in the <stdlib.h> header file.
  • 108. 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 memoryn"); }else{ strcpy(description, "my name is khan"); } printf("description = %s", description); return 0; }
  • 109. Resizing and Releasing Memory #include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ char *description; description = malloc(10 * sizeof(char)); // allocating memory dynamically description = realloc( description, 100 * sizeof(char) ); // resizing memory if(description == NULL){ printf("unable to allocate required memoryn"); }else{ strcpy(description, "my name is khan, and i'm not a terrorist"); } printf("description = %s", description); free(description); // releasing memory return 0; }
  • 111. 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.
  • 112. Defining a Union union [union tag] { member definition; member definition; ... member definition; } [one or more union variables];
  • 113. 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.
  • 114. Assigning values to Union data.i = 10; data.f = 220.5; strcpy( data.str, “Hello world”);
  • 115. Accessing Union Members union Data data; printf( "Memory size occupied by data : %dn", sizeof(data)); printf( "data.i : %dn", data.i); printf( "data.f : %fn", data.f); printf( "data.str : %sn", data.str);
  • 116. 12. Other Data Types
  • 117. 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.
  • 118. Defining a Structure struct [structure tag] { member definition; member definition; ... member definition; } [one or more structure variables];
  • 119. 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.
  • 120. 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;
  • 121. Accessing Structure Members printf( "Book 1 title : %sn", Book1.title); printf( "Book 1 author : %sn", Book1.author); printf( "Book 1 category : %sn", Book1.category); printf( "Book 1 book_id : %dn", Book1.book_id);
  • 122. Structures as Function Arguments // function definition void printBook( struct Books book ) { printf( "Book title : %sn", book.title); printf( "Book author : %sn", book.author); printf( "Book category : %sn", book.category); printf( "Book book_id : %dn", book.book_id); } // calling function printBook( Book1 );
  • 123. Pointers to Structures //define pointer to structure struct Books *struct_pointer; //store the address of a structure variable in the pointer struct_pointer = &Book1; //access the members of a structure struct_pointer->title;
  • 124. Bit Fields Bit fields offers a better way to utilize the memory space occupied by a Structure.
  • 125. 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.
  • 126. 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 : %dn", sizeof(status)); printf( "Memory size occupied by status2 : %dn", sizeof(status2));
  • 128. Opening Files FILE *fopen( const char * filename, const char * mode );
  • 130. Closing a File int fclose( FILE *fp );
  • 131. 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 );
  • 132. 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, ...)
  • 134. Searching Algorithms • Linear Search • Binary Search
  • 135. Linear Search Linear search start at the beginning and walk to the end, testing for a match at each item.
  • 136. Linear Search int 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"); }
  • 137. 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.
  • 138. Binary Search int 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"); }
  • 140. Sorting Algorithms • Bubble Sort • Selection Sort • Insertion Sort
  • 142. 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; } } }
  • 144. 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; }
  • 146. 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; }
  • 147. Comparison of Sorting Algorithms Bubble Sort Selection Sort Insertion Sort Data structure Array Array Array Worst 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.
  • 148. 16. Introduction to data structures
  • 149. 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.
  • 150. An introduction to Data Structures Organized Data + Operations = Data Structure Algorithm + Data Structure = Computer Program
  • 151. Classifications of data structures
  • 152. Frequently used data structures • Stack • Queue • Linked List • Tree • Graph
  • 153. 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.
  • 154. 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
  • 156. Algorithm for push 1. If TOP = SIZE – 1, then: a) Display “The stack is in overflow condition” b) Exit 2. TOP = TOP + 1 3. STACK [TOP] = ITEM 4. Exit
  • 157. Algorithm for pop 1. If TOP < 0, then a) Display “The Stack is empty” b) Exit 2. Else remove the Top most element 3. DATA = STACK[TOP] 4. TOP = TOP – 1 5. Exit
  • 158. 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.
  • 159. Operations on Queue • PUSH: Insert an element to the queue • POP: Delete an element from a queue
  • 163. Algorithm for push 1. Initialize front=0 rear = –1 2. Input the value to be inserted and assign to variable “data” 3. If (rear >= SIZE) a) Display “Queue overflow” b) Exit 4. Else a) Rear = rear +1 5. Q[rear] = data 6. Exit
  • 164. Algorithm for pop 1. If (rear< front) a) Front = 0, rear = –1 b) Display “The queue is empty” c) Exit 2. Else a) Data = Q[front] 3. Front = front +1 4. Exit
  • 165. 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.
  • 166. 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.
  • 170. Algorithm for push in Circular Queue 1. Initialize FRONT = – 1; REAR = 1 2. REAR = (REAR + 1) % SIZE 3. If (FRONT is equal to REAR) a) Display “Queue is full” b) Exit 4. Else a) Input the value to be inserted and assign to variable “DATA” 5. If (FRONT is equal to – 1) a) FRONT = 0 b) REAR = 0 6. Q[REAR] = DATA 7. Repeat steps 2 to 5 if we want to insert more elements 8. Exit
  • 171. Algorithm for pop in Circular Queue 1. If (FRONT is equal to – 1) a) Display “Queue is empty” b) Exit 2. Else a) DATA = Q[FRONT] 3. If (REAR is equal to FRONT) a) FRONT = –1 b) REAR = –1 4. Else a) FRONT = (FRONT +1) % SIZE 5. Repeat the steps 1, 2 and 3 if we want to delete more elements 6. Exit
  • 172. Linked List • A linked list is a collection of specially designed data elements called nodes storing data and linked to other nodes.
  • 175. 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.
  • 176. 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
  • 177. 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.
  • 178. Operations on Singly Linked List
  • 179. Operations on Singly Linked List
  • 181. Insert a Node at the beginning 1. Input DATA to be inserted 2. Create a NewNode 3. NewNode → DATA = DATA 4. If (SATRT equal to NULL) a) NewNode → Link = NULL 5. Else a) NewNode → Link = START 6. START = NewNode 7. Exit
  • 182. Insert a Node at the end 1. Input DATA to be inserted 2. Create a NewNode 3. NewNode → DATA = DATA 4. NewNode → Next = NULL 5. If (SATRT equal to NULL) a) START = NewNode 6. Else a) TEMP = START b) While (TEMP → Next not equal to NULL) i. TEMP = TEMP → Next c) TEMP → Next = NewNode 7. Exit
  • 183. Insert a Node at any specified position 1. Input DATA and POS to be inserted 2. Initialize TEMP = START; and k = 0 3. Repeat the step 3 while( k is less than POS) a) TEMP = TEMP  Next b) If (TEMP is equal to NULL) i. Display “Node in the list less than the position” ii. Exit c) k = k + 1 4. Create a New Node 5. NewNode → DATA = DATA 6. NewNode → Next = TEMP → Next 7. TEMP → Next = NewNode 8. Exit
  • 185. Algorithm for deleting a node 1. Input the DATA to be deleted 2. if ((START → DATA) is equal to DATA) a) TEMP = START b) START = START → Next c) Set free the node TEMP, which is deleted d) Exit 3. HOLD = START 4. while ((HOLD → Next → Next) not equal to NULL)) a) if ((HOLD → NEXT → DATA) equal to DATA) I. TEMP = HOLD → Next II. HOLD → Next = TEMP → Next III. Set free the node TEMP, which is deleted IV. Exit b) HOLD = HOLD → Next 5. if ((HOLD → next → DATA) == DATA) a) TEMP = HOLD → Next b) Set free the node TEMP, which is deleted c) HOLD → Next = NULL d) Exit 6. Display “DATA not found” 7. Exit
  • 186. Algorithm for searching a node 1. Input the DATA to be searched 2. 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 → Next 6. POS = POS+1 7. If (TEMP is equal to NULL) a) Display “The data is not found in the list” 8. Exit
  • 187. Algorithm for display all nodes 1. If (START is equal to NULL) a) Display “The list is Empty” b) Exit 2. Initialize TEMP = START 3. Repeat the step 4 and 5 until (TEMP == NULL ) 4. Display “TEMP → DATA” 5. TEMP = TEMP → Next 6. Exit
  • 188. Tree • Tree is a non-liner data structure. • Used to represent data items possessing hierarchical relationship. • Very flexible, versatile and powerful.
  • 189. Tree
  • 190. 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
  • 191. 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.
  • 193. 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.
  • 194. Expression tree E = ( a + b ) / ( (c - d ) * e )
  • 195. Left skewed and Right skewed Trees Left Skewed Tree Right Skewed Tree
  • 196. 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.
  • 197. Binary Tree Representation • Sequential representation using arrays • Linked list representation
  • 198. Array representation Father of a node having index n: = (n – 1) / 2 = 3 – 1 / 2 = 2 / 2 = 1
  • 199. Array representation Left child of a node having index n: = (2n +1) = 2*2 + 1 = 4 + 1 = 5
  • 200. Array representation Right child of a node having array index n: = (2n + 2) = 2*1 + 2 = 4
  • 201. Array representation If the left child is at array index n, then its right brother is at (n+1)
  • 202. Array representation Since there is no left child for node C is vacant. Even though memory is allocated for A[5] it is not used, so wasted unnecessarily.
  • 203. 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)
  • 205. 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
  • 206. Traversing binary tree 1. Pre Order Traversal (Node-left-right) 2. In order Traversal (Left-node-right) 3. Post Order Traversal (Left-right-node)
  • 207. Pre Order Traversal 1. Visit the root node 2. Traverse the left sub tree in preorder 3. Traverse the right sub tree in preorder
  • 208. Pre Order Traversal The preorder traversal of a binary tree: A, B, D, E, H, I, C, F, G, J
  • 209. Pre Order Traversal recursively void preorder (Node * Root) { If (Root != NULL) { printf (“%dn”,Root → Info); preorder(Root → L child); preorder(Root → R child); } }
  • 210. In Order Traversal 1. Traverse the left sub tree in order 2. Visit the root node 3. Traverse the right sub tree in order
  • 211. In Order Traversal The in order traversal of a binary tree: D, B, H, E, I, A, F, C, J, G
  • 212. In Order Traversal recursively void inorder (NODE *Root) { If (Root != NULL) { inorder(Root → L child); printf (“%dn”,Root → info); inorder(Root → R child); } }
  • 213. Post Order Traversal 1. Traverse the left sub tree in post order 2. Traverse the right sub tree in post order 3. Visit the root node
  • 214. Post Order Traversal The post order traversal of a binary tree: D, H, I, E, B, F, J, G, C, A
  • 215. Post Order Traversal recursively void postorder (NODE *Root) { If (Root != NULL) { postorder(Root → Lchild); postorder(Root → Rchild); printf (“%dn”,Root  info); } }
  • 216. 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.
  • 218. Operations on BST • Inserting a node • Searching a node • Deleting a node
  • 219. Algorithm for inserting a node to BST 1. 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 NODE 4. Else If (DATA < ROOT → Info) a) ROOT = ROOT → Lchild b) GoTo Step 4 5. Else If (DATA > ROOT → Info) a) ROOT = ROOT → Rchild b) GoTo Step 4 6. If (DATA < ROOT → Info) a) ROOT → LChild = NEWNODE 7. Else If (DATA > ROOT → Info) a) ROOT → RChild = NEWNODE 8. Else a) Display (“DUPLICATE NODE”) b) EXIT 9. NEW NODE → Info = DATA 10. NEW NODE → LChild = NULL 11. NEW NODE → RChild = NULL 12. EXIT
  • 220. Algorithm for searching a node in BST 1. 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→RChild b) GoTo Step 2 5. If(DATA < ROOT→Info) a) ROOT = ROOT→Lchild b) GoTo Step 2 6. Exit
  • 221. 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
  • 222. 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.
  • 223. The node to be deleted has no children 5 3 18 41 5 3 18 4 1 2
  • 224. 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.
  • 225. 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
  • 226. 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.
  • 227. The node has two children 5 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
  • 228. Algorithm for deleting a node on BST 1. 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 = NODE b) NODE = NODE → RChild 4. If(NODE → RChild= =NULL) a) LOC = NODE b) 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 → Lchild 8. LOC → RChild= NODE → RChild 9. Exit
  • 229. Graph • Graph is an another nonlinear data structure. • Applied in subjects like geography, engineering and solving games and puzzles.
  • 230. Graph A graph consist of • Set of vertices V (nodes). • Set of edges E.
  • 231. Graph V = {v1, v2, v3, v4......} E = {e1, e2, e3......cm} E = {(v1, v2) (v2, v3) (v1, v3) (v3, v4), (v3, v5) (v5, v6)}
  • 232. Directed graph Represented geometrically as a set of marked vertices V with a set of edges E between pairs of vertices
  • 233. Directed graph G = {a, b, c, d }, {(a, b), (a, d), (d, b), (d, d), (c, c)}
  • 234. Directed graph In edge (a, b) Vertex a is called the initial vertex Vertex b is called the terminal vertex
  • 235. Directed graph If an edge that is incident from and into the same vertex (d, d) (c, c) called a loop.
  • 236. Directed graph If a vertex has no edge incident with it, it is an isolated vertex. ( c )
  • 237. Undirected graph Represented geometrically as a set of marked vertices V with a set of Edges E between the vertices.
  • 238. Isomorphic graph If there is a one-to-one correspondence between their vertices it is an isomorphic graph
  • 239. Degree of vertex The number of edges incident on a vertex is its degree. degree (a) = 3
  • 240. Weighted graph If every edge and/or vertices assigned with some weight or value it is called weighted graph G = (V, E, WE, WV) N  Negambo C  Colombo K  Kandy M  Matara
  • 241. Disconnected graph Connected graph exist a path from any vertex to any other vertex, otherwise disconnected Disconnected graph Connected graph
  • 242. Complete graph If there is a path from every vertex to every other vertex it is a complete (fully connected) graph
  • 243. Paths in directed graphs • An elementary path does not meet the same vertex twice. • A simple path does not meet the same edges twice.
  • 244. 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
  • 245. Representation of a graph • Sequential representation using adjacent • Linked representation using linked list
  • 251. Operations on graph • Creating a graph • Searching and deleting from a graph • Traversing a graph
  • 252. 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.
  • 253. Searching and deleting from a graph 1. Input an edge to be searched 2. 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
  • 254. Traversing a graph • Breadth First Traversal (BFT) • Depth First Traversal (DFT)
  • 255. 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
  • 256. 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 empty 5. 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.
  • 258. Breadth First Traversal (BFT) Display: A
  • 259. Breadth First Traversal (BFT) Display: A, B, C
  • 260. Breadth First Traversal (BFT) Display: A, B, C, D, E
  • 261. Breadth First Traversal (BFT) Display: A, B, C, D, E, F, G
  • 262. Breadth First Traversal (BFT) Display: A, B, C, D, E, F, G, H
  • 263. 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.
  • 264. 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.
  • 265. Depth First Traversal (DFT) I I G H Display: I, H, E, F, D, G G H G E G E G D G D G F F D G