SlideShare uma empresa Scribd logo
1 de 178
Baixar para ler offline
C_Programming
Part 9
ENG. KEROLES SHENOUDA
1
Brainstorming on
previous session
2
3
Thanks to Eng. Amr for solving it 4
https://github.com/AmrHRAbdeen/C-Programming
AddFunc-Struct.c
5
AddFunc-Union.c
6
AddFunc-Void*.c
7
Dynamic allocation 8
Malloc() 9
calloc() 10
free() 11
12
13
14
C-typedef 15
16
C - Preprocessor 17
18
19
Embedded C Programming
20
useful references for
C and Embedded C
List all preprocessor directives in c
programming language.
22
DIFFERENCE BETWEEN C AND
EMBEDDED C
 Compilers for C (ANSI C) typically generate OS dependant
executables. Embedded C requires compilers to create files to be downloaded
to the microcontrollers/microprocessors where it needs to run. Embedded
compilers give access to all resources which is not provided in compilers for
desktop computer applications.
23
DIFFERENCE BETWEEN C AND
EMBEDDED C
 C is used for desktop computers, while embedded C is for microcontroller
based applications. Accordingly, C has the luxury to use resources of a desktop
PC like memory, OS, etc. While programming on desktop systems, we need
not bother about memory. However, embedded C has to use with the limited
resources (RAM, ROM, I/Os) on an embedded processor. Thus, program code
must fit into the available program memory. If code exceeds the limit, the
system is likely to crash.
24
DIFFERENCE BETWEEN C AND
EMBEDDED C
 Embedded systems often have the real-time constraints, which is usually not
there with desktop computer applications.
 Embedded systems often do not have a console, which is available in case of
desktop applications.
 So, what basically is different while programming with embedded C is the
mindset; for embedded applications, we need to optimally use the resources,
make the program code efficient, and satisfy real time constraints, if any. All
this is done using the basic constructs, syntaxes, and function libraries of ‘C’.
25
Embedded C Constrains
 Memory
 Power
 Size
 Cost
 Timing
 CPU
26
SW Should be
 Portable
 Maintainable
 Optimized
 Reusable
 Readable
27
Embedded versus Desktop
Programming
 Main characteristics of an Embedded programming environment:
• Limited ROM.
• Limited RAM.
• Limited stack space.
• Hardware oriented programming.
• Critical timing (Interrupt Service Routines, tasks, …).
• Many different pointer kinds (far / near / rom / uni / paged / …).
• Special keywords and tokens (@, interrupt, tiny, …)
28
Assembly versus C 29
Why Change to C
 C is much more flexible than other high-level programming languages:
• C is a structured language.
• C is a relatively small language.
• C has very loose data typing.
• C easily supports low-level bit-wise data manipulation.
• C is sometimes referred to as a “high-level assembly language”.
► When compared to assembly language programming:
• Code written in C can be more reliable.
• Code written in C can be more scalable.
• Code written in C can be more portable between different platforms.
• Code written in C can be easier to maintain.
• Code written in C can be more productive
30
How to make Code more Readable
31
1.Commenting 32
2.memory-mapped devices
Documenting the source code is helpful not only for your
future reference but for those who come after you. For
instance, if you're working on an embedded system, you
need to have a memory map indicating where all the
memory-mapped devices can be found. Listing 8 shows
an example of a memory map.
33
Review: The “super loop” software
architecture
 Problem
What is the minimum software environment you need to create an
embedded C program?
 Solution
34
Review: An introduction to schedulers
 Many embedded systems must carry out tasks at particular instants
of time. More specifically, we have two kinds of activity to
perform:
• Periodic tasks, to be performed (say) once every 100 ms,
and - less commonly -
• One-shot tasks, to be performed once after a delay of (say)
50 ms.
35
Function Reuse 36
Header File 37
Header File
 Each .h file should be “stand alone”
▫ It should declare, #define, and typedef anything needed by prototypes and
include any .h files it needs to avoid compiler errors
 In our example prototypes for CircleArea() and Circumference are placed in
circleUtils.h ▫ circleUtils.h included in circleUtils.c ▫ circleUtils.h included in any
other .c file that uses CircleArea()
38
Guarding Header Files 39
Guarding Example 40
Separate Compilation
 If code is separated into multiple .c files
▫ Must compile each .c file
▫ Combine resulting .o files to create executable
41
Program Organization 42
Scope/Lifetime
 Variable “scope” refers to part of the program
that may access the variable
▫ Local, global, etc…
• Variable “lifetime” refers to time in which a
variable occupies memory
• Both determined by how and where variable is
defined
43
Storage classes
 In C language, each variable has a storage class which decides scope, visibility
and lifetime of that variable. The following storage classes are most oftenly
used in C programming,
 Automatic variables
 External variables
 Static variables
 Register variables

44
Automatic variables
 A variable declared inside a function without any storage class specification, is by
default an automatic variable. They are created when a function is called and are
destroyed automatically when the function exits. Automatic variables can also be
called local variables because they are local to a function. By default they are
assigned garbage value by the compiler.
45
External or Global variable
 A variable that is declared outside any function is a Global
variable. Global variables remain available throughout the entire program.
One important thing to remember about global variable is that their values
can be changed by any function in the program.
46
Here the global variable number is available to all three
functions.
extern keyword
The extern keyword is used before a variable to inform the compiler that this
variable is declared somewhere else.
The extern declaration does not allocate storage for variables.
47
Problem when extern is not used 48
Example Using extern in same file 49
Static variables
 A static variable tells the compiler to persist the variable until the end of
program. Instead of creating and destroying a variable every time when it
comes into and goes out of scope, static is initialized only once and remains
into existence till the end of program. A static variable can either be internal or
external depending upon the place of declaraction. Scope of internal
static variable remains inside the function in which it is defined. External
static variables remain restricted to scope of file in each they are declared.
 They are assigned 0 (zero) as default value by the compiler.
50
Static variables 51
Register variable
 Register variable inform the compiler to store the variable in register instead
