Introduction to C Programming<br />
Copyright<br />Copyright © 2011 to author(s). All rights reserved<br />All content in this presentation, including charts,...
Course Objective<br />After completing this course, you will be able to:<br />Write programs in C language<br />Understand...
Course Notes<br />Set your cell phone to vibrate.<br />I assume you know computer architecture.<br />Ask any time.<br />Du...
Course References<br />www.cprogramming.com<br />C by Example<br />www.opengroup.com<br />http://ocw.mit.edu/index.htm<br ...
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
What is C?<br />Invented by Dennis Ritchie – AT&T Bell Labs<br />1972<br />Widely used today<br />Extends to newer system ...
C Features<br />Few keywords<br />Structures, unions, compound data types..<br />Pointers, arrays…<br />Standard library<b...
C Evolution<br />1972 – C Invention<br />1978 – 1st specification published<br />1989 – C89 standard (ANSI C or standard C...
C Usage<br />Systems programming<br />Operating systems<br />Microcontrollers<br />Embedded processors<br />DSP processors...
C vs. Others<br />Recent derivatives: C++, C#, Objective-C<br />Had an effect on: Java, Perl, Python<br />C lacks:<br />Ex...
Editing C Code<br />*.c extension for C source files<br />*.h extension for C header files<br />They are editable by any t...
IDE – All in  One Solution<br />Examples:<br />Eclipse CDT<br />MS VC++ express edition<br />KDevelop<br />Xcode<br />Comp...
Structure of a C File<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />15<br />
Comments<br />Ignored by the compiler<br />Can appear anywhere<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Program...
The #include Macro<br />A header file has constants, functions, and other declarations.<br />#include reads the contents o...
Declaring variables<br />Must declare variables before use <br />General form:<br />type variable_name [=initial_value][,]...
Arithmetic Expressions<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />19<br />
Order of Operations<br />Orders of Operation<br />Use parentheses to override order of evaluation <br />Amr Ali Abdel-Naby...
Function Prototypes<br />Functions also must be declared before use <br />Declaration called function prototype <br />Prot...
The main() Function<br />C Program entry point<br />Can be one of:<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Pro...
Function Definition<br />Must match prototype (if there is one)<br />Variable names don’t have to match<br />Curly braces ...
Our First Program<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />24<br />
More About Strings<br />Strings stored as character array <br />Null-terminated <br />Last character in array is ‘0’ <br /...
Console IO<br />stdout, stdin: console output and input streams <br />puts(string): print string to stdout <br />putchar(c...
Preprocessor Macros<br />They begin with #.<br />They can take arguments.<br />Parentheses ensure order of operations.<br ...
Conditional Preprocessor Macros<br />They can control which lines are compiled.<br />Evaluated before code itself is compi...
Extra Preprocessor Macros <br />Preprocessor directive<br />Trigger a custom compiler error/warning message<br />Remove th...
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Definitions<br />Datatype<br />Determines the set of values an object can have and what operations that can be performed o...
Variables Naming Rules<br />Can contain letters, digits and _<br />Should start with letters<br />Keywords (e.g., for,whil...
Data Types<br />C has a small family of datatypes. <br />Numeric (int, float, double) <br />Character (char) <br />User de...
Variables Sizes and Endianess<br />Sizes are machine/compiler dependent.<br />sizeof(char) < sizeof(short) <= sizeof(int) ...
Big Endian vs. Little Endian<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />35<br />
Constants<br />Literal/fixed values assigned to variables or used directly in expressions<br />Integers<br />3, 3UL, 0x12,...
Operators<br />Arithmetic<br />+, -, *, /, %<br />Relational<br />>, >=, <, <=, ==, !=<br />Logical<br />&&, ||, !<br />In...
Conditional Expression<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />38<br />
Type Conversions<br />C is a weakly typed language. <br />It allows implicit conversions  as well as forced casting.<br />...
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Blocks and Compound Statements<br />Curly braces {} combine statements into a compound statement/block<br />A block substi...
Examples<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />42<br />
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Booleans in C<br />No booleans in C<br />True is any non-zero value/result of a condition/expression.<br />False is any ze...
The if Statement<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />45<br />
The switch Statement<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />46<br />
The while Loop<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />47<br />
The for Loop<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />48<br />
The do-while Loop<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />49<br />
The break and continue Keywords<br />break exists the innermost loop or switch statement.<br />continue skips rest of inne...
goto Keyword<br />Allows you to jump unconditionally to arbitrary part of your code (within the same function) <br />The l...
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Divide and Conquer<br />Let’s design a program to solve linear Diophantine equation.<br />ax + by = c where a, b, c, x, y ...
Returning Multiple Values<br />Extended Euclidean algorithm returns gcd, and two other state variables, x and y <br />Func...
In General<br />Break down problem into simpler sub-problems.<br />Consider iteration and recursion.<br />Writing pseudoco...
Programming Modules in C<br />C programs do not need to be monolithic.<br />Module: interface and implementation <br />Int...
ecluid.c<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />57<br />
ecluid.h<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />58<br />
Using Euclid Module<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />59<br />
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Variable Scope<br />The region in which a variable is valid.<br />Many cases, corresponds to block with variable’s declara...
Scope and Nested Declarations<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />62<br />
Static Variables<br />static keyword has two meanings, depending on where the static variable is declared <br />Outside a ...
Register Variables<br />During execution, data are processed in registers.<br />Explicitly store commonly used data in reg...
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Preliminaries <br />IO facilities are provided by the standard library <stdio.h> and not by the language itself. <br />A t...
Standard IO<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />67<br />
Formatted Output: printf<br />It takes in a variable number of arguments. <br />It returns the number of characters printe...
printf Format Specification - type<br />%[flags][width][. precision][length]<type> <br />Amr Ali Abdel-Naby@2011<br />Intr...
printf Format Specification - width<br />%[flags][width][. precision][length]<type> <br />Amr Ali Abdel-Naby@2011<br />Int...
printf Format Specification - flag<br />%[flags][width][. precision][length]<type> <br />Amr Ali Abdel-Naby@2011<br />Intr...
printf Format Specification - precision<br />%[flags][width][. precision][length]<type> <br />Amr Ali Abdel-Naby@2011<br /...
printf Format Specification - modifier<br />%[flags][width][. precision][length]<type> <br />Amr Ali Abdel-Naby@2011<br />...
Character Arrays<br />Strings are represented as an array of characters.<br />C does not restrict the length of the string...
Comparing Strings<br />strcmp in string.h compares two strings in dictionary order.<br />Lower case letters come after cap...
Formatted Input<br />scanf reads characters from standard input, interpreting them according to format specification <br /...
String IO<br />Formatted data can be written to or read from character arrays.<br />Amr Ali Abdel-Naby@2011<br />Introduct...
File IO<br />C allows us to read/write data from text/binary files.<br />We can:<br />Open a file<br />Close a file<br />R...
Project I: Game of Life <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />79<br />Required:<br />In la...
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Physical vs. Virtual Memory <br />Physical memories are physical resources where data can be stored.<br />Caches<br />RAMs...
Physical Memory Considerations<br />Different sizes and access speeds<br />Memory management is a major OS function.<br />...
Virtual Memory<br />How much physical memory do you have?<br />How much virtual memory do you have?<br />Depends on OS<br ...
Addressing Variables<br />Every variables has an address in memory.<br />What does not have an address?<br />Register vari...
Dereferencing Pointers<br />Using the * operator, I can access and modify addressed variable.<br />A pointer that derefere...
Casting Pointers<br />Explicitly from any type to any type.<br />Implicitly to and from void *.<br />May cause segmentatio...
Functions with Multiple Outputs<br />Recall extended Ecluid, it calculates g = gcd(a,b) and sets the global variables x an...
Accessing Caller’s Variables<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />88<br />
Variable Passing Out of Scope<br />What is wrong with this code?<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Progr...
Pointer to Pointers<br />Address stored by a pointer is also data in memory.<br />A pointer to a pointer can address locat...
Pointer to Pointers Example <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />91<br />vs.<br />
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Arrays and Pointers<br />Arrays in C are implemented using a pointer to block of contiguous memory.<br />[] can be used fo...
The sizeof() Operator<br />Can be used to find the byte size of:<br />A primitive type/variable<br />Primitive arrays<br /...
Pointer Arithmetic<br />A pointer is not an integer but we can add/substract an integer from it.<br />pa + i points to arr...
Strings as Arrays<br />Strings are null terminated character arrays.<br />There are some utilities defined in string.h.<br...
Pointer Arrays<br />Array of pointers<br />Each pointer can point to another array.<br />Example usage: An array int arr[1...
String Arrays<br />An array of strings, each stored as a pointer to an array of chars.<br />Amr Ali Abdel-Naby@2011<br />I...
Multidimensional Arrays<br />C also permits multidimensional arrays specified using []. <br />Higher dimensions are possib...
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Linear Search<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />101<br />
Binary Search<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />102<br />
Binary Search cont’d<br />Requires random access to array memory<br />Slow on sequential devices like hard disks<br />May ...
Simple Sort<br />Iterate through an array until an out of order element found.<br />Insert out of order element into corre...
Finding Out of Order Elements<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />105<br />
Shifting Out of Order Elements<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />106<br />
Quick Sort<br />Choose a pivot element.<br />Move all elements less than pivot to one side.<br />Greater ones are on other...
Quick Sort cont’d<br />Not stable <br />Equal-valued elements can get switched.<br />Can sort in-place<br />Desirable for ...
Exercise 4<br />Required:<br />In assn-04.pdf, solve all problems except 4.3.<br />Duration: 20 minutes<br />Amr Ali Abdel...
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Structure<br />A collection of related variables grouped under a single name.<br />Amr Ali Abdel-Naby@2011<br />Introducti...
Structure cont’d<br />struct defines a new data type. <br />The name of the structure is optional. <br />The variables dec...
Accessing Structure Members<br />The . operator is used to access structure members.<br />Amr Ali Abdel-Naby@2011<br />Int...
Structure Pointers<br />Structures are copied element wise. <br />For large structures it is more efficient to pass pointe...
Array of Structures<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />115<br />
Size of Structures<br />The size of a structure is greater than or equal to the sum of the sizes of its members. <br />Ali...
Union <br />May hold objects of different types/sizes in the same memory location.<br />Union size is equal to the size of...
Bit Fields<br />A bit-field is a set of adjacent bits within a single word.<br />It must be unsigned int.<br />The number ...
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Dynamic Memory Allocation<br />malloc() allocates an uninitialized block of memory.<br />calloc() allocates a zero initial...
Linked List<br />A dynamic data structure that consists of a sequence of records where each element contains a link to the...
Single Linked List<br />Every node has a payload and a link to the next node in the list. <br />The start (head) of the li...
Single Linked List Utilities<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />123<br />
Binary Tree<br />A dynamic data structure where each node has at most two children. <br />A binary search tree is a binary...
Binary Tree Utilities<br />Can be framed as recursive<br />Traversal (printing, searching): <br />Pre-order: root, left su...
Exercise 5<br />Required:<br />In assn-05.pdf, solve all problems.<br />Duration: 60 minutes<br />Amr Ali Abdel-Naby@2011<...
Stack<br />A special type of list where we read and write from same end of list.<br />LIFO list<br />Push operation writes...
Stack as an Array<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />128<br />
Stack as a Linked List<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />129<br />
Queue<br />A special type of list where we read and write from different ends of list.<br />FIFO list<br />Enqueue operati...
Queue as an Array<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />131<br />
Queue as a Linked List<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />132<br />
B Tree<br />Generalized binary search tree, used for databases and file systems <br />With variable number of children<br ...
Inserting Elements<br />Complicated due to maximum number of keys<br />At high level:<br />Traverse tree to leaf node<br /...
Insertion Example<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />135<br />
Insertion Example cont’d<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />136<br />
Searching a B Tree<br />Like searching a B Tree<br />Start at root<br />If node empty, element not in tree <br />Search li...
Deleting Elements<br />Complicated due to minimum number of children restriction<br />You need to ensure child nodes to be...
Deletion Example<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />139<br />
Deletion Example cont’d<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />140<br />
Priority Queue<br />A queue where ordering data by priority, used for sorting, event simulation, and many other algorithms...
Heaps<br />A tree with high-ordering property<br />Child priority ≤ Parent priority<br />Usually implemented as an array w...
Extracting Data<br />Maximum priority element at top of heap <br />Can peek by looking at top element <br />We can remove ...
Inserting Data/Increasing Priority<br />Element is inserted at the end.<br />Increase priority of element to real priority...
Inserting Example<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />145<br />
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Void Pointers<br />C does not allow to declare and usage of void pointers.<br />Can be used as a return type or as a funct...
Function Pointers<br />In C, function itself is not a variable. <br />It is possible to declare pointer to functions. <br ...
Callbacks<br />A piece of executable code passed to functions. <br />Callbacks are implemented by passing function pointer...
qsort Callback<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />150<br />
Linked List Callback<br />We can make a callback that iterates a function through the list.<br />Amr Ali Abdel-Naby@2011<b...
Printing and Counting Nodes<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />152<br />
Array of Function Pointers<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />153<br />
Array of Function Pointers cont'd<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />154<br />
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Hash Table<br />Combines linked lists and arrays to provide an efficient structure for storing dynamic data.<br />They are...
Hash Table cont'd<br />Each data item is associated with a key that determines its location. <br />Hash functions are used...
Hash Functions<br />A hash function maps its input into a finite range: hash value, hash code. <br />The hash value should...
Hash Table Example<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />159<br />
Hash Table Example<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />160<br />
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Symbols and Libraries<br />External libraries provide a wealth of functionality .<br />C standard library <br />Programs a...
Functions and Variables as Symbols<br />What variables and functions are declared globally?<br />Amr Ali Abdel-Naby@2011<b...
C Compilation Process<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />164<br />
Static and Dynamic Linking<br />Functions, global variables must be allocated memory before used. <br />Can allocate at co...
Static vs. Dynamic Linking<br />Static<br />During compile time<br />Linked symbols are added to executable. <br />Larger ...
Symbol Resolution Issues<br />Symbols can be defined in multiple places.<br />Suppose we define our own puts() function .<...
Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Mo...
Standard Library<br /><stdio.h><br /><ctype.h> <br /><stdlib.h><br /><string.h> <br /><assert.h> <br /><stdarg.h> <br /><t...
<stdio.h><br />fopen<br />freopen<br />fflush<br />rename<br />remove<br />tmpfile<br />tmpname<br />fread<br />fwrite<br ...
<ctype.h><br />isalnum<br />isctrl<br />isdigit<br />islower<br />isprint<br />ispunct<br />isspace<br />isupper<br />Amr ...
<string.h><br />memcpy<br />memmove<br />memcmp<br />memset<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programmin...
<stdlib.h><br />atof<br />atoi<br />atol<br />rand<br />srand<br />abort<br />exit<br />atexit<br />system<br />bsearch<br...
<assert.h><br />assert<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />174<br />
<time.h><br />clock<br />time<br />difftime<br />mktime<br />asctime<br />localtime<br />ctime<br />strftime<br />Amr Ali ...
Project II: BMP to JPEG Tool <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />176<br />Required:<br /...
BMP File Format<br />File header<br />Image header<br />Color table<br />GAP1<br />Pixel array<br />GAP2<br />Color profil...
BMP File Header<br />Signature:<br />2 bytes<br />“BM”<br />File size:<br />4 bytes<br />File size in bytes<br />Reserved ...
BMP Image Header<br />Each field is either 4 bytes or 2 bytes.<br />Color space endpoints is 36 bytes.<br />Planes must be...
BMP Color Table<br />Mandatory when bits per pixel are less than 8.<br />It defines colors used in the bitmap.<br />Can be...
BMP Pixels<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />181<br />
JPEG Compression<br />Color space transformation<br />Downsampling<br />Discrete cosine transform<br />Quantization<br />Z...
Color Space Transformation and Downsampling<br />Transforming RGB to YCbCr<br />YCbCr allows reduction in Cb and Cr compon...
Discrete Cosine Transform<br />For 8×8 block, its values are shifted from a positive range to one centered around zero bef...
Quantization<br />Dividing DCT output with quantization matrix.<br />The output will is rounding of quantization.<br />Amr...
Zigzag Scanning<br />Maps 8x8 matrix into a vector<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />18...
DPCM and RLE<br />DPCM:<br />Store the difference between the current DC value and the previous one<br />RLE:<br />Encode ...
Entropy Coding<br />Categorize DC values into SSS<br />Send off SSS as Huffman symbol, followed by actual 3 bits.<br />For...
JPEG File Format<br />Let’s check http://www.w3.org/Graphics/JPEG/jfif3.pdf<br />Amr Ali Abdel-Naby@2011<br />Introduction...
Upcoming SlideShare
Loading in...5
×

Introduction to C Programming

50,266

Published on

16 Comments
138 Likes
Statistics
Notes
  • http://www.slideshare.net/rattanano/introduction-c-programming
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Please enable download......it is very helpful .. pleae send me...........
    mahesh100nucs@gmail.com
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • i am c++ user plz give me if you give me my problem is sloved. plz plz plz
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • plz enable it and you donot enable it i will report virus site and your computer will be blast
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Please enable download......it is very helpful ....god wil also help u :D
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
50,266
On Slideshare
0
From Embeds
0
Number of Embeds
111
Actions
Shares
0
Downloads
0
Comments
16
Likes
138
Embeds 0
No embeds

No notes for slide
  • E+02
  • E+02
  • i– not i++
  • Transcript of "Introduction to C Programming"

    1. 1. Introduction to C Programming<br />
    2. 2. Copyright<br />Copyright © 2011 to author(s). All rights reserved<br />All content in this presentation, including charts, data, artwork and logos (from here on, "the Content"), is the property of Amr Ali or the corresponding owners, depending on the circumstances of publication, and is protected by national and international copyright laws.<br />Authors are not personally liable for your usage of the Content that entailed casual or indirect destruction of anything or actions entailed to information profit loss or other losses.<br />Users are granted to access, display, download and print portions of this presentation, solely for their own personal non-commercial use, provided that all proprietary notices are kept intact. <br />Product names and trademarks mentioned in this presentation belong to their respective owners.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />2<br />
    3. 3. Course Objective<br />After completing this course, you will be able to:<br />Write programs in C language<br />Understand what are the constructs of the C language<br />Implement data structures and algorithms in C<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />3<br />
    4. 4. Course Notes<br />Set your cell phone to vibrate.<br />I assume you know computer architecture.<br />Ask any time.<br />During labs, feel free to:<br />Check any material<br />Search internet<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />4<br />
    5. 5. Course References<br />www.cprogramming.com<br />C by Example<br />www.opengroup.com<br />http://ocw.mit.edu/index.htm<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />5<br />
    6. 6. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />6<br />
    7. 7. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />7<br />
    8. 8. What is C?<br />Invented by Dennis Ritchie – AT&T Bell Labs<br />1972<br />Widely used today<br />Extends to newer system architectures<br />Efficiency/performance<br />Low-level access<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />8<br />
    9. 9. C Features<br />Few keywords<br />Structures, unions, compound data types..<br />Pointers, arrays…<br />Standard library<br />Compiles to native code<br />Macro preprocessor<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />9<br />
    10. 10. C Evolution<br />1972 – C Invention<br />1978 – 1st specification published<br />1989 – C89 standard (ANSI C or standard C)<br />1990 – ANSI C adopted by ISO, AKA C90<br />1999 – C99 standard<br />Not completely implemented in many compilers<br />2007 – Work on new standard C1X announced<br />We will focus on ANSI/ISO C (C89/C90)<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />10<br />
    11. 11. C Usage<br />Systems programming<br />Operating systems<br />Microcontrollers<br />Embedded processors<br />DSP processors<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />11<br />
    12. 12. C vs. Others<br />Recent derivatives: C++, C#, Objective-C<br />Had an effect on: Java, Perl, Python<br />C lacks:<br />Exceptions<br />Range checking<br />Garbage collection<br />OOP<br />…<br />Lower level language<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />12<br />
    13. 13. Editing C Code<br />*.c extension for C source files<br />*.h extension for C header files<br />They are editable by any text editor.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />13<br />
    14. 14. IDE – All in One Solution<br />Examples:<br />Eclipse CDT<br />MS VC++ express edition<br />KDevelop<br />Xcode<br />Compiler, editor, debugger…<br />Suitable for large programs<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />14<br />
    15. 15. Structure of a C File<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />15<br />
    16. 16. Comments<br />Ignored by the compiler<br />Can appear anywhere<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />16<br />
    17. 17. The #include Macro<br />A header file has constants, functions, and other declarations.<br />#include reads the contents of the header file<br />#include <header-file> searches for the header file in the include paths<br />#include “header-file” searches for the header file in the current directory where the file it included it is in<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />17<br />
    18. 18. Declaring variables<br />Must declare variables before use <br />General form:<br />type variable_name [=initial_value][,][…];<br />Uninitialized, variable assumes a default value<br />Can declare/initialize multiple variables at once <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />18<br />
    19. 19. Arithmetic Expressions<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />19<br />
    20. 20. Order of Operations<br />Orders of Operation<br />Use parentheses to override order of evaluation <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />20<br />
    21. 21. Function Prototypes<br />Functions also must be declared before use <br />Declaration called function prototype <br />Prototypes for many common functions in header files for C Standard Library <br />General form:<br />return_type function_name(arg1, arg2, …)<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />21<br />
    22. 22. The main() Function<br />C Program entry point<br />Can be one of:<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />22<br />
    23. 23. Function Definition<br />Must match prototype (if there is one)<br />Variable names don’t have to match<br />Curly braces define a block<br />Variables declared in a block exist only in that block <br />Variable declarations must be before any other statements <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />23<br />
    24. 24. Our First Program<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />24<br />
    25. 25. More About Strings<br />Strings stored as character array <br />Null-terminated <br />Last character in array is ‘0’ <br />Not written explicitly in string literals <br />Special characters specified using (escape character): <br /> - backslash, ’ - apostrophe, ” - quotation mark <br />b, t, r, n - backspace, tab, carriage return, linefeed <br />ooo, xhh - octal and hexadecimal ASCII character codes<br />x41 – ’A’, <br />060 – ’0’ <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />25<br />
    26. 26. Console IO<br />stdout, stdin: console output and input streams <br />puts(string): print string to stdout <br />putchar(char): print character to stdout <br />char = getchar(): return character from stdin <br />string = gets(string): read line from stdin into string <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />26<br />
    27. 27. Preprocessor Macros<br />They begin with #.<br />They can take arguments.<br />Parentheses ensure order of operations.<br />Compiler performs inline replacement.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />27<br />
    28. 28. Conditional Preprocessor Macros<br />They can control which lines are compiled.<br />Evaluated before code itself is compiled, so conditions must be preprocessor defines or literals <br />Used in header files to ensure declarations happen only once <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />28<br />
    29. 29. Extra Preprocessor Macros <br />Preprocessor directive<br />Trigger a custom compiler error/warning message<br />Remove the definition of a previously defined constant<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />29<br />
    30. 30. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />30<br />
    31. 31. Definitions<br />Datatype<br />Determines the set of values an object can have and what operations that can be performed on it <br />Operator<br />Specifies how an object can be manipulated<br />Expression<br />Combination of values, variables, operators, and functions<br />Variable<br />Named link/reference to a value stored in the system’s memory or an expression that can be evaluated<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />31<br />
    32. 32. Variables Naming Rules<br />Can contain letters, digits and _<br />Should start with letters<br />Keywords (e.g., for,while etc.) cannot be used as variable names.<br />Names are case sensitive. <br />X is not as x.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />32<br />
    33. 33. Data Types<br />C has a small family of datatypes. <br />Numeric (int, float, double) <br />Character (char) <br />User defined (struct, union) <br />Numeric datatypes<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />33<br />
    34. 34. Variables Sizes and Endianess<br />Sizes are machine/compiler dependent.<br />sizeof(char) < sizeof(short) <= sizeof(int) <= sizeof(long)<br />sizeof(char) < sizeof(short) <= sizeof(float) <= sizeof(double)<br />For datatypes spanning multiple bytes, the order of arrangement of the individual bytes is important. <br />Big endian vs. little endian<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />34<br />
    35. 35. Big Endian vs. Little Endian<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />35<br />
    36. 36. Constants<br />Literal/fixed values assigned to variables or used directly in expressions<br />Integers<br />3, 3UL, 0x12, 012 <br />Floating point<br />3.141, 3.141F<br />Character <br />‘A’, ‘x41’, ‘0101’<br />String <br />“Hello world”, “Hello” “world”<br />Enumeration<br />enum bool{YES, NO}, enum color{R=1, G, B, Y=10}<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />36<br />
    37. 37. Operators<br />Arithmetic<br />+, -, *, /, %<br />Relational<br />>, >=, <, <=, ==, !=<br />Logical<br />&&, ||, !<br />Increment and decrement<br />X++, Y—<br />--X, ++X<br />Bitwise<br />&, |, ^, ~, >>, <<<br />Assignment<br />+=, &=…<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />37<br />
    38. 38. Conditional Expression<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />38<br />
    39. 39. Type Conversions<br />C is a weakly typed language. <br />It allows implicit conversions as well as forced casting.<br />When variables are promoted to higher precision, data is preserved.<br />char  int<br />int  float<br />As a rule (with exceptions), the compiler promotes each term in an binary expression to the highest precision operand.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />39<br />
    40. 40. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />40<br />
    41. 41. Blocks and Compound Statements<br />Curly braces {} combine statements into a compound statement/block<br />A block substitute a simple statement and compiled as a single unit.<br />Variables can be declared in a block.<br />A block can be empty or nested.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />41<br />
    42. 42. Examples<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />42<br />
    43. 43. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />43<br />
    44. 44. Booleans in C<br />No booleans in C<br />True is any non-zero value/result of a condition/expression.<br />False is any zero value/result of a condition/expression.<br />Expression must be numeric or a pointer.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />44<br />
    45. 45. The if Statement<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />45<br />
    46. 46. The switch Statement<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />46<br />
    47. 47. The while Loop<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />47<br />
    48. 48. The for Loop<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />48<br />
    49. 49. The do-while Loop<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />49<br />
    50. 50. The break and continue Keywords<br />break exists the innermost loop or switch statement.<br />continue skips rest of innermost loop body, jumping to loop condition .<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />50<br />
    51. 51. goto Keyword<br />Allows you to jump unconditionally to arbitrary part of your code (within the same function) <br />The location is identified using a label. <br />A label is a named location in the code. It has the same form as a variable followed by a ’:’ .<br />Do not use it.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />51<br />
    52. 52. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />52<br />
    53. 53. Divide and Conquer<br />Let’s design a program to solve linear Diophantine equation.<br />ax + by = c where a, b, c, x, y are integers<br />get a, b, c from command line<br />compute g = gcd(a,b)<br />if (c is not a multiple of the gcd) no solutions exist; <br />Run Extended Euclidean algorithm on a, b <br />rescale x and y output by (c/g)<br />print solution <br />Extended Euclidean algorithm: finds integers x, y s.t. ax + by = gcd(a, b). <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />53<br />
    54. 54. Returning Multiple Values<br />Extended Euclidean algorithm returns gcd, and two other state variables, x and y <br />Functions only return (up to) one value <br />Solution: Use global variables <br />Declare variables for other outputs outside the function.<br />Variables declared outside of a function block are global.<br />Persist throughout life of program <br />Can be accessed/modified in any function <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />54<br />
    55. 55. In General<br />Break down problem into simpler sub-problems.<br />Consider iteration and recursion.<br />Writing pseudocode first can help.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />55<br />
    56. 56. Programming Modules in C<br />C programs do not need to be monolithic.<br />Module: interface and implementation <br />Interface: header files <br />Implementation: auxiliary source/object files <br />Same concept carries over to external libraries.<br />Lets take the extended Euclid as an example.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />56<br />
    57. 57. ecluid.c<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />57<br />
    58. 58. ecluid.h<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />58<br />
    59. 59. Using Euclid Module<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />59<br />
    60. 60. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />60<br />
    61. 61. Variable Scope<br />The region in which a variable is valid.<br />Many cases, corresponds to block with variable’s declaration <br />Variables declared outside of a function have global scope <br />Function definitions also have scope <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />61<br />
    62. 62. Scope and Nested Declarations<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />62<br />
    63. 63. Static Variables<br />static keyword has two meanings, depending on where the static variable is declared <br />Outside a function, static variables/functions only visible within that file<br />Not global (cannot be extern’ed) <br />Inside a function, static variables are local to that function<br />Initialized only during program initialization <br />Do not get reinitialized with each function call <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />63<br />
    64. 64. Register Variables<br />During execution, data are processed in registers.<br />Explicitly store commonly used data in registers <br />Minimize load/store overhead <br />Can explicitly declare certain variables as registers using register keyword <br />Must be a simple type <br />Only local variables and function arguments eligible <br />excess/unallowed register declarations ignored,<br />Registers do not reside in addressed memory<br />Pointer of a register variable illegal <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />64<br />
    65. 65. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />65<br />
    66. 66. Preliminaries <br />IO facilities are provided by the standard library <stdio.h> and not by the language itself. <br />A text stream consists of a series of lines ending with ’n’. <br />The standard library takes care of conversion from ’rn’−’n’ .<br />A binary stream consists of a series of raw bytes. <br />The streams provided by standard library are buffered. <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />66<br />
    67. 67. Standard IO<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />67<br />
    68. 68. Formatted Output: printf<br />It takes in a variable number of arguments. <br />It returns the number of characters printed. <br />The format can contain literal strings as well as format specifiers (starts with %). <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />68<br />
    69. 69. printf Format Specification - type<br />%[flags][width][. precision][length]<type> <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />69<br />
    70. 70. printf Format Specification - width<br />%[flags][width][. precision][length]<type> <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />70<br />
    71. 71. printf Format Specification - flag<br />%[flags][width][. precision][length]<type> <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />71<br />
    72. 72. printf Format Specification - precision<br />%[flags][width][. precision][length]<type> <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />72<br />
    73. 73. printf Format Specification - modifier<br />%[flags][width][. precision][length]<type> <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />73<br />
    74. 74. Character Arrays<br />Strings are represented as an array of characters.<br />C does not restrict the length of the string. The end of the string is specified using 0.<br />“hello”  {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘0’}<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />74<br />
    75. 75. Comparing Strings<br />strcmp in string.h compares two strings in dictionary order.<br />Lower case letters come after capital case.<br />‘a’ > ‘A’<br />The function returns a value <0 if s comes before t <br />The function return a value 0 if s is the same as t <br />The function return a value >0 if s comes after t<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />75<br />
    76. 76. Formatted Input<br />scanf reads characters from standard input, interpreting them according to format specification <br />Similar to printf , scanf also takes variable number of arguments.<br />Arguments have to be address of variables.<br />The format specification is the same as that for printf .<br />When multiple items are to be read, each item is assumed to be separated by white space.<br />scanf ignores white spaces. <br />It returns the number of items read or EOF.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />76<br />
    77. 77. String IO<br />Formatted data can be written to or read from character arrays.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />77<br />
    78. 78. File IO<br />C allows us to read/write data from text/binary files.<br />We can:<br />Open a file<br />Close a file<br />Read a single character<br />Read a single line<br />Write a single character<br />Write a single line<br />Read formatted line<br />Write formatted line<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />78<br />
    79. 79. Project I: Game of Life <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />79<br />Required:<br />In lab-01.pdf, solve all problems.<br />Duration: 120 minutes<br />
    80. 80. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />80<br />
    81. 81. Physical vs. Virtual Memory <br />Physical memories are physical resources where data can be stored.<br />Caches<br />RAMs<br />Hard disks<br />Removable storage<br />Virtual memory is an OS abstracted addressable space accessible by your code.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />81<br />
    82. 82. Physical Memory Considerations<br />Different sizes and access speeds<br />Memory management is a major OS function.<br />You have to optimize your code to make the best usage of the physical memory.<br />OS moves data around physical memory during execution.<br />In embedded systems, it may be very limited.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />82<br />
    83. 83. Virtual Memory<br />How much physical memory do you have?<br />How much virtual memory do you have?<br />Depends on OS<br />Usable parts of virtual memory are stack and heap.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />83<br />
    84. 84. Addressing Variables<br />Every variables has an address in memory.<br />What does not have an address?<br />Register variables<br />Expressions unless result is a variable.<br />Constants, literals, and preprocessors<br />The & operator finds the address of a variable.<br />Address of a variable of type t has type t *.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />84<br />
    85. 85. Dereferencing Pointers<br />Using the * operator, I can access and modify addressed variable.<br />A pointer that dereferences nothing is called a NULL pointer.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />85<br />
    86. 86. Casting Pointers<br />Explicitly from any type to any type.<br />Implicitly to and from void *.<br />May cause segmentation faults and many difficult errors to debug.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />86<br />
    87. 87. Functions with Multiple Outputs<br />Recall extended Ecluid, it calculates g = gcd(a,b) and sets the global variables x and y.<br />Using pointers we can, extend the outputs of a function.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />87<br />
    88. 88. Accessing Caller’s Variables<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />88<br />
    89. 89. Variable Passing Out of Scope<br />What is wrong with this code?<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />89<br />
    90. 90. Pointer to Pointers<br />Address stored by a pointer is also data in memory.<br />A pointer to a pointer can address location of address in memory.<br />Uses in C: <br />Pointer arrays<br />String arrays <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />90<br />
    91. 91. Pointer to Pointers Example <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />91<br />vs.<br />
    92. 92. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />92<br />
    93. 93. Arrays and Pointers<br />Arrays in C are implemented using a pointer to block of contiguous memory.<br />[] can be used for accessing array elements.<br />Array name is a pointer to its 1st element.<br />Not modifiable/reassignable like any pointer.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />93<br />
    94. 94. The sizeof() Operator<br />Can be used to find the byte size of:<br />A primitive type/variable<br />Primitive arrays<br />How to find array length?<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />94<br />
    95. 95. Pointer Arithmetic<br />A pointer is not an integer but we can add/substract an integer from it.<br />pa + i points to arr[i];<br />Address value increments by i x size of data type.<br />If arr[0] has address 100, then pa + 3 has value of 112. <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />95<br />
    96. 96. Strings as Arrays<br />Strings are null terminated character arrays.<br />There are some utilities defined in string.h.<br />strcpy<br />strncpy<br />strcmp<br />strncmp<br />strlen<br />strcat<br />strncat<br />strchr<br />strrchr<br />…<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />96<br />
    97. 97. Pointer Arrays<br />Array of pointers<br />Each pointer can point to another array.<br />Example usage: An array int arr[100] that we want to sort without modifying<br />Solution: <br />Declare a pointer array int * sorted_arr[100] containing pointers to elements of arr.<br />Sort the pointers instead of the numbers themselves.<br />Good approach for sorting arrays whose elements are very large.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />97<br />
    98. 98. String Arrays<br />An array of strings, each stored as a pointer to an array of chars.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />98<br />
    99. 99. Multidimensional Arrays<br />C also permits multidimensional arrays specified using []. <br />Higher dimensions are possible.<br />Multidimensional arrays are rectangular.<br />Pointer arrays can be arbitrary shaped.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />99<br />
    100. 100. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />100<br />
    101. 101. Linear Search<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />101<br />
    102. 102. Binary Search<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />102<br />
    103. 103. Binary Search cont’d<br />Requires random access to array memory<br />Slow on sequential devices like hard disks<br />May be wasteful<br />Linear search may be useful in some cases.<br />Implemented in C standard library<br />bsearch in stdlib.h<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />103<br />
    104. 104. Simple Sort<br />Iterate through an array until an out of order element found.<br />Insert out of order element into correct location.<br />Repeat until end of array reached.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />104<br />
    105. 105. Finding Out of Order Elements<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />105<br />
    106. 106. Shifting Out of Order Elements<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />106<br />
    107. 107. Quick Sort<br />Choose a pivot element.<br />Move all elements less than pivot to one side.<br />Greater ones are on other side.<br />Sort sides individually.<br />Implemented in C standard library<br />qsort in stdlib.h<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />107<br />
    108. 108. Quick Sort cont’d<br />Not stable <br />Equal-valued elements can get switched.<br />Can sort in-place<br />Desirable for low-memory environments <br />Choice of pivot influences performance.<br />Easily parallelizable <br />Recursive<br />Can cause stack overflow on large array <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />108<br />
    109. 109. Exercise 4<br />Required:<br />In assn-04.pdf, solve all problems except 4.3.<br />Duration: 20 minutes<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />109<br />
    110. 110. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />110<br />
    111. 111. Structure<br />A collection of related variables grouped under a single name.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />111<br />
    112. 112. Structure cont’d<br />struct defines a new data type. <br />The name of the structure is optional. <br />The variables declared within a structure are called its members. <br />Variables can be declared like any other built in data-type. <br />Initialization is done by specifying values of every member. <br />Assignment operator copies every member of the structure.<br />Be careful with pointers.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />112<br />
    113. 113. Accessing Structure Members<br />The . operator is used to access structure members.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />113<br />
    114. 114. Structure Pointers<br />Structures are copied element wise. <br />For large structures it is more efficient to pass pointers. <br />Members can be accesses from structure pointers using the -> operator. <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />114<br />
    115. 115. Array of Structures<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />115<br />
    116. 116. Size of Structures<br />The size of a structure is greater than or equal to the sum of the sizes of its members. <br />Alignment and padding are issues. <br />Libraries<br />Precompiled files<br />SIMD instructions<br />Members can be explicitly aligned or padded using compiler extensions. <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />116<br />
    117. 117. Union <br />May hold objects of different types/sizes in the same memory location.<br />Union size is equal to the size of its largest element. <br />The compiler does not test if the data is being read in the correct format. <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />117<br />
    118. 118. Bit Fields<br />A bit-field is a set of adjacent bits within a single word.<br />It must be unsigned int.<br />The number after: specifies the width<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />118<br />
    119. 119. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />119<br />
    120. 120. Dynamic Memory Allocation<br />malloc() allocates an uninitialized block of memory.<br />calloc() allocates a zero initialized array of n elements.<br />free() frees allocated memory.<br />Common errors:<br />Accessing freed memory<br />Accessing uninitialized pointer<br />Memory leak<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />120<br />
    121. 121. Linked List<br />A dynamic data structure that consists of a sequence of records where each element contains a link to the next and may be previous record in the sequence.<br />They can be:<br />Single<br />Double<br />Circular<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />121<br />
    122. 122. Single Linked List<br />Every node has a payload and a link to the next node in the list. <br />The start (head) of the list is maintained in a separate variable.<br />End of the list is indicated by NULL (sentinel). <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />122<br />
    123. 123. Single Linked List Utilities<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />123<br />
    124. 124. Binary Tree<br />A dynamic data structure where each node has at most two children. <br />A binary search tree is a binary tree with ordering among its children. <br />Usually, all elements in the left subtree are less than the root element while elements in the right subtree are greater than the root element. <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />124<br />
    125. 125. Binary Tree Utilities<br />Can be framed as recursive<br />Traversal (printing, searching): <br />Pre-order: root, left subtree, right subtree<br />In order: left subtree, root, right subtree<br />Post order: left subtree , right subtree, root<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />125<br />
    126. 126. Exercise 5<br />Required:<br />In assn-05.pdf, solve all problems.<br />Duration: 60 minutes<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />126<br />
    127. 127. Stack<br />A special type of list where we read and write from same end of list.<br />LIFO list<br />Push operation writes to list end.<br />POP operation reads from list end.<br />Can be build as an array or as a linked list.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />127<br />
    128. 128. Stack as an Array<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />128<br />
    129. 129. Stack as a Linked List<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />129<br />
    130. 130. Queue<br />A special type of list where we read and write from different ends of list.<br />FIFO list<br />Enqueue operation writes to list end.<br />Dequeue operation reads from other list end.<br />Can be build as an array or as a linked list.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />130<br />
    131. 131. Queue as an Array<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />131<br />
    132. 132. Queue as a Linked List<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />132<br />
    133. 133. B Tree<br />Generalized binary search tree, used for databases and file systems <br />With variable number of children<br />Tree is balanced.<br />All leaves at same level<br />A node contains a list of keys to divide range of elements in children.<br />Initially, it contains a root node with no children.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />133<br />
    134. 134. Inserting Elements<br />Complicated due to maximum number of keys<br />At high level:<br />Traverse tree to leaf node<br />If leaf full, split into two<br />Move median key element into parent and split parent if already full<br />Split remaining keys into 2 leaves<br />Add elements to sorted list of keys<br />Can be done in one pass by splitting full parents during traversal in step 1<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />134<br />
    135. 135. Insertion Example<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />135<br />
    136. 136. Insertion Example cont’d<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />136<br />
    137. 137. Searching a B Tree<br />Like searching a B Tree<br />Start at root<br />If node empty, element not in tree <br />Search list of keys for element (using linear or binary search) <br />If element in list, return element <br />Otherwise, element between keys, and repeat search on child node for that range <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />137<br />
    138. 138. Deleting Elements<br />Complicated due to minimum number of children restriction<br />You need to ensure child nodes to be traversed have enough keys <br />If adjacent child node has at least t keys, move separating key from parent to child and closest key in adjacent child to parent <br />If no adjacent child nodes have extra keys, merge child node with adjacent child <br />When removing a key from a node with children, need to rearrange keys again <br />If child before or after removed key has enough keys, move closest key from child to parent <br />If neither child has enough keys, merge both children <br />If child not a leaf, have to repeat this process <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />138<br />
    139. 139. Deletion Example<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />139<br />
    140. 140. Deletion Example cont’d<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />140<br />
    141. 141. Priority Queue<br />A queue where ordering data by priority, used for sorting, event simulation, and many other algorithms <br />Elements enqueued with priority, dequeued in order of highest priority <br />Common implementations: heap or binary search tree <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />141<br />
    142. 142. Heaps<br />A tree with high-ordering property<br />Child priority ≤ Parent priority<br />Usually implemented as an array with top element at beginning<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />142<br />
    143. 143. Extracting Data<br />Maximum priority element at top of heap <br />Can peek by looking at top element <br />We can remove top element, move last element to top, and swap top element down with its children until it satisfies heap-ordering property: <br />Start at top <br />Find largest of element and children; if element is largest, we are done <br />Otherwise, swap element with largest child and repeat with element in new position <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />143<br />
    144. 144. Inserting Data/Increasing Priority<br />Element is inserted at the end.<br />Increase priority of element to real priority.<br />Start at element<br />If new priority less than parent’s, we are done.<br />Otherwise, swap element with parent and repeat.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />144<br />
    145. 145. Inserting Example<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />145<br />
    146. 146. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />146<br />
    147. 147. Void Pointers<br />C does not allow to declare and usage of void pointers.<br />Can be used as a return type or as a function parameter<br />C allows void pointers.<br />The can point to any data point.<br />They can’t be dereferenced.<br />They must be cast before used.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />147<br />
    148. 148. Function Pointers<br />In C, function itself is not a variable. <br />It is possible to declare pointer to functions. <br />Declaration examples: <br />Function pointers can be assigned, pass to and from functions, placed in arrays etc.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />148<br />
    149. 149. Callbacks<br />A piece of executable code passed to functions. <br />Callbacks are implemented by passing function pointers.<br />Example:<br />qsort() can sort an array of any data type. <br />qsort() calls a function whenever a comparison needs to be done. <br />Callback<br />The callback returns <0, 0, or >0 depending on iinputs.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />149<br />
    150. 150. qsort Callback<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />150<br />
    151. 151. Linked List Callback<br />We can make a callback that iterates a function through the list.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />151<br />
    152. 152. Printing and Counting Nodes<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />152<br />
    153. 153. Array of Function Pointers<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />153<br />
    154. 154. Array of Function Pointers cont'd<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />154<br />
    155. 155. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />155<br />
    156. 156. Hash Table<br />Combines linked lists and arrays to provide an efficient structure for storing dynamic data.<br />They are commonly implemented as an array of linked lists. <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />156<br />
    157. 157. Hash Table cont'd<br />Each data item is associated with a key that determines its location. <br />Hash functions are used to generate an evenly distributed hash value.<br />A hash collision is said to occur when two items have the same hash value. <br />Items with the same hash keys are chained <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />157<br />
    158. 158. Hash Functions<br />A hash function maps its input into a finite range: hash value, hash code. <br />The hash value should ideally have uniform distribution. <br />Other uses of hash functions: cryptography, caches (computers/internet)…<br />Hash function types: <br />Division type <br />Multiplication type <br />… <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />158<br />
    159. 159. Hash Table Example<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />159<br />
    160. 160. Hash Table Example<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />160<br />
    161. 161. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />161<br />
    162. 162. Symbols and Libraries<br />External libraries provide a wealth of functionality .<br />C standard library <br />Programs access libraries’ functions and variables via identifiers known as symbols.<br />Header file declarations/prototypes mapped to symbols at compile time. <br />Symbols linked to definitions in external libraries during linking.<br />Our own program produces symbols too.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />162<br />
    163. 163. Functions and Variables as Symbols<br />What variables and functions are declared globally?<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />163<br />
    164. 164. C Compilation Process<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />164<br />
    165. 165. Static and Dynamic Linking<br />Functions, global variables must be allocated memory before used. <br />Can allocate at compile time (static) or at run time (shared) <br />Static linking links symbols in .o files and .lib files.<br />Dynamic linking uses symbols in .dll files.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />165<br />
    166. 166. Static vs. Dynamic Linking<br />Static<br />During compile time<br />Linked symbols are added to executable. <br />Larger executable<br />No libraries’ dependencies on run time<br />Library upgrade needs recompilation.<br />Dynamic<br />During run time<br />Linked symbols are loaded from shared library.<br />Smaller executable<br />Depends on shared libraries location on run time.<br />No recompilation needed<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />166<br />
    167. 167. Symbol Resolution Issues<br />Symbols can be defined in multiple places.<br />Suppose we define our own puts() function .<br />But, puts() is defined in C standard library.<br />Which puts compiler uses?<br />Dynamic linking uses our puts as C standard library is known at run time only.<br />Statically linking against C standard library causes an error.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />167<br />
    168. 168. Outline<br />Introduction to C<br />Variables and Data Types<br />Blocks and Compound Statements<br />Control Flow<br />Modular Programming<br />Variable Scope<br />I/O<br />Pointers and Memory Addresses<br />Arrays and Pointers Arithmetic<br />Search and Sorting Algorithms<br />User Defined Data Types<br />Data Structures<br />Callbacks<br />Hash Tables<br />Using External Libraries<br />Creating Libraries<br />Standard Library<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />168<br />
    169. 169. Standard Library<br /><stdio.h><br /><ctype.h> <br /><stdlib.h><br /><string.h> <br /><assert.h> <br /><stdarg.h> <br /><time.h><br />…<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />169<br />
    170. 170. <stdio.h><br />fopen<br />freopen<br />fflush<br />rename<br />remove<br />tmpfile<br />tmpname<br />fread<br />fwrite<br />fseek<br />ftell<br />rewind<br />clearerr<br />feof<br />ferror<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />170<br />
    171. 171. <ctype.h><br />isalnum<br />isctrl<br />isdigit<br />islower<br />isprint<br />ispunct<br />isspace<br />isupper<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />171<br />
    172. 172. <string.h><br />memcpy<br />memmove<br />memcmp<br />memset<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />172<br />
    173. 173. <stdlib.h><br />atof<br />atoi<br />atol<br />rand<br />srand<br />abort<br />exit<br />atexit<br />system<br />bsearch<br />qsort<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />173<br />
    174. 174. <assert.h><br />assert<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />174<br />
    175. 175. <time.h><br />clock<br />time<br />difftime<br />mktime<br />asctime<br />localtime<br />ctime<br />strftime<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />175<br />
    176. 176. Project II: BMP to JPEG Tool <br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />176<br />Required:<br />Write a utility that converts a bmp image to a jpeg image.<br />Deadline: <br />A week from now<br />References:<br />http://en.wikipedia.org/wiki/BMP_file_format<br />http://en.wikipedia.org/wiki/JPEG<br />http://www.digicamsoft.com/itu/itu-t81-36.html<br />http://www.cs.cf.ac.uk/Dave/Multimedia/node234.html<br />http://www.w3.org/Graphics/JPEG/jfif3.pdf<br />Bmp to jpeg<br />utility<br />
    177. 177. BMP File Format<br />File header<br />Image header<br />Color table<br />GAP1<br />Pixel array<br />GAP2<br />Color profile<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />177<br />
    178. 178. BMP File Header<br />Signature:<br />2 bytes<br />“BM”<br />File size:<br />4 bytes<br />File size in bytes<br />Reserved 1 and 2:<br />Each 2 bytes<br />Used by the image creator application<br />File offset to pixel array:<br />4 bytes<br />Offset from file start to pixel array<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />178<br />
    179. 179. BMP Image Header<br />Each field is either 4 bytes or 2 bytes.<br />Color space endpoints is 36 bytes.<br />Planes must be 1.<br />Bits per pixel can be 1, 4, 8, 16, 24, and 32.<br />We will only focus on uncompressed bmp.<br />Important color count is usually ignored.<br />Masks can be used to extract data from pixels.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />179<br />
    180. 180. BMP Color Table<br />Mandatory when bits per pixel are less than 8.<br />It defines colors used in the bitmap.<br />Can be used to index bitmap images.<br />A table entry is either 4 bytes or 3 bytes depending on the header version.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />180<br />
    181. 181. BMP Pixels<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />181<br />
    182. 182. JPEG Compression<br />Color space transformation<br />Downsampling<br />Discrete cosine transform<br />Quantization<br />Zigzag scanning<br />DPCM on DC components<br />RLE on AC components<br />Entropy Coding<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />182<br />
    183. 183. Color Space Transformation and Downsampling<br />Transforming RGB to YCbCr<br />YCbCr allows reduction in Cb and Cr components. <br />Downsampling<br />Known Downsampling are:<br />4:4:4<br />4:2:2<br />4:2:0<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />183<br />
    184. 184. Discrete Cosine Transform<br />For 8×8 block, its values are shifted from a positive range to one centered around zero before computing the DCT.<br />DCT is performed after shifting as follows:<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />184<br />
    185. 185. Quantization<br />Dividing DCT output with quantization matrix.<br />The output will is rounding of quantization.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />185<br />
    186. 186. Zigzag Scanning<br />Maps 8x8 matrix into a vector<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />186<br />
    187. 187. DPCM and RLE<br />DPCM:<br />Store the difference between the current DC value and the previous one<br />RLE:<br />Encode the AC values as pairs of (skip, value).<br />Skip is the number of preceding zeroes.<br />Value is the next non-zero value.<br />(0,0) is used as end of block.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />187<br />
    188. 188. Entropy Coding<br />Categorize DC values into SSS<br />Send off SSS as Huffman symbol, followed by actual 3 bits.<br />For AC components (skip, value), encode the composite symbol (skip, SSS) using the Huffman coding.<br />Huffman Tables can be custom (sent in header) or default.<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />188<br />
    189. 189. JPEG File Format<br />Let’s check http://www.w3.org/Graphics/JPEG/jfif3.pdf<br />Amr Ali Abdel-Naby@2011<br />Introduction to C Programming<br />189<br />

    ×