of memory. Register variable has faster access than normal variable.
Frequently used variables are kept in register. Only few variables can be
placed inside register.
 NOTE : We can never get the address of such variables.
 Syntax :
52
Volatile Type Qualifier 53
How to define u8 ,u32,…. 54
Modularity 55
 UART.c
 UART_init ()
{
……
pDATA_recieve = F1 ;
}
ISR()
{ if (pDATA_recieve != NULL)
pDATA_recieve (uDR);
}
56
APP
ECU
HAL
HW
UART
F1();
UART.h
Void (* pDATA_recieve )(char);
#pragma
 The #pragma directive gives special instructions to the compiler. The #pragma
directive is especially useful in embedded C programming and can tell the
compiler to allocate a certain variable in RAM or EEPROM. It can also tell the
compiler to insert a snippet of assembly language code.
 The GNU GCC compiler, which is a popular compiler for various embedded
architectures such as ARM and AVR, also uses attributes as an alternative
syntax to the #pragma directive.
57
#pragma GCC dependency
allows you to check the relative dates of the current file and another file. If the other file is more recent than the current file, a warning is issued.
This is useful if the current file is derived from the other file,
and should be regenerated. The other file is searched for using the normal include search path.
Optional trailing text can be used to give more information in the warning message.
C Startup
 It is not possible to directly execute C code, when the processor comes out of
reset. Since, unlike assembly language, C programs need some basic pre-
requisites to be satisfied. This section will describe the pre-requisites and how
to meet the pre-requisites.
 We will take the example of C program that calculates the sum of an array as
an example. And by the end of this section, we will be able to perform the
necessary setup, transfer control to the C code and execute it.
58
59Listing 12. Sum of Array in C
Before transferring control to C code, the
following have to be setup correctly.
 Stack
 Global variables
Initialized
Uninitialized
 Read-only data
60
Stack
 C uses the stack for storing local (auto)
variables, passing function arguments,
storing return address, etc. So it is
essential that the stack be setup
correctly, before transferring control to
C code.
 Stacks are highly flexible in the ARM
architecture, since the implementation
is completely left to the software.
61
Stack 62
 So all that has to be done in the startup code is to point r13 at the highest RAM
address, so that the stack can grow downwards (towards lower addresses).
For the connex board this can be acheived using the following ARM
instruction.
Global Variables
 When C code is compiled, the compiler places initialized global variables in the
.data section. So just as with the assembly, the .data has to be copied from
Flash to RAM.
 The C language guarantees that all uninitialized global variables will be
initialized to zero. When C programs are compiled, a separate section called
.bss is used for uninitialized variables. Since the value of these variables are all
zeroes to start with, they do not have to be stored in Flash. Before
transferring control to C code, the memory locations corresponding to these
variables have to be initialized to zero.
63
Read-only Data
 GCC places global variables marked as const in a separate section, called
.rodata. The .rodata is also used for storing string constants.
 Since contents of .rodata section will not be modified, they can be placed in
Flash. The linker script has to modified to accomodate this.
64
Startup
Code
65
Linker Script for C code 66
The startup code has the following parts 67
1.exception vectors
2.code to copy the .data from Flash to RAM
3.code to zero out the .bss
4.code to setup the stack pointer
5.branch to main
Startup Assembly 68
Data Structures
69
Introduction to Data Structures
 Data Structure is a way of collecting and organising data in such a way that we
can perform operations on these data in an effective way
70
Basic types of Data Structures
 anything that can store data can be called as a data strucure, hence Integer,
Float, Boolean, Char etc, all are data structures. They are known as Primitive
Data Structures.
 Then we also have some complex Data Structures, which are used to store
large and connected data. Some example of Abstract Data Structure are :
 Linked List
 Tree
 Graph
 Stack, Queue etc.
 All these data structures allow us to perform different operations on data. We
select these data structures based on which type of operation is required
71
Basic types of Data Structures 72
Stacks
 Stack is an abstract data type with a bounded(predefined) capacity. It is a
simple data structure that allows adding and removing elements in a particular
order. Every time an element is added, it goes on the top of the stack, the only
element that can be removed is the element that was at the top of the stack,
just like a pile of objects.
73
Basic features of Stack
 Stack is an ordered list of similar data type.
 Stack is a LIFO structure. (Last in First out).
 push() function is used to insert new elements into the Stack and pop() is used
to delete an element from the stack. Both insertion and deletion are allowed
at only one end of Stack called Top.
 Stack is said to be in Overflow state when it is completely full and is said to be
in Underflow state if it is completely empty.
74
Applications of Stack
 The simplest application of a stack is to reverse a word. You push a given word
to stack - letter by letter - and then pop letters from the stack.
75
Implementation of Stack
 Stack can be easily implemented using an Array or a Linked List. Arrays are
quick, but are limited in size and Linked List requires overhead to allocate, link,
unlink, and deallocate, but is not limited in size. Here we will implement Stack
using array.
76
Stack Implementation with Array 77
Stack Implementation with Array 78
Stack Implementation with Array 79
Stack Implementation with Array 80
Stack Implementation with Array 81
Stack Implementation with Array 82
Stack Implementation with Array 83
Stack Implementation with Array 84
Stack Implementation with Array 85
Status of Stack
Position of Top Status of Stack
-1 Stack is Empty
0 Only one element in Stack
N-1 Stack is Full
N Overflow state of Stack
86
Basic Operations
 Stack operations may involve initializing the stack, using it and then de-
initializing it. Apart from these basic stuffs, a stack is used for the following
two primary operations −
 push() − pushing (storing) an element on the stack.
 pop() − removing (accessing) an element from the stack.
 When data is PUSHed onto stack.
 To use a stack efficiently we need to check status of stack as well. For the
same purpose, the following functionality is added to stacks −
 peek() − get the top data element of the stack, without removing it.
 isFull() − check if stack is full.
 isEmpty() − check if stack is empty.
87
Basic Operations 88
int peek()
{ return stack[top]; }
isfull()
peek()
bool isfull() {
if(top == MAXSIZE)
return true;
else
return false;
}
isempty()
bool isempty()
{
if(top == -1)
return true;
else
return false;
}
PUSH Operation 89
The process of putting a new data element onto stack is known as PUSHOperation. Push operation involves series of steps −
•Step 1 − Check if stack is full.
•Step 2 − If stack is full, produce error and exit.
•Step 3 − If stack is not full, increment top to point next empty space.
•Step 4 − Add data element to the stack location, where top is pointing.
•Step 5 − return success.
if linked-list is used to implement stack, then in step 3, we need to allocate space dynamically.
PUSH Operation 90
void push(int data)
{
if(!isFull())
{ top = top + 1;
stack[top] = data;
}else {
printf("Could not insert data, Stack is full.n");
}
}
Pop Operation 91
A POP operation may involve the following steps −
•Step 1 − Check if stack is empty.
•Step 2 − If stack is empty, produce error and exit.
•Step 3 − If stack is not empty, access the data element at which top is pointing.
•Step 4 − Decrease the value of top by 1.
•Step 5 − return success.
92
Stack Code 93
Queue Data Structures
 Queue is also an abstract data type or a linear data structure, in which the first element
is inserted from one end called REAR(also called tail), and the deletion of exisiting
element takes place from the other end called asFRONT(also called head). This makes
queue as FIFO data structure, which means that element inserted first will also be
removed first.
 The process to add an element into queue is called Enqueue and the process of
removal of an element from queue is called Dequeue.
94
Queue
 Queue is an abstract data structure, somewhat similar to Stack. In contrast to
Queue, queue is opened at both end. One end is always used to insert data
(enqueue) and the other is used to remove data (dequeue). Queue follows
First-In-First-Out methodology, i.e., the data item stored first will be accessed
first.
95
Queue
Same as Queue, queue can also be implemented using Array,
Linked-list, Pointer and Structures. For the sake of simplicity we
shall implement queue using one-dimensional array.
96
Queue Basic Operations
 Queue operations may involve initializing or defining the queue, utilizing it and
then completing erasing it from memory. Here we shall try to understand basic
operations associated with queues −
 enqueue() − add (store) an item to the queue.
 dequeue() − remove (access) an item from the queue.
 Few more functions are required to make above mentioned queue operation
efficient. These are −
 peek() − get the element at front of the queue without removing it.
 isfull() − checks if queue is full.
 isempty() − checks if queue is empty.
 In queue, we always dequeue (or access) data, pointed by front pointer and while
enqueing (or storing) data in queue we take help of rear pointer.
97
Queue Implementation with Array 98
Queue Implementation with Array 99
Queue Implementation with Array 100
Queue Implementation with Array 101
Queue Implementation with Array 102
Queue Implementation with Array 103
Queue Implementation with Array 104
Queue Implementation with Array 105
Queue Implementation with Array 106
Queue Implementation with Array 107
Queue Implementation with Array 108
Queue Implementation with Array 109
Queue Implementation with Array 110
Queue Implementation with Array 111
Queue Implementation with Array 112
Queue Implementation with Array 113
Queue Implementation with Array 114
Queue Implementation with Array 115
Queue Implementation with Array 116
Queue Implementation with Array 117
Queue Implementation with Array 118
Queue Implementation with Array 119
Queue Implementation with Array 120
Queue
 peek()

 isfull()

121
Queue
 isempty()

122
Enqueue Operation
 Step 1 − Check if queue is full.
 Step 2 − If queue is full, produce overflow error and exit.
 Step 3 − If queue is not full, increment rear pointer to point next empty space.
 Step 4 − Add data element to the queue location, where rear is pointing.
 Step 5 − return success.
123
Enqueue Operation 124
Dequeue Operation
 Step 1 − Check if queue is empty.
 Step 2 − If queue is empty, produce underflow error and exit.
 Step 3 − If queue is not empty, access data where frontis pointing.
 Step 3 − Increment front pointer to point next available data element.
 Step 5 − return success.
125
Data Structure - Linked List
 A linked-list is a sequence of data structures which are connected together via
links.
 Link − Each Link of a linked list can store a data called an element.
 Next − Each Link of a linked list contain a link to next link called Next.
 LinkedList − A LinkedList contains the connection link to the first Link called
First.
 Linked list can be visualized as a chain of nodes, where every node points to
the next node.
126
Data Structure - Linked List
 As per above shown illustration, following are the important points to be
considered.
 LinkedList contains an link element called first.
 Each Link carries a data field(s) and a Link Field called next.
 Each Link is linked with its next link using its next link.
 Last Link carries a Link as null to mark the end of the list
127
Types of Linked List
 Simple Linked List − Item Navigation is forward only.
 Doubly Linked List − Items can be navigated forward and backward way.
 Circular Linked List − Last item contains link of the first element as next and
and first element has link to last element as prev.
128
Basic Operations
 Insertion − add an element at the beginning of the list.
 Deletion − delete an element at the beginning of the list.
 Display − displaying complete list.
 Search − search an element using given key.
 Delete − delete an element using given key.
129
Insertion Operation 130
Deletion Operation 131
Reverse Operation 132
Data Structure - Doubly Linked List
 Doubly Linked List is a variation of Linked list in which navigation is possible in
both ways either forward and backward easily as compared to Single Linked
List
 Doubly LinkedList contains an link element called first and last.
 Each Link carries a data field(s) and a Link Field called next.
 Each Link is linked with its next link using its next link.
 Each Link is linked with its previous link using its prev link.
 Last Link carries a Link as null to mark the end of the list.
133
Singly Linked List as Circular
 In singly linked list, the next pointer of the last node points to the first node.
134
Doubly Linked List as Circular
 n doubly linked list, the next pointer of the last node points to the first node
and the previous pointer of the first node points to the last node making the
circular in both directions.
135
Dynamic Linked Lists
 Problem Statement
Consider Students Database program, it appears that the program uses (realloc)
when
adding or deleting student member. Using (realloc) may solve the problem,
especially if
the structure size and the number of records are small.
Actually (realloc) function
1. Creates a new buffer with the new size
2. Copies the original contents
3. Deletes the original buffer
4. Returns the address of the new buffer
Consider a complicated SStudent structure containing all student information and
his courses
degrees as shown below:
136
Dynamic Linked Lists Contn. 137
Above structure size is 8548 byte, if it is required to build a
program that supports up to
10,000 student. This means adding extra student will cost
transfering following data size
inside the computer:
10000 * 8548 = 85,480,000 Byte
If it is required to transfere 1 byte 1 micosecond the above
addition operation will take 85
second or 1.5 minute. This time is very long.
Understanding the Solution
 Another techniqe is used, it depends on storing student information in a
separte buffers and
linking between them using a pointers. This techniqe called the Linked List
method.
Assument the new structure SStudent after adding the member (SStudent
*pNextStudent). pNextStudent is a pointer containing the address of the next
member of the list. Last member of the last have equals pNextStudent NULL.
138
139
Write the Program 140
 At the beginning of the program only it is required to have one empty pointer,
indicating that
there is no students added.
141
142
To delete certain record to the list: 143
144
ViewStudents function: 145
DeleteAll function: 146
Stack Implementation
with
Linked List
147
Stack Implementation with
Linked List
148
Stack Implementation with
Linked List
149
Stack Implementation with
Linked List
150
Stack Implementation with
Linked List
151
Stack Implementation with
Linked List
152
Queue
Implementation with
Linked List
153
Queue Implementation with
Linked List
154
Queue Implementation with
Linked List
155
Queue Implementation with
Linked List
156
Queue Implementation with
Linked List
157
Queue Implementation with
Linked List
158
Queue Implementation with
Linked List
159
Queue Implementation with
Linked List
160
Queue Implementation with
Linked List
161
Queue Implementation with
Linked List
162
Queue Implementation with
Linked List
163
Queue Implementation with
Linked List
164
Queue Implementation with
Linked List
165
Queue Implementation with
Linked List
166
Queue Implementation with
Linked List
167
Queue Implementation with
Linked List
168
Queue Implementation with
Linked List
169
Doubly-Linked List
170
Doubly-Linked List 171
Doubly-Linked List 172
Node contains:
key
next pointer
prev pointer
Doubly-Linked List 173
Doubly-Linked List 174
Doubly-Linked List 175
Doubly-Linked List 176
177
References 178
 http://www.tutorialspoint.com/data_structures_algorithms/index.htm
 http://www.studytonight.com/data-structures/
 std::printf, std::fprintf, std::sprintf, std::snprintf…..
 C Programming for Engineers, Dr. Mohamed Sobh
 C programming expert.
 fresh2refresh.com/c-programming
 C programming Interview questions and answers
 C – Preprocessor directives

Mais conteúdo relacionado

Mais procurados

Writing c code for the 8051
Writing c code for the 8051Writing c code for the 8051
Writing c code for the 8051
Quản Minh Tú
 
Embedded c programming22 for fdp
Embedded c programming22 for fdpEmbedded c programming22 for fdp
Embedded c programming22 for fdp
Pradeep Kumar TS
 
08 chapter03 06_status_bits_otl_otu_scan_logic_fa16
08 chapter03 06_status_bits_otl_otu_scan_logic_fa1608 chapter03 06_status_bits_otl_otu_scan_logic_fa16
08 chapter03 06_status_bits_otl_otu_scan_logic_fa16
John Todora
 
Lecture 2 verilog
Lecture 2   verilogLecture 2   verilog
Lecture 2 verilog
venravi10
 

Mais procurados (18)

C programming part2
C programming part2C programming part2
C programming part2
 
Embedded c program and programming structure for beginners
Embedded c program and programming structure for beginnersEmbedded c program and programming structure for beginners
Embedded c program and programming structure for beginners
 
Embedded c
Embedded cEmbedded c
Embedded c
 
Embedded c programming
Embedded c programmingEmbedded c programming
Embedded c programming
 
Writing c code for the 8051
Writing c code for the 8051Writing c code for the 8051
Writing c code for the 8051
 
Embedded _c_
Embedded  _c_Embedded  _c_
Embedded _c_
 
8051 programming skills using EMBEDDED C
8051 programming skills using EMBEDDED C8051 programming skills using EMBEDDED C
8051 programming skills using EMBEDDED C
 
05 chapter03 03_memory_structure_slc500_fa16
05 chapter03 03_memory_structure_slc500_fa1605 chapter03 03_memory_structure_slc500_fa16
05 chapter03 03_memory_structure_slc500_fa16
 
Embedded c programming22 for fdp
Embedded c programming22 for fdpEmbedded c programming22 for fdp
Embedded c programming22 for fdp
 
Fpga 04-verilog-programming
Fpga 04-verilog-programmingFpga 04-verilog-programming
Fpga 04-verilog-programming
 
Introduction to C Language - Version 1.0 by Mark John Lado
Introduction to C Language - Version 1.0 by Mark John LadoIntroduction to C Language - Version 1.0 by Mark John Lado
Introduction to C Language - Version 1.0 by Mark John Lado
 
08 chapter03 06_status_bits_otl_otu_scan_logic_fa16
08 chapter03 06_status_bits_otl_otu_scan_logic_fa1608 chapter03 06_status_bits_otl_otu_scan_logic_fa16
08 chapter03 06_status_bits_otl_otu_scan_logic_fa16
 
Verilog tutorial
Verilog tutorialVerilog tutorial
Verilog tutorial
 
Lecture 2 verilog
Lecture 2   verilogLecture 2   verilog
Lecture 2 verilog
 
Embedded c lab and keil c manual
Embedded  c  lab  and keil c  manualEmbedded  c  lab  and keil c  manual
Embedded c lab and keil c manual
 
Verilog HDL
Verilog HDLVerilog HDL
Verilog HDL
 
Assembler Programming
Assembler ProgrammingAssembler Programming
Assembler Programming
 
Digital Circuit Verification Hardware Descriptive Language Verilog
Digital Circuit Verification Hardware Descriptive Language VerilogDigital Circuit Verification Hardware Descriptive Language Verilog
Digital Circuit Verification Hardware Descriptive Language Verilog
 

Destaque

Destaque (14)

C programming session8
C programming  session8C programming  session8
C programming session8
 
C programming session7
C programming  session7C programming  session7
C programming session7
 
Homework 2
Homework 2Homework 2
Homework 2
 
C programming part2
C programming part2C programming part2
C programming part2
 
Microcontroller part 3
Microcontroller part 3Microcontroller part 3
Microcontroller part 3
 
Microcontroller part 7_v1
Microcontroller part 7_v1Microcontroller part 7_v1
Microcontroller part 7_v1
 
Microcontroller part 1
Microcontroller part 1Microcontroller part 1
Microcontroller part 1
 
Microcontroller part 2
Microcontroller part 2Microcontroller part 2
Microcontroller part 2
 
Microcontroller part 4
Microcontroller part 4Microcontroller part 4
Microcontroller part 4
 
Microcontroller part 9_v1
Microcontroller part 9_v1Microcontroller part 9_v1
Microcontroller part 9_v1
 
Microcontroller part 8_v1
Microcontroller part 8_v1Microcontroller part 8_v1
Microcontroller part 8_v1
 
C programming part2
C programming part2C programming part2
C programming part2
 
C programming first_session
C programming first_sessionC programming first_session
C programming first_session
 
C programming session3
C programming  session3C programming  session3
C programming session3
 

Semelhante a C programming session9 -

Compiler design notes phases of compiler
Compiler design notes phases of compilerCompiler design notes phases of compiler
Compiler design notes phases of compiler
ovidlivi91
 
Effisiensi prog atmel
Effisiensi prog atmelEffisiensi prog atmel
Effisiensi prog atmel
rm_dhozooo
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
Sowri Rajan
 
Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)
mujeeb memon
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
Sowri Rajan
 

Semelhante a C programming session9 - (20)

Embedded C.pptx
Embedded C.pptxEmbedded C.pptx
Embedded C.pptx
 
Unit-2.pptx
Unit-2.pptxUnit-2.pptx
Unit-2.pptx
 
Compiler design notes phases of compiler
Compiler design notes phases of compilerCompiler design notes phases of compiler
Compiler design notes phases of compiler
 
Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
 
Effisiensi prog atmel
Effisiensi prog atmelEffisiensi prog atmel
Effisiensi prog atmel
 
Unit-1 (introduction to c language).pptx
Unit-1 (introduction to c language).pptxUnit-1 (introduction to c language).pptx
Unit-1 (introduction to c language).pptx
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
 
Embedded concepts
Embedded conceptsEmbedded concepts
Embedded concepts
 
C session 1.pptx
C session 1.pptxC session 1.pptx
C session 1.pptx
 
Rr
RrRr
Rr
 
Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)
 
C pdf
C pdfC pdf
C pdf
 
Computer Programming In C.pptx
Computer Programming In C.pptxComputer Programming In C.pptx
Computer Programming In C.pptx
 
Transpilers(Source-to-Source Compilers)
Transpilers(Source-to-Source Compilers)Transpilers(Source-to-Source Compilers)
Transpilers(Source-to-Source Compilers)
 
0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
 
First session quiz
First session quizFirst session quiz
First session quiz
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
 
AAME ARM Techcon2013 003v02 Software Development
AAME ARM Techcon2013 003v02  Software DevelopmentAAME ARM Techcon2013 003v02  Software Development
AAME ARM Techcon2013 003v02 Software Development
 

Mais de Keroles karam khalil

Mais de Keroles karam khalil (20)

C basics quiz part 1_solution
C basics quiz part 1_solutionC basics quiz part 1_solution
C basics quiz part 1_solution
 
Autosar Basics hand book_v1
Autosar Basics  hand book_v1Autosar Basics  hand book_v1
Autosar Basics hand book_v1
 
Automotive embedded systems part6 v2
Automotive embedded systems part6 v2Automotive embedded systems part6 v2
Automotive embedded systems part6 v2
 
Automotive embedded systems part5 v2
Automotive embedded systems part5 v2Automotive embedded systems part5 v2
Automotive embedded systems part5 v2
 
Automotive embedded systems part7 v1
Automotive embedded systems part7 v1Automotive embedded systems part7 v1
Automotive embedded systems part7 v1
 
Automotive embedded systems part6 v1
Automotive embedded systems part6 v1Automotive embedded systems part6 v1
Automotive embedded systems part6 v1
 
Automotive embedded systems part5 v1
Automotive embedded systems part5 v1Automotive embedded systems part5 v1
Automotive embedded systems part5 v1
 
Automotive embedded systems part4 v1
Automotive embedded systems part4 v1Automotive embedded systems part4 v1
Automotive embedded systems part4 v1
 
Automotive embedded systems part3 v1
Automotive embedded systems part3 v1Automotive embedded systems part3 v1
Automotive embedded systems part3 v1
 
Automotive embedded systems part2 v1
Automotive embedded systems part2 v1Automotive embedded systems part2 v1
Automotive embedded systems part2 v1
 
Automotive embedded systems part1 v1
Automotive embedded systems part1 v1Automotive embedded systems part1 v1
Automotive embedded systems part1 v1
 
Automotive embedded systems part8 v1
Automotive embedded systems part8 v1Automotive embedded systems part8 v1
Automotive embedded systems part8 v1
 
Quiz 9
Quiz 9Quiz 9
Quiz 9
 
Quiz 10
Quiz 10Quiz 10
Quiz 10
 
Homework 6
Homework 6Homework 6
Homework 6
 
Homework 5 solution
Homework 5 solutionHomework 5 solution
Homework 5 solution
 
Notes part7
Notes part7Notes part7
Notes part7
 
Homework 5
Homework 5Homework 5
Homework 5
 
Notes part6
Notes part6Notes part6
Notes part6
 
Homework 4 solution
Homework 4 solutionHomework 4 solution
Homework 4 solution
 

Último

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Último (20)

Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answers
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 

C programming session9 -

  • 3. 3
  • 4. Thanks to Eng. Amr for solving it 4 https://github.com/AmrHRAbdeen/C-Programming
  • 12. 12
  • 13. 13
  • 14. 14
  • 16. 16
  • 18. 18
  • 19. 19
  • 21. useful references for C and Embedded C
  • 22. List all preprocessor directives in c programming language. 22
  • 23. DIFFERENCE BETWEEN C AND EMBEDDED C  Compilers for C (ANSI C) typically generate OS dependant executables. Embedded C requires compilers to create files to be downloaded to the microcontrollers/microprocessors where it needs to run. Embedded compilers give access to all resources which is not provided in compilers for desktop computer applications. 23
  • 24. DIFFERENCE BETWEEN C AND EMBEDDED C  C is used for desktop computers, while embedded C is for microcontroller based applications. Accordingly, C has the luxury to use resources of a desktop PC like memory, OS, etc. While programming on desktop systems, we need not bother about memory. However, embedded C has to use with the limited resources (RAM, ROM, I/Os) on an embedded processor. Thus, program code must fit into the available program memory. If code exceeds the limit, the system is likely to crash. 24
  • 25. DIFFERENCE BETWEEN C AND EMBEDDED C  Embedded systems often have the real-time constraints, which is usually not there with desktop computer applications.  Embedded systems often do not have a console, which is available in case of desktop applications.  So, what basically is different while programming with embedded C is the mindset; for embedded applications, we need to optimally use the resources, make the program code efficient, and satisfy real time constraints, if any. All this is done using the basic constructs, syntaxes, and function libraries of ‘C’. 25
  • 26. Embedded C Constrains  Memory  Power  Size  Cost  Timing  CPU 26
  • 27. SW Should be  Portable  Maintainable  Optimized  Reusable  Readable 27
  • 28. Embedded versus Desktop Programming  Main characteristics of an Embedded programming environment: • Limited ROM. • Limited RAM. • Limited stack space. • Hardware oriented programming. • Critical timing (Interrupt Service Routines, tasks, …). • Many different pointer kinds (far / near / rom / uni / paged / …). • Special keywords and tokens (@, interrupt, tiny, …) 28
  • 30. Why Change to C  C is much more flexible than other high-level programming languages: • C is a structured language. • C is a relatively small language. • C has very loose data typing. • C easily supports low-level bit-wise data manipulation. • C is sometimes referred to as a “high-level assembly language”. ► When compared to assembly language programming: • Code written in C can be more reliable. • Code written in C can be more scalable. • Code written in C can be more portable between different platforms. • Code written in C can be easier to maintain. • Code written in C can be more productive 30
  • 31. How to make Code more Readable 31
  • 33. 2.memory-mapped devices Documenting the source code is helpful not only for your future reference but for those who come after you. For instance, if you're working on an embedded system, you need to have a memory map indicating where all the memory-mapped devices can be found. Listing 8 shows an example of a memory map. 33
  • 34. Review: The “super loop” software architecture  Problem What is the minimum software environment you need to create an embedded C program?  Solution 34
  • 35. Review: An introduction to schedulers  Many embedded systems must carry out tasks at particular instants of time. More specifically, we have two kinds of activity to perform: • Periodic tasks, to be performed (say) once every 100 ms, and - less commonly - • One-shot tasks, to be performed once after a delay of (say) 50 ms. 35
  • 38. Header File  Each .h file should be “stand alone” ▫ It should declare, #define, and typedef anything needed by prototypes and include any .h files it needs to avoid compiler errors  In our example prototypes for CircleArea() and Circumference are placed in circleUtils.h ▫ circleUtils.h included in circleUtils.c ▫ circleUtils.h included in any other .c file that uses CircleArea() 38
  • 41. Separate Compilation  If code is separated into multiple .c files ▫ Must compile each .c file ▫ Combine resulting .o files to create executable 41
  • 43. Scope/Lifetime  Variable “scope” refers to part of the program that may access the variable ▫ Local, global, etc… • Variable “lifetime” refers to time in which a variable occupies memory • Both determined by how and where variable is defined 43
  • 44. Storage classes  In C language, each variable has a storage class which decides scope, visibility and lifetime of that variable. The following storage classes are most oftenly used in C programming,  Automatic variables  External variables  Static variables  Register variables  44
  • 45. Automatic variables  A variable declared inside a function without any storage class specification, is by default an automatic variable. They are created when a function is called and are destroyed automatically when the function exits. Automatic variables can also be called local variables because they are local to a function. By default they are assigned garbage value by the compiler. 45
  • 46. External or Global variable  A variable that is declared outside any function is a Global variable. Global variables remain available throughout the entire program. One important thing to remember about global variable is that their values can be changed by any function in the program. 46 Here the global variable number is available to all three functions.
  • 47. extern keyword The extern keyword is used before a variable to inform the compiler that this variable is declared somewhere else. The extern declaration does not allocate storage for variables. 47
  • 48. Problem when extern is not used 48
  • 49. Example Using extern in same file 49
  • 50. Static variables  A static variable tells the compiler to persist the variable until the end of program. Instead of creating and destroying a variable every time when it comes into and goes out of scope, static is initialized only once and remains into existence till the end of program. A static variable can either be internal or external depending upon the place of declaraction. Scope of internal static variable remains inside the function in which it is defined. External static variables remain restricted to scope of file in each they are declared.  They are assigned 0 (zero) as default value by the compiler. 50
  • 52. Register variable  Register variable inform the compiler to store the variable in register instead of memory. Register variable has faster access than normal variable. Frequently used variables are kept in register. Only few variables can be placed inside register.  NOTE : We can never get the address of such variables.  Syntax : 52
  • 54. How to define u8 ,u32,…. 54
  • 56.  UART.c  UART_init () { …… pDATA_recieve = F1 ; } ISR() { if (pDATA_recieve != NULL) pDATA_recieve (uDR); } 56 APP ECU HAL HW UART F1(); UART.h Void (* pDATA_recieve )(char);
  • 57. #pragma  The #pragma directive gives special instructions to the compiler. The #pragma directive is especially useful in embedded C programming and can tell the compiler to allocate a certain variable in RAM or EEPROM. It can also tell the compiler to insert a snippet of assembly language code.  The GNU GCC compiler, which is a popular compiler for various embedded architectures such as ARM and AVR, also uses attributes as an alternative syntax to the #pragma directive. 57 #pragma GCC dependency allows you to check the relative dates of the current file and another file. If the other file is more recent than the current file, a warning is issued. This is useful if the current file is derived from the other file, and should be regenerated. The other file is searched for using the normal include search path. Optional trailing text can be used to give more information in the warning message.
  • 58. C Startup  It is not possible to directly execute C code, when the processor comes out of reset. Since, unlike assembly language, C programs need some basic pre- requisites to be satisfied. This section will describe the pre-requisites and how to meet the pre-requisites.  We will take the example of C program that calculates the sum of an array as an example. And by the end of this section, we will be able to perform the necessary setup, transfer control to the C code and execute it. 58
  • 59. 59Listing 12. Sum of Array in C
  • 60. Before transferring control to C code, the following have to be setup correctly.  Stack  Global variables Initialized Uninitialized  Read-only data 60
  • 61. Stack  C uses the stack for storing local (auto) variables, passing function arguments, storing return address, etc. So it is essential that the stack be setup correctly, before transferring control to C code.  Stacks are highly flexible in the ARM architecture, since the implementation is completely left to the software. 61
  • 62. Stack 62  So all that has to be done in the startup code is to point r13 at the highest RAM address, so that the stack can grow downwards (towards lower addresses). For the connex board this can be acheived using the following ARM instruction.
  • 63. Global Variables  When C code is compiled, the compiler places initialized global variables in the .data section. So just as with the assembly, the .data has to be copied from Flash to RAM.  The C language guarantees that all uninitialized global variables will be initialized to zero. When C programs are compiled, a separate section called .bss is used for uninitialized variables. Since the value of these variables are all zeroes to start with, they do not have to be stored in Flash. Before transferring control to C code, the memory locations corresponding to these variables have to be initialized to zero. 63
  • 64. Read-only Data  GCC places global variables marked as const in a separate section, called .rodata. The .rodata is also used for storing string constants.  Since contents of .rodata section will not be modified, they can be placed in Flash. The linker script has to modified to accomodate this. 64
  • 66. Linker Script for C code 66
  • 67. The startup code has the following parts 67 1.exception vectors 2.code to copy the .data from Flash to RAM 3.code to zero out the .bss 4.code to setup the stack pointer 5.branch to main
  • 70. Introduction to Data Structures  Data Structure is a way of collecting and organising data in such a way that we can perform operations on these data in an effective way 70
  • 71. Basic types of Data Structures  anything that can store data can be called as a data strucure, hence Integer, Float, Boolean, Char etc, all are data structures. They are known as Primitive Data Structures.  Then we also have some complex Data Structures, which are used to store large and connected data. Some example of Abstract Data Structure are :  Linked List  Tree  Graph  Stack, Queue etc.  All these data structures allow us to perform different operations on data. We select these data structures based on which type of operation is required 71
  • 72. Basic types of Data Structures 72
  • 73. Stacks  Stack is an abstract data type with a bounded(predefined) capacity. It is a simple data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack, the only element that can be removed is the element that was at the top of the stack, just like a pile of objects. 73
  • 74. Basic features of Stack  Stack is an ordered list of similar data type.  Stack is a LIFO structure. (Last in First out).  push() function is used to insert new elements into the Stack and pop() is used to delete an element from the stack. Both insertion and deletion are allowed at only one end of Stack called Top.  Stack is said to be in Overflow state when it is completely full and is said to be in Underflow state if it is completely empty. 74
  • 75. Applications of Stack  The simplest application of a stack is to reverse a word. You push a given word to stack - letter by letter - and then pop letters from the stack. 75
  • 76. Implementation of Stack  Stack can be easily implemented using an Array or a Linked List. Arrays are quick, but are limited in size and Linked List requires overhead to allocate, link, unlink, and deallocate, but is not limited in size. Here we will implement Stack using array. 76
  • 86. Status of Stack Position of Top Status of Stack -1 Stack is Empty 0 Only one element in Stack N-1 Stack is Full N Overflow state of Stack 86
  • 87. Basic Operations  Stack operations may involve initializing the stack, using it and then de- initializing it. Apart from these basic stuffs, a stack is used for the following two primary operations −  push() − pushing (storing) an element on the stack.  pop() − removing (accessing) an element from the stack.  When data is PUSHed onto stack.  To use a stack efficiently we need to check status of stack as well. For the same purpose, the following functionality is added to stacks −  peek() − get the top data element of the stack, without removing it.  isFull() − check if stack is full.  isEmpty() − check if stack is empty. 87
  • 88. Basic Operations 88 int peek() { return stack[top]; } isfull() peek() bool isfull() { if(top == MAXSIZE) return true; else return false; } isempty() bool isempty() { if(top == -1) return true; else return false; }
  • 89. PUSH Operation 89 The process of putting a new data element onto stack is known as PUSHOperation. Push operation involves series of steps − •Step 1 − Check if stack is full. •Step 2 − If stack is full, produce error and exit. •Step 3 − If stack is not full, increment top to point next empty space. •Step 4 − Add data element to the stack location, where top is pointing. •Step 5 − return success. if linked-list is used to implement stack, then in step 3, we need to allocate space dynamically.
  • 90. PUSH Operation 90 void push(int data) { if(!isFull()) { top = top + 1; stack[top] = data; }else { printf("Could not insert data, Stack is full.n"); } }
  • 91. Pop Operation 91 A POP operation may involve the following steps − •Step 1 − Check if stack is empty. •Step 2 − If stack is empty, produce error and exit. •Step 3 − If stack is not empty, access the data element at which top is pointing. •Step 4 − Decrease the value of top by 1. •Step 5 − return success.
  • 92. 92
  • 94. Queue Data Structures  Queue is also an abstract data type or a linear data structure, in which the first element is inserted from one end called REAR(also called tail), and the deletion of exisiting element takes place from the other end called asFRONT(also called head). This makes queue as FIFO data structure, which means that element inserted first will also be removed first.  The process to add an element into queue is called Enqueue and the process of removal of an element from queue is called Dequeue. 94
  • 95. Queue  Queue is an abstract data structure, somewhat similar to Stack. In contrast to Queue, queue is opened at both end. One end is always used to insert data (enqueue) and the other is used to remove data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first will be accessed first. 95
  • 96. Queue Same as Queue, queue can also be implemented using Array, Linked-list, Pointer and Structures. For the sake of simplicity we shall implement queue using one-dimensional array. 96
  • 97. Queue Basic Operations  Queue operations may involve initializing or defining the queue, utilizing it and then completing erasing it from memory. Here we shall try to understand basic operations associated with queues −  enqueue() − add (store) an item to the queue.  dequeue() − remove (access) an item from the queue.  Few more functions are required to make above mentioned queue operation efficient. These are −  peek() − get the element at front of the queue without removing it.  isfull() − checks if queue is full.  isempty() − checks if queue is empty.  In queue, we always dequeue (or access) data, pointed by front pointer and while enqueing (or storing) data in queue we take help of rear pointer. 97
  • 123. Enqueue Operation  Step 1 − Check if queue is full.  Step 2 − If queue is full, produce overflow error and exit.  Step 3 − If queue is not full, increment rear pointer to point next empty space.  Step 4 − Add data element to the queue location, where rear is pointing.  Step 5 − return success. 123
  • 125. Dequeue Operation  Step 1 − Check if queue is empty.  Step 2 − If queue is empty, produce underflow error and exit.  Step 3 − If queue is not empty, access data where frontis pointing.  Step 3 − Increment front pointer to point next available data element.  Step 5 − return success. 125
  • 126. Data Structure - Linked List  A linked-list is a sequence of data structures which are connected together via links.  Link − Each Link of a linked list can store a data called an element.  Next − Each Link of a linked list contain a link to next link called Next.  LinkedList − A LinkedList contains the connection link to the first Link called First.  Linked list can be visualized as a chain of nodes, where every node points to the next node. 126
  • 127. Data Structure - Linked List  As per above shown illustration, following are the important points to be considered.  LinkedList contains an link element called first.  Each Link carries a data field(s) and a Link Field called next.  Each Link is linked with its next link using its next link.  Last Link carries a Link as null to mark the end of the list 127
  • 128. Types of Linked List  Simple Linked List − Item Navigation is forward only.  Doubly Linked List − Items can be navigated forward and backward way.  Circular Linked List − Last item contains link of the first element as next and and first element has link to last element as prev. 128
  • 129. Basic Operations  Insertion − add an element at the beginning of the list.  Deletion − delete an element at the beginning of the list.  Display − displaying complete list.  Search − search an element using given key.  Delete − delete an element using given key. 129
  • 133. Data Structure - Doubly Linked List  Doubly Linked List is a variation of Linked list in which navigation is possible in both ways either forward and backward easily as compared to Single Linked List  Doubly LinkedList contains an link element called first and last.  Each Link carries a data field(s) and a Link Field called next.  Each Link is linked with its next link using its next link.  Each Link is linked with its previous link using its prev link.  Last Link carries a Link as null to mark the end of the list. 133
  • 134. Singly Linked List as Circular  In singly linked list, the next pointer of the last node points to the first node. 134
  • 135. Doubly Linked List as Circular  n doubly linked list, the next pointer of the last node points to the first node and the previous pointer of the first node points to the last node making the circular in both directions. 135
  • 136. Dynamic Linked Lists  Problem Statement Consider Students Database program, it appears that the program uses (realloc) when adding or deleting student member. Using (realloc) may solve the problem, especially if the structure size and the number of records are small. Actually (realloc) function 1. Creates a new buffer with the new size 2. Copies the original contents 3. Deletes the original buffer 4. Returns the address of the new buffer Consider a complicated SStudent structure containing all student information and his courses degrees as shown below: 136
  • 137. Dynamic Linked Lists Contn. 137 Above structure size is 8548 byte, if it is required to build a program that supports up to 10,000 student. This means adding extra student will cost transfering following data size inside the computer: 10000 * 8548 = 85,480,000 Byte If it is required to transfere 1 byte 1 micosecond the above addition operation will take 85 second or 1.5 minute. This time is very long.
  • 138. Understanding the Solution  Another techniqe is used, it depends on storing student information in a separte buffers and linking between them using a pointers. This techniqe called the Linked List method. Assument the new structure SStudent after adding the member (SStudent *pNextStudent). pNextStudent is a pointer containing the address of the next member of the list. Last member of the last have equals pNextStudent NULL. 138
  • 139. 139
  • 140. Write the Program 140  At the beginning of the program only it is required to have one empty pointer, indicating that there is no students added.
  • 141. 141
  • 142. 142
  • 143. To delete certain record to the list: 143
  • 144. 144
  • 172. Doubly-Linked List 172 Node contains: key next pointer prev pointer
  • 177. 177
  • 178. References 178  http://www.tutorialspoint.com/data_structures_algorithms/index.htm  http://www.studytonight.com/data-structures/  std::printf, std::fprintf, std::sprintf, std::snprintf…..  C Programming for Engineers, Dr. Mohamed Sobh  C programming expert.  fresh2refresh.com/c-programming  C programming Interview questions and answers  C – Preprocessor directives