Sie sind auf Seite 1von 185

B Math I

Computer Science I
Megha Nugehally

July 2015

1
Lorem Ipsum Dolor

Welcome!
Computer Science I

2
courtesy: deviantart.net
3
4
Learning Objectives
❖ Understanding how computers work!
❖ Problem solving through computers!
❖ Writing basic programs using C!
❖ Thinking algorithmically!
❖ Basic computational vocabulary - Read and reuse code!
❖ Basic knowledge of data structures!
❖ Knowledge of Program Design

5
Topics
❖ Digital Representation of Information!
❖ Writing basic programs in C!
❖ Pointers and Memory Management!
❖ Data Structures and Encapsulation!
❖ Abstraction and Algorithms!
❖ Simple I/O!
❖ Advanced C Topics!
❖ Program Design

6
“To me programming is more than an important
practical art. It is also a gigantic undertaking in the
foundations of knowledge.”

–Grace Hopper

7
Computers and Computer Science

8
Computers
❖ Machines that perform highly complex tasks and
computations that are typically very difficult for humans!
❖ Wide range of applications - almost all areas in life!
❖ First computing machine was developed by Blaise Pascal in
the 17th century!
❖ First mechanical computer was developed by Charles
Babbage in 18th century.!
❖ First theoretical computer based on which present-day
computers are built was developed by John Von Neumann
and Alan Turing in the 20th century
9
Computer Science
❖ Scientific approach to the study of computation and its applications!
❖ Computer Science has its foundation in science, technology and
mathematics!
❖ Algorithms and programming are essential aspects of computer
science!
❖ Theories of computation include 3 main concepts!
❖ Automata Theory, !
❖ Computational Theory, and !
❖ Complexity Theory

10
Insides of a Computer

11
C
❖ Procedural language!
❖ Founded by Dennis Ritchie and Brian Kernighan around
1970!
❖ Was developed primarily to create low-level source code
like Operating Systems and Compilers!
❖ Provided the ability to access low-level memory locations!
❖ Rich syntax with simple clean style !
❖ The source code would need to be compiled to create
executable code. Hence a C Compiler is required

12
What is required to write C programs
❖ Source code or program files which have the extension “.c” by convention!
❖ Header files that contain function declarations or prototypes of pre-existing
codeas part of the C Standard Reference library!
❖ Object files with extension ‘.o’ that are the result of compiling source code
files.!
❖ C Standard Reference Library, that come as object files usually “.a” or “.sa”
by convention. These are linked together with the ‘.o’ files to create the final
executable.!
❖ CPP or C Preprocessor!
❖ C Compiler and linker!
❖ Final executable code which is named by the user or is named as ‘a.out’ on
Unix systems by default.
13
Our first C program
#include <stdio.h>!
!
// All programs are collections of functions.!

// Every program needs to have at least one function !

// for it to be able to execute - the main() function.!

int main() // beginning of executable code!

{!

! printf("Hello world\n");!

! return 0;!! ! !
}

14
Compiling C Programs
❖ Invoke the C Compiler!
❖ Converts source file .c into binary object file .o!
❖ .o files are not directly executable!
❖ Why?!
❖ In general, the compiler is invoked as follows:!
❖ for compile only option!
❖ % gcc -c test.c !
❖ for compile and link to create the executable!
❖ % gcc test.c -o test!
❖ % gcc test1.c test2.c -o test to create an executable of multiple
source files

15 courtesy: caltech.edu
Programming Paradigms
❖ Imperative: Programming with an explicit sequence of ❖ Event-Driven: Programming with emitters and
commands that update state.! listeners of asynchronous actions.!
❖ Declarative: Programming by specifying the result you want, ❖ Flow-Driven: Programming processes
not how to get it.!
communicating with each other over predefined
❖ Structured: Programming with clean, goto-free, nested control channels.!
structures.!
❖ Logic (Rule-based): Programming by specifying a
❖ Procedural: Imperative programming with procedure calls.!
set of facts and rules. An engine infers the answers
❖ Functional (Applicative): Programming with function calls to questions.!
that avoid any global state.!
❖ Constraint: Programming by specifying a set of
❖ Function-Level (Combinator): Programming with no constraints. An engine finds the values that meet
variables at all.! the constraints.!
❖ Object-Oriented: Programming by defining objects that send ❖ Aspect-Oriented: Programming cross-cutting
messages to each other. Objects have their own internal
(encapsulated) state and public interfaces. Object orientation
concerns applied transparently.!
can be:! ❖ Reflective: Programming by manipulating the
❖ Class-based: Objects get state and behavior based on program elements themselves.!
membership in a class.! ❖ Array: Programming with powerful array
❖ Prototype-based: Objects get behavior from a prototype operators that usually make loops unnecessary.
object.

16
What exactly happens ?

17
C Preprocessor
❖ A separate program, called CPP!
❖ Called by the C Compiler!
❖ Denoted by the symbol #!
❖ Expands the source code file to include pre-defined C functions, header
files, macros and constants specified by ‘#’ in the program source code
file!
❖ Most common preprocessor commands!
❖ #define!
❖ #include!
❖ Macros - we’ll come back to this later

18 courtesy: caltech.edu
Creating the C Executable
❖ Link the .o object files to create the executable!
❖ put together the executable by linking the .o files both what
the programmer has created and the predefined ones!
❖ predefined object files come in the form of libraries and
have the extension .a or .so!
❖ Like the preprocessor, the linker is a separate program called
‘ld’, which the Compiler calls automatically. !
❖ Invoke the linker through this command:!
❖ % gcc test1.o test2.o test3.o -o mytest!
❖ Now get started!!
19 courtesy: caltech.edu
C Programming Language Standard
❖ What to do when a C program produces different results in two different compilers?!
❖ For example, !
❖ void main() { }!
❖ Fails in gcc but compiles in other Compilers!
❖ Which is correct?!
❖ Refer to C Standard!
❖ The latest C standard is ISO/IEC 9899:2011, also known as C11 as the final draft was
published in 2011!
❖ Benefits of C!
❖ Can use it to write computer applications that access low-level memory locations!
❖ Examples of Computer applications written in C - Embedded System applications!
❖ The UNIX OS is written in C

20 Source geeksforgeeks.org
“First solve the problem, then write code”

–all designers

21
Digitizing Information

22
Number Systems
❖ Decimal system!
❖ Binary system!
❖ Other systems - Octal, Hexadecimal!
❖ Decimal to Binary Conversions!
❖ ASCII !
❖ ASCII Table!
❖ Complement Number Systems!
❖ 1’s Complement System!
❖ 2’s Complement System!
❖ Non-negative numbers: Ordinary binary number system is used to represent
positive numbers and zero. In all these cases the most significant bit is always
0. !
❖ Negative numbers: Two’s complement notation is used to represent all negative
numbers and in this case the most significant is always 1.
23
Two’s Complement
Integer 2's Complement in an 8-bit
Signed Unsigned System
5 5 0000 0101
4 4 0000 0100
3 3 0000 0011
2 2 0000 0010
1 1 0000 0001
0 0 0000 0000
-1 255 1111 1111
-2 254 1111 1110
-3 253 1111 1101
-4 252 1111 1100
-5 251 1111 1011

24
Why Two’s Complement?
❖ Binary representation of negative values complicates arithmetic operations
and can lead to incorrect answers!
❖ For example, 6 + (-6) should yield 0, but it does not!
❖ In a 8-bit system, !
❖ 0000 0110 (+6)!
❖ 1000 0110 (-6)!
❖ ———————!
❖ 1000 1100 - which is incorrect!
❖ Possibility of representing Zero as -0 is not there!
❖ With Two’s complement, the same CPU adder circuits can be used to
perform subtraction
25
Two’s Complement Methodology
❖ To represent a negative value in Two’s complement binary:!
❖ Method 1!
❖ First invert the bits!
❖ Then add 1 !
❖ Ignore any overflow carry!
❖ Method 2!
❖ Retain the binary number upto the least-significant ‘1’
value (binary value) and then invert the rest
26
Constants & Variables
❖ Constant!
❖ A named location in memory that stores a value that cannot be modified through the
life of the program!
❖ Declaring and defining a constant!
❖ const int a = 32; !
❖ const char x = ‘c’;!
❖ Variable!
❖ A named location in memory that stores a value that can be modified
programmatically!
❖ Declaring and defining a variables!
❖ int x = 12;!
❖ char b; char z = ‘f’;!
❖ int c, d, f;
27
Types of Constants
Integer constants! int! 0, 45, 2395, 32145 etc !
unsigned int! 5000u, 1000U etc!
long int! 48364790!
Real or Floating point constants! long
float!long int! 2,147,483,680
3.1456!
doule! 100.123456789

Octal constants int int! 025 // starts with 0 !

Hexadecimal constant int int! 0×79 // starts with 0x

Character constants char A’, ‘c’, ‘a’, ‘B’, ‘z’

String constants char *! “ABCD”!


“Hello World”

Backslash character constants predefined constants in C

28
Backslash Constants
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
\N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)
29
Reading from stdin, Writing to stdout
stdin is short for standard input device, typically the keyboard!
stdout is short for standard output device, typically the computer screen or monitor!
Example of Simple Reading from stdin and Writing to stdout!
#include <stdio.h>!
// scanf and printf are examples of predefined functions in C, prototypes of which can be found in stdio.h!
int main()!
{!
! int a; // Example of a variable declaration!
! printf("Enter an integer\n”);!
! scanf("%d", &a);! ! ! // Notice the “&",!
!
! printf("Integer that you have entered is %d\n", a); // Notice no ampresand!
!
! return 0;!
}

30
C Programming Constructs
❖ Keywords !
❖ int, char, !
❖ for, while,!
❖ extern, main, return!
❖ Variables !
❖ x, y, discount, substr!
❖ Constants (eg: 10, 20),!
❖ Strings (eg: “total”, “hello”)!
❖ Special symbols (eg: (), {}),!
❖ Operators (eg: +, /,-,*)

31 Source fresh2refresh.com
List of Keywords in C
❖ C has 32 keywords in all.!
❖ Homework - Look them up in the library or online
and try to understand the purpose of each keyword.

32 Source en.wikipedia.org
Run this program
#include<stdio.h>!
!
int main()!
{!
int a, b, c;!
!
printf("Enter two numbers to add\n");!
scanf("%d%d",&a,&b);!
!
c = a + b;!
!
printf("Sum of entered numbers = %d\n",c);!
!
return 0;!
}

33
Run this C Program
#include <stdio.h>!
int main()!
{!
int first, second, add, subtract, multiply;!
float divide;!
!
printf("Enter two integers\n");!
scanf("%d%d", &first, &second);!
!
add = first + second;!
subtract = first - second;!
multiply = first * second;!
divide = first / (float)second; //typecasting, otherwise this will do integer division!
!
printf("Sum = %d\n",add);!
printf("Difference = %d\n",subtract);!
printf("Multiplication = %d\n",multiply);!
printf("Division = %.2f\n",divide);!
!
return 0;!
}
34
Operators in C
Types of
S.no              Description               Example
Operators
Arithmetic_ope These are used to perform mathematical calculations
1 +, -, *, /, %
rators like addition, subtraction, multiplication, division and
Assignment modulus
These are used to assign the values for the variables in C =, +=, -+, *=, %=, ^=,
2
operators programs. &=
Relational These operators are used to compare the value of two
3 >, <, <=, >=, ==, !=
operators variables.
Logical These operators are used to perform logical operations
4 &&, ||, !
operators on the given two variables
Bit wise These operators are used to perform bit operations on
5 &, |, !, ^
operators given two variables
Conditional Conditional operators return one value if condition is  (Condition?
6
(ternary) true and returns another value is condition is false true_value:
operators
Increment / These operators are used to either increase or decrease false_value)
7 ++, —
decrement the value of the variable by one
operators
Special
8 &, *, sizeof( ) &, *, sizeof( )
operators
35 Source fresh2refresh.com
Arithematic Operators
#include <stdio.h>!
int main()!
{!
int a=40,b=20, add,sub,mul,div,mod;!
add = a+b;!
sub = a-b;!
mul = a*b;!
div = a/b;!
mod = a%b;!
printf(“Addition of a, b is : %d\n”, add);!
printf(“Subtraction of a, b is : %d\n”, sub);!
printf(“Multiplication of a, b is : %d\n”, mul);!
printf(“Division of a, b is : %d\n”, div);!
printf(“Modulus of a, b is : %d\n”, mod);!
! return 0;!
}

36 Source fresh2refresh.com
Assignment Operators
#include <stdio.h>!
int main()!
{!
! int a=40,b=20, add,sub,mul,div,mod;!
! add = a+b;!
! sub = a-b;!
! mul = a*b;!
! div = a/b;!
! mod = a%b;!
! printf(“Addition of a, b is : %d\n”, add);!
! printf(“Subtraction of a, b is : %d\n”, sub);!
! printf(“Multiplication of a, b is : %d\n”, mul);!
! printf(“Division of a, b is : %d\n”, div);!
! printf(“Modulus of a, b is : %d\n”, mod);!
! return 0;!
}
37 Source fresh2refresh.com
Relational Operators
#include <stdio.h>!
int main()!
{!
! int m=40,n=20;!
! if (m == n)!
! {!
!! printf(“m and n are equal”);!
! }!
! else!
! {!
! ! printf(“m and n are not equal”);!
! }!
! return 0;!
}

38 Source fresh2refresh.com
Logical Operators
#include <stdio.h>!
int main()!
{!
int m=40,n=20;!
int o=20,p=30;!
if (m>n && m !=0) !
{!
!printf(“&& Operator : Both conditions are true\n”);!
}!
if (o>p || p!=20) {!
!printf(“|| Operator : Only one condition is true\n”);!
}!
if (!(m>n && m !=0)) !
{!
!printf(“! Operator : Both conditions are true\n”);!
}!
else {!
!printf(“! Operator : Both conditions are true. ” \!
!“But, status is inverted as false\n”);!
}!
}
39 Source fresh2refresh.com
Bitwise Operators
Name Bitwise Operator

x y x&y x|y x^y ~x ~y


Bitwise AND &
0 0 0 0 0 1 1
Bitwise OR |
1 0 0 1 1 0 1

Bitwise XOR ^
0 1 0 1 1 1 0

Bitwise NOT ~ 1 1 1 1 0 0 0

Left Shift <<

Right Shift >>

40 Source fresh2refresh.com
Bitwise left shift / right shift
❖ Left shift operator shifts bits
#include <stdio.h>!
to the left by one bit.!
int main()!
❖ What is this equivalent to?! {!
int num=212,i;!
❖ Right shift operator shifts bits
for (i=0;i<=2;++i)!
to the right by one bit.!
printf("Right shift by %d: %d
❖ What is this equivalent to?! \n",i,num>>i);!
printf("\n");!
❖ Bitwise operators are fast
for (i=0;i<=2;++i) !
compared to other operations!
printf("Left shift by %d: %d\n",i,num<<i); !
❖ Useful in creating bitfields return 0;!
and building boolean masks }

41
Conditional Operators
#include <stdio.h>!
int main()!
{!
! int x=1, y ;!
! y = ( x ==1 ? 2 : 0 ) ;!
! printf(“x value is %d\n”, x);!
! printf(“y value is %d”, y);!
}

42 Source fresh2refresh.com
Increment/Decrement Operators
Postfix notation
//Example for post increment operators! //Example for post decrement operators!
! !
#include <stdio.h>! #include <stdio.h>!
int main()! int main()!
{! {!

int i=1;! int i=20;!

while(i<10)! while(i>10)!

{! {!

printf("%d ",i);! printf("%d ",i);!


i--;!
i++;!
} !
} !
}
}
Source fresh2refresh.com
43
Increment/Decrement Operators
Prefix notation
//Example for increment operators! //Example for decrement operators!
! !
#include <stdio.h>! #include <stdio.h>!
int main()! int main()!
{! {!
int i=0;! int i=10;!
while(++i < 5 )! while(--i > 5 )!
{! {!

printf("%d ",i);! printf("%d ",i);!

}! }!

return 0;! return 0;!

} } Source fresh2refresh.com

44
Special Operators
❖ #include <stdio.h>!
❖ int main()!
❖ {!
int a=40,b=20, c=70;!
add = a+b;!
sub = a-b;!
mul = a*b;!
div = a/b;!
mod = a%b;!
printf(“Address of a is : %d\n”, &add);!
printf(“pointer to a is %p\n”, &c);!
return 0;!
❖ }

45 Source fresh2refresh.com
pseudocode
❖ Algorithm to Convert From Decimal To Another Base!
❖ Let n be the decimal number. !
❖ Let m be the number, initially empty, that we are converting to. We'll be
composing it right to left. !
❖ Let b be the base of the number we are converting to. !
❖ Repeat until n becomes 0 !
❖ Divide n by b, letting the result be d and the remainder be r. !
❖ Write the remainder, r, as the leftmost digit of b. !
❖ Let d be the new value of n.

46
Number System Exercises

❖ Convert 325 into Binary!


❖ Convert it back to Decimal in a program!
❖ Lets write the psuedocode for it!
❖ Assignment : Write psuedocode for the above

47
Basic structure of a C Program

48 Source thecrzayprogrammer.com
Type declarations & definitions
❖ A variable must be declared before it can be used!
❖ Rule 1: Declare first, use later!
❖ Examples of type definitions!
int a;!
int a, b, c;!
char x, y, z = ‘c’;!
float x = 3.14; z = x + 1;!
int a = 3*4*2;!
int a, b, c, d;!
a=b=c=d=10;!
❖ Implicit and Explicit type conversions!
❖ Rule 2: Types get promoted or demoted based on assignment

49
Type Conversion Rules
❖ 1. Arithmetic operation between integer and integer will always result in an
integer.!
❖ 2. Arithmetic operation between float and float will always give float number.!
❖ 3. Arithmetic operation between float and integer will always give float
number. In this case, first integer will be promoted to float after that the
arithmetic operation will take place.!
❖ Run through examples + practise session

50 Source crazyprogrammer.com
51 Source crazyprogrammer.com
Control Structures
❖ Decision Control Structure!
❖ If-then-else!
❖ Repetition Control Structure!
❖ for!
❖ while!
❖ do-while

52
Run this program
#include <stdio.h>!
int main()!
{!
float amnt,famnt,dis;!
printf("Enter the total amountn");!
scanf("%f",&amnt);!
famnt=amnt;!
if (amnt > 2000) {!
printf("You are eligible for discount\n”);!
dis=0.1*amnt;!
famnt=famnt-dis;!
}!
printf("final amount is %f”,famnt);!
return 0;!
}
53 Source crazyprogrammer.com
Run this program
#include <stdio.h>!
int main()!
{!
int num;!
printf("Enter a number to check if it is negative:n");!
scanf(“%d”, &num);!
if(num < 0) {!
printf("Number is negative"); !
}!
else {!
printf("Number is positive");!
}!
return 0;!
}
54 Source crazyprogrammer.com
Examples of decision control
What happens to these ?!
if(3+2) {!
printf(“This will print everytime”); }!
if(6/2+4) {!
printf(“This will print everytime”); }!
if(0) {!
printf(“This will never execute”); }!
else {!
printf(“This will print everytime”); }

55 Source crazyprogrammer.com
Examples of Repetition
#include <stdio.h>!
#include <stdio.h>!
!
int main()! int main()!
{! {!
int i=1;! int x;!
while(i<=10)! for(x=0; x<11; 10;x++)!
{! printf("Say %d”,x);!
printf(“%d”, i);! return 0;!
i=i+1;! }!
}! !
do!
#include <stdio.h>!
!
{!
int main()!
! printf(“This executes at least once\n”);!
{!
} while (1 > 2)!
int i;!
return 0;!
for(i=1;i<11;printf(“%d",i++));!
}
return 0;!
56 } Source crazyprogrammer.com
Let’s Scratch some programs!!

57
Nesting
❖ Defining and using statements within the scope of a
similar statement. !
❖ Nesting if-then-else statements!
❖ Nesting Loops!
❖ Nesting for loops!
❖ Nesting while loops!
❖ Nesting for loop within a while loop and vice
versa

58
Nesting example - Try this
#include <stdio.h>!
int main()!
{!
! int row,c ol;!
! for(row=1; row < 10; row++)!
! {!
!! for(col=1; col < 4; col++)!
!! {!
! ! printf(“%d, %d \n”,row,col);!
!! }!
! }!
! return 0;!
}
59
More on Data Types
Memory Format
Data Type (bytes) Range Specifier
short int 2 -32,768 to 32,767 %hd
unsigned short int 2 0 to 65,535 %hu
unsigned int 4 0 to 4,294,967,295 %u
int 4 -2,147,483,648 to 2,147,483,647 %d
long int 4 -2,147,483,648 to 2,147,483,647 %ld
unsigned long int 4 0 to 4,294,967,295 %lu
long long int 8 -(2^63) to (2^63)-1 %lld
unsigned long long int 8 0 to 18,446,744,073,709,551,615 %llu
signed char 1 -128 to 127 %c
unsigned char 1 0 to 255 %c
float 4 %f
double 8 %l
long double 12 %Lf

60
Run this program - Sizeof() datatypes
//Lets determine the size of different data types!
#include <stdio.h>!
int main()!
{!
int a = 1; float f = 2.99; double d = 3.14; !
char c ='G';!
printf("Hello! I am a character. My value is %c and "!
"my size is %lu byte.\n", b, sizeof(char));!
//can use sizeof(c) above as well!
printf("Hello! I am an integer. My value is %d and "!
"my size is %lu bytes.\n", i, sizeof(int));!
//can use sizeof(i) above as well!
printf("Hello! I am a double floating point variable."!
" My value is %lf and my size is %lu bytes.\n”,c, sizeof(double));!
//can use sizeof(d) above as well!
// Do this for all the datatypes listed above so you get an idea of the range of values and no. of bytes for each
one on your computer!
return 0;!
}
61
Assignment for this week
1. Write a C program to print out the Fibonnacci series up to less than a no. that
you enter!
❖ For example, output should display !
❖ Enter an integer: 50!
❖ Fibonacci Series: 0,1,1,2,3,5,8,13, 34!

2. Write a C program to print out the ASCII table from 0-127. Print out the ASCII
value and the char. !
❖ Hint: You can use integer operations on the char datatype!

3. Write a C program to find out the number of digits in an integer!

4. Write a C program to print out the factorial of a number using a Do-While loop

62
Start Thinking Algorthmically
How do you determine the factors of a given number?!
!
#include <stdio.h>!
// We are trying to print the factors of an integer.!
int main() {!
!int n,i;!
!printf("Enter a number:\n");!
!scanf("%d",&n);!
!printf("1 ");!
!for(i=2;i<=(n/2);i++) {!
!! if((n%i)==0)!
!! ! printf("%d ",i);!
!}!
!printf("and %d\n”,n);!
!return 0;!
}

63
Start Thinking Algorthmically
// How do you determine if a number is Prime?!
!
#include <stdio.h>!
int main() {!
! int n,i, c = 0;!
! printf("Enter a number:\n");!
! scanf("%d",&n);!
! printf("1 ");!
! for(i=2;i<=(n/2);i++) {!
! ! if((n%i)==0) c++;!
! }!
! if (!c) !
printf(“The number %d is prime\n”,n);!
else!
printf(“The number %d is NOT prime\n”,n);!
!
! return 0;!
}

64
Printing ASCII Values
❖ Printing out all ASCII values! ❖ Printing out ASCII value for a given character!
❖ #include <stdio.h>! ❖ #include <stdio.h>!
❖ int main()! ❖ int main()!
❖ {!
❖ {!
❖ int i;!
❖ int e;!
❖ i=0;!
❖ char ch;!
❖ do!
❖ printf("\n Enter a character : ");!
❖ {!
❖ printf("%d %c \n",i,i);!
❖ scanf("%c",ch);!
❖ i++;! ❖ e=ch;!
❖ }! ❖ printf("\n The ASCII value of the character
❖ while(i<=255);!
is : %d",e);!

❖ return 0;!
❖ return 0;!
❖ } ❖ }

65
Basic guidelines of algorithms
❖ Understand the problem!
❖ What is the output!
❖ Specify the output, its format and limits if any!
❖ What is the input!
❖ Specify the input, its format and limits if any!
❖ Starting point!
❖ What are the actions to be performed!
❖ Are there any decisions to be made!
❖ Do we need to repeat any actions?!
❖ Are there any exceptions to the rule?!
❖ End point!
❖ What are the compiler / system considerations? - Advanced topic
66
Rules of functions()
❖ Break down large computing tasks into small manageable
chunks of code!
❖ Reuse what code already exists instead of reinventing the
wheel!
❖ Same code can be called from multiple places!
❖ Enhances code readability!
❖ Easier to make changes to code!
❖ Function signatures allow for compilers to detect errors
quicker
67
More about functions()
❖ Each function definition has the form!
❖ return-type function-name(argument declarations)!
❖ {!
❖ declarations and statements!
❖ }!

❖ Various parts may be absent; a minimal function is!


❖ dummy() {}!
❖ which does nothing and returns nothing
68
// Print stars in 20 rows!
!
// prints 5 stars!
void printStars() {!
printf("*****");!
}!
int main() !
{!
printStars(); // got 5 stars!
printStars(); // got 5 more stars!
// now let us print a new line and then 10 more stars!
printf("\n");!
for (i=1; i<=10; i++)!
{ !
printStars();!
printf("\n");!
!
} !
return 0;!
}

69 Source crazyprogrammer.com
#include <stdio.h>!
// An example function that takes two parameters 'x' and 'y'!
// as input and returns max of two input numbers!
int max(int x, int y) {!
if (x > y)!
return x;!
else!
return y;!
}!
// main function that doesn't receive any parameter and returns an integer.!
int main(void)!
{!
int a = 10, b = 20;!
int m = max(a, b); // Calling above function to find max of 'a' and 'b'!
printf("m is %d", m);!
return 0;!
}
70 Source crazyprogrammer.com
How do you determine if a number is Prime?!
#include<stdio.h>! Prime number
int factors(int x) {!
!int i,c=0;!
using a function()
!for(i=2;i<=(x/2);i++)!
!{ if(x%i==0) c++;!
!}!
!return c;!
}!
!
// To determine if a given number is prime, first determine whether it has any factors!
void main() {!
!int n,y;!
!printf("Enter a number:\n");!
!scanf("%d",&n);!
!y=factors(n);!
!if(y==0)!
!! printf("\nPrime number");!
!else !
!! printf("\nNot a prime number");!
}
71
More about functions()
❖ A function is a piece of code that contains!
❖ A set of statements!
❖ A set of instructions!
❖ Takes some specific inputs!
❖ Produces specific outputs!
❖ Some examples of functions

72
Function Declaration
❖ Function declaration tells the compiler about :!
❖ number of parameters function takes, !
❖ data-types of parameters and !
❖ return type of function. !
❖ Putting parameter names in function declaration is optional in function declaration!
❖ Mandatory to specify them in the definition.!
❖ Example declarations!
❖ int max(int, int); // A function that takes two integers as parameters and returns an
integer!
❖ int thisfunc(char, int); // A function that takes a char and an int as parameters and
returns an integer!
❖ int compute(int x, float t, char c); // declaration that takes an int, float and char,
returning an int

73 Source crazyprogrammer.com
C Libraries - Pre-defined functions
S.No Header file Description

1 stdio.h This is standard input/output header file in which Input/Output!


functions are declared

2 conio.h This is console input/output header file (found only on some compilers)

3 string.h All string related functions are defined in this header file

4 stdlib.h This header file contains general functions used in C programs

5 math.h All maths related functions are defined in this header file

6 time.h This header file contains time and clock related functions

7 ctype.h All character handling functions are defined in this header file

8 stdarg.h Variable argument functions are declared in this header file

9 signal.h Signal handling functions are declared in this file

10 setjmp.h 74
This file contains all jump functions
Library Functions
❖ What is a Library?!
❖ In programming, a library is a collection of precompiled routines that a
program can use. The routines, sometimes called modules, are stored
in object format. Libraries are particularly useful for storing frequently
used routines because you do not need to explicitly link them to every
program that uses them.!
❖ What is the Standard C Library?!
❖ The C language is accompanied by a number of standard library
functions which carry out various useful tasks. In particular, all input
and output operations (e.g., writing to the terminal) and all math
operations (e.g., evaluation of sines and cosines) are implemented by
library functions.
75
Run this program - Area of a Triangle
/*!
* C program to find the area of a triangle, given three sides. Notice that multi-line
comments are enclosed using /* and */!
*/!
! #include <stdio.h>!
! #include <math.h>!
! int main()!
! {!
! int s, a, b, c, area;!
!
! printf("Enter the values of a, b and c \n");!
! scanf("%d %d %d", &a, &b, &c);!
! /* compute s */!
! s = (a + b + c) / 2;!
! area = sqrt(s * (s - a) * (s - b) * (s - c));!
! printf("Area of a triangle = %d \n", area);!
! return 0;!
!}
76
Parameter Passing in functions()
❖ Actual Parameters - parameters passed to function !
❖ Formal Parameters - parameters received by the function. !
❖ Two methods to pass parameters!
1. Pass by Value!
❖ values of actual parameters are copied to function’s formal parameters!
❖ the two types of parameters are stored in different memory locations. !
❖ any changes made inside functions are not reflected in actual parameters of caller.!
2. Pass by Reference !
❖ Both actual and formal parameters refer to same locations,!
❖ any changes made inside the function are actually reflected in actual parameters of
calling function.!
❖ C always passes parameters by value by default

77 Source crazyprogrammer.com
Parameter Passing by Value
#include <stdio.h>!
void setx(int x)!
Actual Formal
{! Paramet Parameter
er
x = 30;!
}!
x= 20 x=
int main(void)!
30
{!
int x = 20;!
setx(x);!
printf("x = %d", x);!
return 0;!
}

78 Source crazyprogrammer.com
Parameter Passing by Reference
#include <stdio.h>!
void setx(int *x)!
Actual Formal
{! Paramet Parameter
er
*x = 30;!
}!
x= x=
int main(void)!
30 30
{!
int x = 20;!
setx(&x);!
printf("x = %d", x);!
return 0;!
}

79 Source crazyprogrammer.com
More about functions()
❖ main() function always called by the operating system when a
program is executed.!
❖ Every function has a return type. If a function doesn’t return any
value, then void is used as return type.!
❖ Functions can return any type except arrays and functions. We can
get around this limitation by returning pointer to array or pointer
to function. - Cover this next week!
❖ Empty parameter list in C mean that the parameter list is not
specified and function can be called with any parameters. !
❖ If a function should be called without any parameters and is not
returning anything, better to use “void fun(void)”.
80 Source crazyprogrammer.com
#include<stdio.h>!
float square ( float x ); // function prototype, also called function declaration !
!
int main( ) // main function, program starts from here!
{!
float m, n ;!
printf ( "\nEnter some number for finding square \n");!
scanf ( "%f", &m ) ;!
n = square ( m ) ; // this is the function call !
printf ( "\nSquare of the given number %f is %f",m,n );!
}!
float square ( float x ) // function definition, pass by value!
{!
float p ;!
p = x * x ;!
return ( p ) ;!
}
81 Source crazyprogrammer.com
functions() Recap
❖ Function declaration or prototype !
❖ function return_type
❖ This informs compiler about the
declaration function_name
function name, function ( argument list );
parameters and return value’s
data type.! ❖ function return_type
definition function_name
❖ Function call! ( arguments list )!
❖ Actual point in the program { Body of function; }
where the function is called!
❖ function function_name
❖ Function definition! call ( arguments list );
❖ All the statements to be executed
within the function call.

82 Source fresh2refresh.com
#include<stdio.h>!
// function prototype, also called function declaration!
void swap(int a, int b); !
int main()! Pass by Value Example
{!
int m = 22, n = 44;!
// calling swap function by value!
printf(" values before swap m = %d \nand n = %d", m, n);!
swap(m, n); !
}!
void swap(int a, int b)!
{!
int tmp;!
tmp = a;!
a = b;!
b = tmp;!
printf(" \nvalues after swap m = %d\n and n = %d", a, b);!
}
83
#include<stdio.h>!
// function prototype, also called function declaration!
void swap(int a, int b); !
int main()! Pass by Reference Example
{!
int m = 22, n = 44;!
// calling swap function by reference!
printf(" values before swap m = %d \nand n = %d", m, n);!
swap(&m, &n); // call using the address of the actual variables !
}!
void swap(int *a, int *b) // integer pointers as parameters!
{!
int tmp;!
tmp = *a;!
*a = *b;!
*b = tmp;!
printf(" \nvalues after swap m = %d\n and n = %d", a, b);!
}
84
Variable Scope
❖ Specifies the validity and life time of the variable!
❖ Scope of a variable may vary from!
❖ Global - accessible to the entire program including all
functions defined in the current file and other files!
❖ main - accessible to the main program and code that is
written in main()!
❖ function level - accessible to code written within the function!
❖ block level - accessible only within the block that it is defined
(if-else, while, do-while), etc.

85
#include <stdio.h>!
int x = 100;! Variable Scope - Run this
void testscope() {!
! int i = 70;!
program
! printf("function scope %d \nglobal scope %d \n", i, x);!
}!
int main(void) {!
! // your code goes here!
! int i = 10;!
! printf("main scope %d \nglobal scope %d \n", i, x);!
! testscope();!
! if (i) {!
! ! int i = 50;!
! ! printf("block scope %d \nglobal scope %d \n", i, x);!
! }!
! return 0;!
} 86
❖ auto: !


Storage Classes in C
default storage class for all variables declarations, hence rarely used explicitly while writing code.!

❖ Scope is local and hence auto variables can be only accessed within the block/function they have been declared !

❖ Can be accessed within nested blocks and outside their scope through pointers.!

❖ assigned a garbage value by default whenever they are declared.!

❖ extern: !

❖ Used to indicate that a variable is defined elsewhere and not within the same block where it is used. !

❖ Even if value is assigned to it in a different block it can be changed in the current block. !

❖ Akin to global variable. If extern keyword is used, the same global variable will be accessed.!

❖ Useful for sharing information between two different files!

❖ static: !

❖ Variable whose value once initialised remains the same.!

❖ Value preserved even if out of scope!

❖ By default initialised to 0 by the compiler!

❖ register: !

❖ Compiler allocates memory from the registry for a variable defined with the ‘register’ qualifier. !

❖ Leads to much faster run-time execution.!

❖ Cannot access the address of register variables through pointers.


87
Variable Scope
❖ #include <stdio.h>! ❖ void f(int d){!
❖ void f(int d);!
❖ static int a = 0;!
❖ int a = 1, b = 2, c = 3, d = 4;!
! ❖ a = a + 7;!
❖ int main(){! ❖ b = a + d;!
❖ int a = 5, c = 6;!
❖ f(a);!
❖ c++;!
❖ f(b);! ❖ d--;!
❖ f(c);!
❖ printf("%d %d %d %d
❖ printf("%d %d %d %d\n",a,b,c,d);!
\n",a,b,c,d);!
❖ return 0;!
❖ } ❖ }
88
Do the following
Write a program called calculate.c and define a function that takes as input two
integers and returns the sum of these two integers!
Use pass by value!
Now modify the program to write 3 more functions to do subtraction, division,
multiplication. Each function take two values as input and a third char that
specifies arithmetic operation!
Call the functions add(), subtract(), multiply(), divide()!
a - addition, s - subtraction, m - multiplication, d - division!
For example: !
calculate 2 3 a or calculate 2 3 m!
the program would then execute add(2, 3) and multiply(2, 3)
89
Assignment for the Week
1. Write a program called polygon defined in polygon.c that
calculates the area of a polygon. !

• Define functions for each polygon. !

• Use pass by value. !

• Assume all sides of the polygon are equal. !

• The inputs to the program are the two integers - the length of the
side and the number of sides. !

• Use if-else statement.!

2. Modify the calculate program to use parameter passing by


reference
90
Pointers
int x = 1, y = 2;!
int *ip; // ip is a pointer to int !
ip = &x; // ip now points to x!
y = *ip; // y is now 1!
*ip = 0; // x is now 0!
int z[10];!
ip = &z[0]; // ip now points to z[0] !
const char *sp = “Hello World”;
91
More on pointers
If ip points to the integer x, then *ip can occur in any context
where x could, !
so *ip = *ip + 10; increments *ip by 10.!
what do the following expressions do?!
• y = *ip + 1!
• *ip += 1!
• ++*ip!
• (*ip)++!
• int *iq; iq = ip;
92
Call by Value! Call by Reference!
! !

void swap(int x, int y) !


void swap(int *x, int *y) !

{! {!

int temp;! int temp;!

temp = x;! temp = x;!

x = y;! x = y;!

y = temp;! y = temp;!

}! }!

……! ……!

int main()! int main()!

{! {!
……! ……!
swap (a,b); // Call by value! swap (&a, &b); // Call by referece!
…..! …..!
} }
93
#include <stdio.h>!

!
int factorial(int i)! Factorial using Recursion
{!

! if (i < 1)!

! ! return 1;!

! else!

! ! return (i * factorial(i-1));!

}!

int main(void) {!

! int i;!

! scanf ("%d", &i);!

! printf("factorial of %d is %d",i, factorial(i));!

! return 0;!

}
94
#include<stdio.h>! GCD/LCM using
int gcd ( int a , int b ) // program by Leon Fernandes!
{! Recursion
if ( a % b == 0 )!
! return b ;!
else!
! return gcd ( b , a % b ) ;!
}!
int main ()!
{!
int m , n , g ;!
printf ( "Enter two numbers :" ) ;!
scanf ( "%d%d", & m, & n ) ;!
g = gcd ( m , n ) ;!
printf ( "\nGcd = %d\nLcm = %d\n", g , m * n / g );!
}

95
Group sessions
❖ Write a program using if-else, functions, printf, scanf, operators, while
loops!
❖ checking for non-zero value!
❖ negative or positive!
❖ prime no!
❖ if not find its factors!
❖ then determine the ascii value!
❖ Roots of Quadratic equation using functions!
❖ LCM & HCF

96
Arrays & Strings
❖ Arrays are Contiguous location of memory allocated to a well-defined number of
identical data types.!
❖ Each individual member of an array is identified by its index!
❖ Example Array declaration !
❖ int x[10];!
❖ char str[5]; //String is a fixed length array of chars!
❖ long double dbl[7];!
❖ float discount[3] = { 2.5, 3.5, 4.5 }!
❖ int vibgyor[] = { 1, 2, 3, 4, 5, 6, 7}!
❖ int *addr[10];!
❖ String is a fixed length array of chars
97
Strings - gets and puts
#include<stdio.h>!
// You can read and wtite strings using either scanf or puts and gets!
int main() {!
! char str[20];!
! printf("Enter a string: ");!
! gets(str);!
// puts writes the string s and a newline to stdout. !
! puts(str);!
printf("\nEnter another string: ");!
! scanf("%s",str);! ! ! // IMPORTANT: Notice no "&", why?!
printf("\nEnter another string: ");!
! printf(“%s",str);!
return 0;!
}

98
#include<stdio.h>!
#include<string.h> // You need this to use string operation functions like strlen(see below)!
// This shows that a string is nothing but a sequence of characters.!
// and you can access the individual characters if you want.!
int main() {!
! char str[50];!
! int n,i;!
! printf("Enter string:\n");!
! gets(str);!
! n=strlen(str);!
! for(i=0;i<n;i++)!
! { printf("\n%c",str[i]);!
! }!
! return 0;!
}
99
#include<stdio.h>!
// print characters and their corresponding ASCII values!
#include<string.h>!
int main() {! Printing ASCII Values
! char str[50];!
! int i,n;!
! printf("Enter a string:\n");!
! gets(str);!
! n=strlen(str);!
! printf("\nChar ASCII\n");!
! for(i=0;i<n;i++)!
! {!
! ! printf("%c %d\n",str[i],str[i]); // shows how a character !
// can be interpretted as an integer.!
! }!
! return 0;!
}

100
More On Strings
❖ Write a program that copies one string to another!
❖ Write a program that searches for a character in a string!
❖ Write a program that reverses two strings!
❖ Write a program that splits a string into two halves!
❖ Print all possible strings that can be made by placing
spaces!
❖ Find if a string is a palindrome!
❖ Find if a string is an Anagram of another
101
#include<stdio.h>!
More on Arrays
int main()!
int findmin(int a[], int n){!
{!
! int x[5];! int min;!
! int i, sum;!
if ( n==1 )!
! for(i=0;i<5;i++)!
! {! return a[0];!
!! scanf(“%d”,&x[i]);!
min=findmin(a+1,n-1);!
! ! sum+=x[i];!
! }! if (a[0] < min )!
! printf(“sum of array is %d \n”, sum);!
min=a[0];!
! write code for find min……!
! return 0;! return min;!
}
}
102
#include<stdio.h>!
int main()!
{!
char i;!
! printf(“Enter a value\n”);!
Switch-case Example
! scanf(“%c”, &i);!
! switch(i)!
{!
!! case ‘a':!
! ! ! ! printf("This will print a”); !
! ! ! ! break;!
! ! case ‘z’:!
! ! ! ! printf("This will print z”);!
! ! ! ! break;!
! ! case ‘m’:!
! ! ! ! printf("This will print p”);!
! ! ! ! break;!
! ! default:!
! ! ! ! printf("Sorry its a mismatch”);!
! ! ! ! break;!
! ! }!
! ! return 0;!
}
103
! More on Switch
❖ Switch vs if-else - which is faster?!
❖ It doesn’t allow conditions with operators.!
❖ switch (i*a)!
❖ Case cannot include an arithmetic expression!
❖ case: a++:!
❖ No floating point expressions allowed!
❖ switch (0.5)!
❖ A programmer cannot write multiple cases which will give same result.
Write a program that copies one string to another!
❖ case 7,8 : for example
104
Assignment for the week
❖ Write a program that accepts two strings as input, one
larger than the other.!
❖ Write a function and use the function to determine if the
smaller string is contained in the larger string!
❖ Use pass by reference.!
❖ Use array indexing or pointer arithmetic to access array
elements

105
#include <stdio.h>! Two dimensional arrays
int main() !

{!

! int a[2][5]; // declare a two-dimensional array!

! int i,j,k;!

!for ( i=0 ; i <2 ; i++) // Assigning values!

! ! for (j=0;j<5;j++)!

!! a[i][j]=10*i+j;!

! for ( i=0 ; i <2 ; i++) !

! {!

! ! printf("\n\nRow %d",i);!

! ! for (j=0;j<5;j++)!

!! printf("\na[%d][%d]: address:%p value:%d",i,j,&a[i][j],a[i][j]);!

!} !

! printf("\n");!

! return 0;!

}
106
#include <stdio.h>!

2D Array Example
void read_array(int a[][20], int nr,int nc){!
int i,j;!
for (i=0;i<nr;i++)!
for (j=0;j<nc;j++)!
!
scanf("%d",&a[i][j]);!
!
}!
int main() {!
void print_array(int a[][20], int nr,int nc){!
int a[20][20];!
int i,j;!
int i,j,r,c;!
for (i=0;i<nr;i++) {!
!
for (j=0;j<nc;j++)!
// Assigning values!
printf("%d ",a[i][j]);!
printf("\n");!
!
printf("\n Give num rows and num columns: ");!
}!
scanf("%d %d",&r,&c);!
}!
printf("\n Give elements row by row:\n");!
int sumelements(int a[][20], int nr, int nc){!
int i,j,sum;!
read_array(a,r,c);!

sum=0;! printf("\n Printing elements row by row:\n");!

for (i=0;i<nr;i++)! print_array(a,r,c);!

for (j=0;j<nc;j++)! printf("\n Sum of all its elements i%d",sumelements(a,r,c));!

sum+=a[i][j];! printf(“\n");!

return sum;! ! return 0;!


} }

107
Enumerated Data type
❖ Enumeration data type consists of named integer constants as a list.!
❖ enum <name > { const1, const2, …..}enum flag { const1, const2, ..., constN };!
❖ month { Jan, Feb, Mar }; // Jan, Feb and Mar variables will be assigned
to 0, 1 and 2 respectively by default !
❖ enum month { Jan = 1, Feb, Mar }; // Feb and Mar variables will be
assigned to 2 and 3 respectively by default !
❖ enum week { Mon, Tue, Wed, Thurs, Fri, Sat, Sun }; !
❖ enum month {Jan=20,Feb,Mar}; //Jan is assigned to 20. Feb and Mar
variables will be assigned to 21 and 22 respectively by default */!
❖ Starts with 0 (zero) by default and value is incremented by 1 for the
sequential identifiers in the list.

108
Enum Example
! !
#include <stdio.h>! // Example Enum declarations

int main()! enum suit {


club = 0,
{!
diamonds = 10,
! enum MONTH { Oct = 10, Nov, Dec };!
hearts = 20,
! enum MONTH month = Dec;!
spades = 3,
! if(month == 10)!
};
! ! printf(“Value of Oct”);! !
! else if(month == 11)! enum boolean { false, true };
! ! printf(“Month is Nov”);!

! if(month == 12)!

! ! printf(“Month is Dec”);!
}
109
Enum Example
#include <stdio.h>!
enum designFlags {!
! BOLD = 1, ITALICS = 2,, UNDERLINE = 4!
};!
int main() {!
! int myDesign = BOLD | UNDERLINE; !
// 00000001!
// | 00000100!
// ___________!
// 00000101!
!
! printf("%d", myDesign);!
! return 0;!
}

110
❖ User defined data type used to group
dissimilar data items into a single named
data type.!
#include <stdio.h>!
Struct
struct Point {!
❖ Example declarations!
int x;!
int y;!
❖ As a datatype!
} P1;!
struct Point !
{!
!
int x;!
int main ()!
int y;! {!
};! ! struct Point P2, *P3;!
struct Point P1, P2;! ! struct Point P4 = {0, 4};!
! struct Point P5 = {.x = 3, .y = 8};!
❖ As a variable ! scanf(“Enter point coordinates %d %d”, &P2x,
OR! &P2.y);!
struct Point {! P1.x = P2.x;!
int x;! P1.y = P2.y;!
int y;! printf(“Point coordinates are: %d %d\n”, P1.x, P1.y);!
} P1, P2;! P3->x = P4.x;!
P3->y=P4.y;!
❖ As a typedef ! printf(“Point coordinates are: %d %d\n”, P3.x, P3.y);!
typedef struct Point {! printf(“Point coordinates are: %d %d\n”, P5.x, P5.y);!
int x;! !
int y;! return 0;!
} P1, P2; };
111
Typedef
typedef unsigned int uint;!
❖ symbolic name for a variable typedef unsigned char BYTE;!
typedef struct Points {!
declaration.! int x;!
int y;!
❖ An alias for a variable! } point_t;!
point xcrd, ycrd;!
!
❖ In C typedef is akin to a storage point_t * retStructPtr(struct Points p)!
{!
class, hence cannot be used ! return &p;!
}!
with other storage classes! !
int main() {!
❖ Example! ! int i;!
! char c;! !
typedef unsigned int uint;! ! unsigned int u;!
typedef unsigned char BYTE;! ! unsigned char uc;!
! uint ui;!
typedef struct Points {!
! BYTE uchar!
int x;! ! struct point x;!
int y;! ! point_t y; !
} point_t;! ! point_t * py;!
point xcrd, ycrd; !
…….!
!
112 }
Array of Structs
!
int main() {!
#include <stdio.h>!
! Point pts[10]; // an array of 10 structs, just
typedef struct Point { !// use typdef if like an array of integers !
! int i,n;!
you need to declare many struct variables! ! int s1, s2, s3; // scale values!
! int theta; // rotation angle!
float x,y, z;!
! printf(“How many points ? : “);!
} Point;! ! scanf(“%d",&n);!
! for (i=0;i<n;i++) {!
int translate(Point *p, int s1, int s2, int s3)! ! ! scanf(“%f %f
%f”,&pts[i].x,&pts[i].y,&pts[i].z);!
{! ! ! printf("%f %f \n”,pts[i].x,pts[i].y,
pts[i].z);!
! p->x = p->x + s1;! ! }!
! printf(“\n\n\n");!
! p->y = p->y + s2;! ! scanf(“%d %d %d”, &s1, &s2, &s3);!
! translate(&pts[0], s1, s2, s3);!
! p->z = p->z + s3;! ! printf("%f %f %f\n”,pts[0].x, pts[0].y,
pts[0].z);!
! return 0;! ! !
! return 0;!
} }
113
Unions
❖ Union is a keyword in C which signifies a user-defined data type like the
Struct!
❖ Main characteristic of Union is that it can take on different forms based
on different conditions!
❖ For example,!
Union alphaNumeric {!
int number;!
char alphabet;!
};!
union alphaNumeric ant;!
❖ At any given point, the variable ant will store only valid one datatype,
either an int or a char, not both.!
❖ Memory is allocated enough for the largest Union member!
❖ It the user’s responsibility to keep track of which datatype is stored at
what point
114 Source: thecrazyprogrammer.com
Union Example
#include <stdio.h>!
union test!
{!
! unsigned int x;!
! unsigned char y;!
! int z;!
};!
int main()!
{!
! union test t;!
! t.x = 5;!
! t.y = 4;!
! t.z = 1;!
! printf("t.x = %d, t.y = %d, t.z = %d\nsize of t = %d”, t.x, t.y, t.z, sizeof(t));!
! return 0;!
}
115 Source: geeksforgeeks.com
Bit-Fields
Optimizing memory usage for greater

❖ Use int: 0 to force bit field
efficiency!
boundary to the next byte!
❖ For example, size of a date can be stored in !
❖ unsigned int size! ❖ Arrays of bit fields are not
❖ 4 bytes of unsigned int can have the value 2 allowed!
power 64. Do we need to use such a large
data type? NO!!! ❖ Pointers to bit-fields are not
❖ To optimize memory, we declare:! allowed.!
unsigned int size : 4;!
short unsigned int size : 4!
Struct date {!
❖ Assigning values larger than
unsigned int day: 5;! what the bit-field can hold
unsigned int month: 4;!
will give unpredictable
unsigned int year;!
}; results.
116
Bit-Field Example
0 1 2 3 4 5 6

a b c d e f g

typedef struct A {! Field Byte Offfset Bit Offset


int a : 8;! a 0 0
int b : 10;!
b 1 0
int c : 12;!
c 2 2
int d : 4;!
int e : 3;! d 3 6
int : 0;! e 4 2
int f : 1;!
f 5 0
char g;!
g 6 0
} A_t;

117
Source: http://www-01.ibm.com/support/knowledgecenter
Bit-Field Example
❖ #include <stdio.h>! ❖ int main()!
❖ // A simple representation of date! ❖ {!
❖ struct date_1!
❖ {!
❖ printf("Size of date is %d bytes\n",
❖ unsigned int d;!
sizeof(struct date_1));!
❖ unsigned int m;! ❖ struct date_1 dt1 = {31, 12, 2014};!
❖ unsigned int y;!
❖ printf("Date is %d/%d/%d", dt1.d, dt1.m,
❖ };!
dt1.y);!
❖ // A space optimized representation of date!
❖ struct date_2!
❖ printf("Size of optimized date is %d bytes\n",
❖ {!
sizeof(struct date_2));!
❖ // d has value between 1 and 31, so 5 bits are sufficient! ❖ struct date_2 dt2 = {1, 1, 2017};!
❖ unsigned int d: 5;!
❖ printf("Date is %d/%d/%d", dt2.d, dt2.m,
❖ // m has value between 1 and 12, so 4 bitsare sufficient!
dt2.y);!
❖ unsigned int m: 4;!
❖ unsigned int y;!
❖ return 0;!
❖ }; ❖ }

118 Source: tutorials point.com


Memory Management
❖ Memory for variables are allocated at compile time!
❖ Some variables are allocated memory during run time.!
❖ Specifically memory can be allocated at run time programmatically through calling specific
functions!
❖ // allocates memory of num elements each of which size in bytes will be size. The allocated
memory is initialised!
❖ void *calloc(int num, int size);!
❖ // allocates memory of num bytes and leaves them uninitialized.!
❖ void *malloc(int num);!
❖ // This function re-allocates memory extending it upto newsize.!
❖ void *realloc(void *address, int newsize);!
❖ // release a block of memory block specified by address.!
❖ void free(void *address);

119
Memory Management Example
❖ int main()!
❖ {!
❖ int *arr;!
❖ !
❖ // malloc() allocate the memory for 5 integers!
❖ // containing garbage values!
❖ arr = (int *)malloc(5 * sizeof(int)); // 5*4bytes = 5 bytes!
❖ !
❖ // Deallocates memory previously allocated by malloc() function!
❖ free( arr );!
❖ !
❖ // calloc() allocate the memory for 5 integers and!
❖ // set 0 to all of them!
❖ arr = (int *)calloc(5, sizeof(int));!
❖ !
❖ // Deallocates memory previously allocated by calloc() function!
❖ free(arr);!
❖ return(0);!
❖ }

120
Function Pointers
!

❖ Function pointer stores the start of executable code and points to


code and not data.!
❖ Function pointers don’t require allocation and de-allocation of
memory.!
❖ Example declaration of function pointers:!
❖ int (* fptr) (int, int);!
❖ A function’s name can also be used for the functions’ address.!
❖ Function pointers can be passed as parameters to other functions
just like data pointers.
121
Function Pointer Declaration
// Program to illustrate declaration of a function pointer and calling function through a pointer!
#include <stdio.h>!
int printValue(int x)!
{!
!printf("Value passed is %d\n", x);!
! return 0;!
}!
int main()!
{!
! int (* fptr) (int); ! !
! fptr = &printValue;! // fptr = printValue is also valid in the case of function pointers!
!(*fptr) (7); ! // call the function!
!return 0;!
}

122
Function Pointer Arrays
// Program to illustrate array of function pointers!
#include <stdio.h>!
void add(int x, int y)!
{!
printf("Adding 2 numbers %d\n", x+y);!
}!
void subtract(int x, int y)!
{!
printf(“Subtracting 2 numbers%d\n", x-y);!
}!
void multiply(int x, int y)!
{!
printf(“Multiplying 2 numbers %d\n", x*y);!
}!
!
int main() !
{!
! short int choice;!
! void (* fptrarr[] ) (int, int) = {add, subtract, multiply};!
! printf("Enter Choice: 0 for add, 1 for subtract and 2 for multiply\n");!
! scanf("%d", &choice);!
! if (choice < 0 || choice > 2) !
! ! return 0;!
! ( * fptrarr[choice]) (23, 56);!
! return 0;!
}

123
Function Pointers as Function Parameters
// A simple C program to show function pointers as parameter!
#include <stdio.h>!
!
// Declare prototype of sorting functions!
extern int bubbleSort (int * arr[]);!
extern int heapSort(int * arr[]);!
!
// A function that receives a simple function as parameter and calls the function!
void sortArray(int *arr, int (* sortfunc)(int * arr[]))!
{!
!sortfunc(arr);!
! for (int i=0; i < sizeof(arr); i++)!
! ! printf(“%d”, arr[i]);!
! printf(“\n”);!
}!
!
int main()!
{!
! int array[] = {9, 34, 67, 28, 2, 7};!
! char c;!
! printf(“Sort using which algorithm?”);!
! scanf(“%c”, &c);!
!if (c == ‘b’)!
! ! sortArray(bubbleSort);!
! elseif (c == ‘h’)!
! ! sortArray(heapSort);!
!
!return 0;!
}

124
C Preprocessor and Macros
❖ The C Preprocessor is a text substitution tool that is executed before the C Compiler!
❖ All CPP commands begin with ‘#’ symbol!
❖ Typical commands include:!
❖ #include <stdio.h> or #include “myfile.h”!
❖ #define TRUE 1!
❖ #define FALSE 0!
❖ #define PI 3.14159!
❖ #define celtofar(x) ( (x*9/5)+32)!
❖ #define fartocel(x) ((x-32)*5/9!
❖ #define MAX(x,y) ((x) > (y) ? (x) : (y))!
❖ #undef LIMIT - to delete a previously defined macro!
❖ #define LIMIT 100
125
C Preprocessor and Macros
!
❖ Conditional Compilation!
❖ Use #if, #ifdef, #ifndef, #else, #elif, #endif!
❖ #ifdef __unix__ /* __unix__ is usually defined by compilers targeting Unix systems */!
❖ # include <unistd.h>!
❖ #elif defined _WIN32 /* _Win32 is usually defined by compilers targeting 32 or 64 bit Windows
systems */!
❖ # include <windows.h>!
❖ #endif!
❖ User defined error messages!
❖ #ifdef DEBUG!
❖ #error “This is a debug build”!
❖ #endif

126
Common CPP Commands
Directive Description

#define Substitutes a preprocessor macro


#include Inserts a particular header from another file
#undef Undefines a preprocessor macro
#ifdef Returns true if this macro is defined
#ifndef Returns true if this macro is not defined

#if Tests if a compile time condition is true

#else The alternative for #if

#elif #else an #if in one statement

#endif Ends preprocessor conditional

#error Prints error message on stderr

#pragma Issues special commands to the compiler, using a standardized method

127
File I/O
❖ File I/O == File Input/Output == Reading and writing from and to a file!
❖ To access a file,!
❖ declare a file pointer of type !
❖ FILE * fp; // FILE is a predefined type!
❖ Open a file using fopen!
❖ FILE *fopen( const char * filename, const char * mode );!
❖ Read and write on a file!
❖ Use fgetc, fgets to read!
❖ Use fputc, fputs to write!
❖ fprintf and fscanf are used formatted read write much like scant and printf!
❖ fscanf(file pointer, format string, variable addresses);!
❖ fprintf(file pointer, format string, variables);!
❖ Close a file, using close!
❖ int fclose( FILE *fp );!
❖ stdin, stdout and stderr are also file pointers which can be substituted for fp in functions that require them.!
❖ File I/O functions and corresponding types are all defined in stdio.h

128
File Open Modes
Mode Description

r Opens an existing text file for reading purpose.

w Opens a text file for writing, if it does not exist then a new

file is created. Here your program will start writing content

a Opens a text file for writing in appending mode, if it does not

exist then a new file is created. Here your program will start

r+ Opens a text file for reading and writing both.

w+ Opens a text file for reading and writing both. It first

truncate the file to zero length if it exists otherwise create

a+ Opens a text file for reading and writing both. It creates the

file if it does not exist. The reading will start from the
129
FILE I/O Example
#include <stdio.h>
!
int main()
{
FILE *fp;
char buffer[255];
!
fp = fopen("fileio.txt", "w+");
! fprintf(fp, “Hello formatted world...\n");!
! fputs(“Hello world!…\n”, fp);!
! fputs(“Testing writing to a file\n”);!
! fclose(fp);!
!
fp = fopen("fileio.txt", "r");
fscanf(fp, "%s", buffer);
printf("1 : %s\n", buffer );
!
fgets(buffer, 255, (FILE*)fp);
printf("2: %s\n", buffer );

fgets(buffer, 255, (FILE*)fp);


printf("3: %s\n", buffer );
fclose(fp);
!
! return 0;!
}

130 Source: cprogramming.com


Command Line Arguments
#include <stdio.h>!
// What does this program do?!
int main( int argc, char *argv[] ) ! ! // argc specifies the number of arguments!
{! ! ! ! ! ! ! ! // argv is a pointer to an array of strings or arguments!
!
! if (argc > 0)!
! {!
! ! printf("Number of arguments = %d\n", argc);!
! ! for (int i = 0; i < argc; i++)!
! ! {!
! ! ! printf("%s ", argv[i]);!
! ! }!
! ! printf("\n");!
! }!
! else!
! ! printf("At least one argument expected\n");!
! return 0;!
}
131
Variable Length Arguments
/* To define functions with variable number of arguments do the following: */!
#include <stdio.>!
#include <stdarg.h> ! ! // STEP 1: include this header file!
!
double average(int num,…) ! // STEP 2: Define the variable argument function with last parameter as ellipses and!
{! ! ! ! ! ! // the one before this as an int which will represent number of arguments. !
!
! va_list valist; ! // STEP 3: Create a va_list type variable in the function definition.!
! double sum = 0.0;!
!int i;!
!
!va_start(valist, num); ! // STEP 4: Use int parameter and va_start macro to initialize the va_list variable ! ! ! ! !
! ! ! // to an argument list.!
!
! for (i = 0; i < num; i++) !
! {!
! ! sum += va_arg(valist, int); !// STEP 5: Use va_arg macro and va_list variable to access each item in !
! ! ! ! ! ! ! // argument list. !
!}!
! va_end(valist); ! // STEP 6: Use a macro va_end to clean up the memory assigned to va_list variable.!
!
!return sum/num;!
}!
int main() ! // STEP 7: main driver program to test this functionality!
{!
! printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5));!
! printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));!
! return 0;!
} 132 Source: geeksforgeeks.com
Data Structures in C

133
Linked List
❖ Data Structure Abstraction!
struct node {
int id;
❖ Singly Linked List! struct node *next;
};

!
Node

! Next Next Next


100 200 300 400
Tail == NULL

! Head

❖ Doubly Linked List

Prev Prev Prev


100 200 300 400
Next Next Next

Head Tail == NULL

134
Linked List Implementation
❖ Fundamental data structure in C programs!
❖ Like arrays, linked lists are linear data structures!
❖ Unlike arrays, storage is not in contiguous memory location, but is random!
❖ Size of list can be dynamic!
❖ Data manipulation is easier in a list!
❖ Pointers are used to navigate the list!
❖ NULL pointer signifies an empty list!
❖ Beginning of the list is typically referred to as HEAD!
❖ End of the list is typically referred to as TAIL!
❖ Singly linked and doubly linked lists are typical implementations
135
Linked list implementation: Creating a
List
1. Define the structure of the node or list element, For example!
typedef struct node {
int id;
struct node *next;
struct node *prev; // for doubly linked list only
} node_t;
2. Declare pointers (good to have global pointers, head, current, tail).!
3. Create a new node!
4. Check if list is empty!
5. If empty, make the new node the Head pointer. Tail and Current
pointers will also point to the new node.

136
Linked List Implementation: Creating a
Node
1. Define a function createNode() with signature!
node_t * createNode(int val)
2. Declare a pointer variable in function createNode !
node_t * listItem;
3. Allocate memory to the node!
listItem = (struct node *) malloc(sizeof(stuct node));
4. Assign values to the node!
listItem->id = val;
listItem->next = NULL //initialize the pointer
listItem->prev = NULL // for doubly linked lists
5. Return pointer to new node !
return listItem;
137
Linked List Implementation; Deleting a
node_t * head;!
node
!
int deleteNode(struct node * ptr) !
{!
struct node * temp;!
temp = head;!
while (temp != NULL)!
{!
if (temp->next == ptr) { ! ! !
! temp->next = ptr->next;!
! temp->next->prev = temp // for a doubly linked list!
! free(ptr);!
! ptr = NULL!
! break;!
}!
else!
! temp = temp->next;!
}!
return 0;!
}
138
Linked List Implementation: Searching a
list
struct node * searchList(struct *list, int x)!
{!
! int found = 0;!
! struct node * ptr;!
! ptr = list;!
! while (ptr != NULL) { !
! if (ptr->id == x) { // assume the simple case that values are ! ! !
! ! ! ! ! ! // unique in the list!
! ! found = 1!
! ! break;!
! }!
! else!
! ! ptr = ptr->next;!
!
! return ptr; ! ! ! // return pointer to found node!
}
139
Linked List Implementation: Inserting a
node
❖ Nodes can be added to the !
1. beginning of a list!
2. end of a list!
3. after a given node in a list!
4. before a given node in a list!
Declare and define separate function for each of the above cases !
OR!
• Declare and define a single function that handles all of the above cases!
• It is best to implement as separate functions

140
Linked List Implementation: Add node to
front of list
Prev Prev Prev
100 200 300 400
Next Next Next
Tail ==
Head
NULL

50 New data value = 50

Prev Next
Call createNode(50) to allocate memory for a new node

Reset pointers and return pointer to new node


Prev Prev Prev Prev
50 100 200 300 400
Next Next Next Next
Head Ta
N

141
Linked List Implementation: Add node to
end of list
Prev Prev Prev
100 200 300 400
Next Next Next
Tail = NULL
Head

500 New data value = 500

Prev Next
Call createNode(500) to allocate memory for a new node

Reset pointers and return pointer to new node

Prev Prev Prev Prev


100 200 300 400 500
Next Next Next Next

Tail = NULL
Head
142
Stack
❖ Linear data structure abstraction that requires implementation!
❖ Last-in-first-out or First-in-last-out theme!
❖ Can be accessed only from the top or first element!
❖ Can be implemented using arrays or linked list!
❖ Operations include:!
❖ Push - Add an element to the Stack from the top!
❖ Pop- Remove an element from the stack from the top!
❖ Peek- Read the element on the top of the stack!
❖ isEmpty(), isFull() are additional functions !
❖ Stack applications include !
❖ infix to postfix conversion of arithmetic expressions!
❖ dynamic function call stack!
❖ Undo-redo operations in editors!
❖ Forward-backward page navigation in web browsers

143
Stack
❖ Using Arrays!
struct Stack {
! int size;
int top;
Stack.top = 445 445 123 89 324 int *arr;
! };

❖ Push elements on top of the stack!

!
445 123 89 324
! Stack.top = 445

❖ Pop elements from the top of the stack

445 123 89 324


Stack Using Linked Lists
❖ Push elements on top of the stack!

Prev Prev Prev


! 100 200 300 400
Next Next Next
Head Tail =NULL
!

❖ Pop elements from the top of the stack

Prev Prev Prev


100 200 300 400
Next Next Next
Head Tail =NULL

145
t#include <stdio.h>!
void printTree(treenode_t * node)!
#include <stdlib.h>!
{!
! ! // Fill in your code here!
typedef struct treenode {! ! printf("Node value is %d \n", node->data);!

int data;! ! if (node->left)!


! ! printTree(node->left);!
struct treenode *left;!
! if (node->right)!
struct treenode *right;! ! ! printTree(node->right);!
} treenode_t;! ! //printf("Node value is %d \n", node->data);!
}!
!
int main() !
/* newNode() allocates a new node with the given
{!
data and assigns NULL to left and right pointers. */!
! treenode_t * root;!
treenode_t * newNode(int data) ! ! root = newNode(0);!
{! ! root->left = newNode(1);!
! root->right = newNode(2);!
! treenode_t * node = (treenode_t *)
malloc(sizeof(treenode_t));! ! root->left->left = newNode(3);!
! root->left->right = newNode(4);!
! node->data = data;!
! !
! node->left = NULL;! ! printTree(root);!
! node->right = NULL;! ! return 0;!

! return(node);! }

} 146
Arithmetic Expressions: Infix Notation
❖ Infix notation: <operator> <operand> <operator>!
❖ 2 +3, x + y, x + (y * i), (x+y) / (s-t)!
❖ For example, in !
❖ 5+3*4 => 8 * 4 = 32 without operator precedence!

! ! => 5 + 12 = 17 with operator precedence!


❖ Order of operations!
❖ Parentheses!
❖ Exponents - (right to left)!
❖ Multiplication and Division - left to right!
❖ Addition and Subtraction - left to right!
❖ Parantheses are used to explicitly control the order of evaluation and to make the expression
more readable.!
❖ Most common form or writing expressions but difficult to parse esp. in a computer

147
Arithmetic Expressions: Prefix and Postfix
❖ Prefix notation: <operator> <operand> <operand> (Also called
Polish notation)!
❖ Postfix notation: <operand> <operand> <operator>!
❖ 2 +3 => +2 3 => 2 3 +!
❖ x - y => -xy => xy -!
❖ (x*y) + (a*b) -z=> -z+*xy*ab => xy*ab*+z-!
❖ (x ^ y) ^4/ (5 * z) + 10 => xy^4^5z*/10+!
❖ No ambiguity about precedence in complex expresssions!
❖ Algorithm to convert infix to postfix
148
Infix to postfix algorithm
❖ Read the infix expression!
❖ Initialize a string array to hold the postfix expression!
❖ For each character in the input expression, check the following!
❖ Begin the loop until end of expression is reached!
❖ If the character is an operand store into the output string!
❖ If the character is an open parenthesis push onto the stack!
❖ If the character is an operator, compare the precedence of the operator with the one on the top of the
stack.!
❖ if operator’s precedence is greater then push it onto the stack!
❖ if operator’s precedence is less than or equal then pop the top of the stack and add to the string until
operator’s precedence is greater than top of the stack!
❖ If character is a close parenthesis, keep popping the stack and adding to the string, until you reach a
matching open parenthesis. Discard the parenthesis!
❖ Continue the loop until the end of expression.!
❖ Evaluate the expression now from left to right

149
Infix to Postfix Pseudocode
Parse the infix expression from left to right!
infix2postfix(expstr)!
{!
Stack_t * S;!
char * postfixStr!
for i = 0 to strlen(expstr)!
{!
if (expstr[i] == operand)!
add operand to postfixStr!
else if expstr[i] == ‘(‘!
! S.push(expStr[i]);!
else if expstr[i] == operator!
while (stack S is not empty && peek(S) is higher than expstr[i] && ! peek(S) == ‘(‘)!
{!
add S.top to postfixStr!
pop(S)!
}!
else if expstr[i] == ‘)’!
{!
! while ( ! S.empty() && peek(S) != ‘(‘!
! {!
! ! postfixStr = postfixStr + pop(S);!
! }!
! S.pop() // pop the opening parenthesis!
}!
S.push(exp[i]!
}!
while (!S.empty())!
{!
! postfix = postfix = pop(S)!
}!
return postfixSTr! 150
}
Postfix Evaluation
// psudocode Function to evaluate a postfix expression!
evalpostfix(expstr)!
{!
Create a stack S!
for i = 0 to strlen(expstr)!
{!
if (expstr[i] == isOperand())!
{!
push(expstr[i], S);!
else if (expstr[i] is operator)!
{!
oper 1 = pop(S)!
oper 2 = pop(S)!
result = execute(expstr[i], oper 1, Oper 1);!
push (result)!
}!
return (peek(S));!
}!

151
Tower of Hanoi
❖ To solve the problem for ToH of 3 disks,!
❖ Use 3 stacks, S, D, T for source,
destination, temp!
❖ pop(S), push(D)!
❖ pop(S), push(T)!
❖ pop(D), push(T)!
❖ pop(S), push(D)!
❖ pop(T), push(S)!
❖ pop(T), push(D)!
❖ pop(S), push(D)!
❖ One can write a recursive solution using
stacks to solve for a Tower of n discs,
which is solved in 2n -1 moves.

152
Tower of Hanoi - Recursion
// C recursive function to solve tower of hanoi puzzle, courtesy c-programming.com!

#include <stdio.h>!

!
void towerOfHanoi(int n, char fromrod, char torod, char auxrod)!

{!

if (n == 1)!

{!

printf("\n Move disk 1 from rod %c to rod %c", fromrod, torod); // substitute with pop and push!

return;!

}!

towerOfHanoi(n-1, fromrod, auxrod, torod);!

printf("\n Move disk %d from rod %c to rod %c", n, fromrod, torod);!

towerOfHanoi(n-1, auxrod, torod, fromrod);!

}!

!
int main()!

{!

int n = 4; // Number of disks!

towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods!

return 0;!

}
153 Source: thecrazyprogrammer.com
Queues
❖ Like Stacks, Queues are linear data structures with a specific order of insertion and removal!
❖ Last-in-first-out or First-in-last-out theme!
❖ Can be accessed only from the top or first element!
❖ Can be implemented using arrays or linked lists!
❖ Operations include:!
❖ Enqueue- Add an element to the queue from the top of the queue. If the queue is full its an overflow
condition!
❖ Dequeue-Delete an element from the queue in the same order it was entered. IF the queue is empty its
an underflow condition.!
❖ Front - Get the element at the top or front of the queue!
❖ Back - Get the element at the back of the queue!
❖ isEmpty(), isFull() are additional functions !
❖ Queue applications include !
❖ Most scheduling applications in the OS or other customer centric and resource centric applications. !
❖ Asynchronous operations where there is a possibility of a delay

154
Queues
❖ Using Arrays!
struct Queue {
int size;
! int front;
int back;
Queue.back = 445 445 123 89 324 int *arr;
! };
!
Push
❖ Enqueue !

!
445 123 89 324 Queue.front = 324

❖ Dequeue

445 123 89 324


Queues Using Linked Lists
❖ Enqueue from the back of the queue!

!
Prev Prev Prev
445 123 89 324
Next Next Next
!
Back Front

❖ Dequeue from the front of the queue

Prev Prev Prev


445 123 89 324
Next Next Next
Back Front

156
// A utility function to create a new linked list node.!
// A C program to demonstrate linked list
qNode_t * newNode(int val) {!
implementation of queue!
#include <stdio.h>! qNode_t *temp = (qNode_t*) malloc(sizeof(qNode_t));!
#include <stdlib.h>!
temp->data = val;!
!
temp->next = NULL;!
// A linked list (LL) node to store a queue
entry! return temp; !

}!
typedef struct qNode {!
!
int data;!
// A utility function to create an empty queue!
struct qNode *next;!
queue_t *createQueue()!
} qNode_t;! {!

! queue_t * q = (queue_t*)malloc(sizeof(queue_t));!

typedef struct queue {! q->front = q->rear = NULL;!

return q;!
qNode_t *front, *rear;!
}
} queue_t;
157
// The function to add a key k to q!
!
void enQueue(queue_t *q, int k)!
!
{!
// Function to remove a key from given queue q!
// Create a new LL node! qNode_t *deQueue(queue_t *q)!

qNode_t *temp = newNode(k);! {!

! // If queue is empty, return NULL.!

// If queue is empty, then new node is front and rear if (q->front == NULL)!
both! return NULL;!

if (q->rear == NULL)! // Store previous front and move front one node ahead!

{! qNode_t *temp = q->front;!

q->front = q->front->next;!
q->front = q->rear = temp;!
!
return;!
// If front becomes NULL, then change rear also as NULL!
}!
if (q->front == NULL)!
! q->rear = NULL;!
// Add the new node at the end of queue and change return temp;!
rear!
}!
q->rear->next = temp;!

q->rear = temp;!

} 158
// Driver Program to test the Queue!

int main()!

{!

queue_t *q = createQueue();!

enQueue(q, 10);!

enQueue(q, 20);!

deQueue(q);!

deQueue(q);!

enQueue(q, 30);!

enQueue(q, 40);!

enQueue(q, 50);!

qNode_t *p = deQueue(q);!

if (p != NULL)!

printf("Dequeued item is %d", p->data);!

return 0;!

159
Binary Trees
❖ Trees are hierarchical data structures!
❖ Each node is connected to two other nodes via pointers. These nodes are the child nodes
and the node containing the pointers is the parent node. !
❖ A node that has no children is called the leaf node.!
❖ The top-most node is called the root node!
!
❖ Binary Tree: A tree which has a maximum of two children!
❖ For an empty tree, the root is NULL!
❖ Tree applications include!
❖ Storing heirarchical data like the File System on a Computer!
❖ Make information easier to search!
❖ Manipulate sorted lists of data!
❖ As a workflow for compositing digital images for visual effects.!
❖ Router algorithms!
❖ Form of a multi-stage decision-making
160
Binary Trees: Linked List Representation
struct treenode {
int data;
Node struct treenode *left;
struct treenode *right;
};
ROOT 0
Left child Right child

10 20

30 40 50 60
Leaf node
Leaf node

90 100
70
80 Leaf nodes

110 120
130 140
Leaf nodes
161 Leaf nodes
Algorithms: Sorting
❖ Sorting : Arrange items of a list in a pre-determined order!
❖ Bubble Sort: !
❖ Selection Sort!
❖ Insertion Sort!
❖ Merge Sort!
❖ Quick Sort!
❖ Heap Sort!
❖ Shell Sort!
❖ Many other sorting algorithms
162
Bubble Sort
❖ Swap adjacent items in a list to place in order, else ❖ Third Pass:!
move to the next item!
❖ Example: Sort the list 4 3 9 2 6!
❖ 3 2 4 6 9 –> 2 3 4 6 9, swap 3 and 2!
❖ First Pass:! ❖ 2 3 4 6 9 –> 2 3 4 6 9!
❖ 4 3 9 2 6 –> 3 4 9 2 6, compares 4 and 3 and swaps the ❖ 2 3 4 6 9 –> 2 3 4 6 9!
numbers.!
❖ 2 3 4 6 9 –> 2 3 4 6 9!
❖ 3 4 9 2 6 –> 3 4 9 2 6, no swap!
❖ 3 4 9 2 6 –> 3 4 2 9 6, swaps 9 and 2!
❖ Fourth Pass:!
❖ 3 4 2 9 6 –> 3 4 2 6 9, swaps 9 and 6! ❖ It finds no swaps, and ends the sort. !
❖ Second Pass:! !
❖ 3 4 2 6 9 –> 3 4 2 6 9 !
❖ Now, the array is already sorted, but our
❖ 3 4 2 6 9 –> 3 2 4 6 9, swap since 4 > 2! algorithm does not know if it is completed.
❖ 3 2 4 6 9 –> 3 2 4 6 9! The algorithm needs one whole pass
❖ 3 2 4 6 9 –> 3 2 4 6 9 without any swap to know it is sorted.

163
Selection Sort
❖ Select the minimum in the list or array and move to the
front. Do the same for the remainder of the array or list until
the last item is reached. For example!
❖ (4 3 9 2 6) –> 2 (4 3 9 6)!
❖ 2 (4 3 9 6) –> 2 3 (4 9 6)!
❖ 2 3 (4 9 6) –> 2 3 4 (9 6)!
❖ 2 3 4 (9 6) => 2 3 4 6 (9)!
❖ 2 3 4 6 (9) => 2 3 4 6 9

164
Insertion Sort
❖ Select the minimum in the list or array and move to the front. Do the same for the remainder of the array or list until the
last item is reached. For example!
// pseudocode for insertion sort!
❖ 4 3 9 2 6 1 8 0 7!
❖ Given an array of size i!
❖ 3 4 9 2 6 1 8 0 7!
❖ 3 4 9 2 6 1 8 0 7!
❖ assume arr[0] is in the right place!

❖ 2 3 4 9 6 1 8 0 7! ❖ for i = 1 all the way to the end of the array!


❖ 2 3 4 9 6 1 8 0 7! ❖ {!
❖ 2 3 4 6 9 1 8 0 7! ❖ x = arr[i]!
❖ 2 3 4 6 9 1 8 0 7! ❖ while x < arr[i-1]!
❖ 1 2 3 4 6 9 8 0 7! ❖ arr[i] = arr[i-1] // move the array down until !
❖ 1 2 3 4 6 9 8 0 7!
❖ // the right place to insert is found!
❖ 1 2 3 4 6 8 9 0 7!
❖ i—;!
❖ 1 2 3 4 6 8 9 0 7!
❖ }!
❖ 0 1 2 3 4 6 8 9 7!
❖ 0 1 2 3 4 6 8 9 7!
❖ arr[i] = x;!
❖ 012346879 ❖ }

165
Merge Sort

166
Heap
❖ A Heap is a sorted binary tree that has the following rules:!
❖ It is a complete tree, i.e. all nodes at a level are filled before filling the next level!
❖ Each level is filled from left to right without a gap!
❖ A Heap is sorted in ascending or descending order which gives rise to two types
of heaps!
❖ MIN Heap, where the root node holds the least key value!
❖ MAX Heap. where the root node holds the highest key value!
❖ Typical operations include:!
❖ Adding a node to the Heap!
❖ Deleting a node to the Heap!
❖ Translating a Heap to an array!
❖ Heaps are also called priority queues
167
Heap Operations
❖ Create the root node. Add the first element of the array to the root. Initialize left child
and right child pointers to NULL.!
❖ Create a MIN Heap for sorting in ascending order and a MAX Heap for sorting in
descending order.!
❖ Add an item to the Heap!
❖ Adding at the root is common practise!
❖ For the remainder of the array, add to the left most left node until the end of the
array !
❖ Heapify, i.e make sure that the Heap is in the right order!
❖ Deleting an item from the array!
❖ Delete the root!
❖ Replace with the right most leaf node!
❖ Heapify, i.e make sure that the Heap is in the right order

168
Search Algorithms
❖ Linear Search - examining each item one by one until the desired item is
found!
❖ Binary Search, search for a given element p in a sorted array. Start from the
middle of the array with value x, if p = x, search is complete, else if p < x,
recursively search for p in first half of array, else if p > x, search for p in 2nd
half of array. !
❖ Binary Search Trees (BST)- A binary tree which for a given value p, has all
values < p to the left of a node and all values > p to the right of the node.
Start with the root node. Each sub-tree is in turn a BST.!
❖ Two basic search algorithms for Trees!
❖ Depth-first-search!
❖ Breadth-first-search
169
Linear Search

// Linearly search x in arr[]. If x is present //


then return its location, otherwise return -1
int search(int arr[], int n, int x)
{
int i;
for (i=0; i<n; i++)
if (arr[i] == x)
return i;
return -1;
}

170
#include <stdio.h>!
Binary Search
!
// A recursive binary search function. It returns location of
x in!
// given array arr[l..r] is present, otherwise -1!
int binarySearch(int arr[], int p, int r, int x)!
{! int main(void)!
if (r >= l)!
{!
{!
int mid = p + (r - l)/2;! int arr[] = {2, 3, 4, 10, 40};!
! int n = sizeof(arr)/ sizeof(arr[0]);!
// If the element is present at the middle itself! int x = 10;!
if (arr[mid] == x) return mid;!
int result = binarySearch(arr, 0, n-1, x);!
!
// If element is smaller than mid, then it can only be (result == -1)? printf("Element is not present
present! in array")!
// in left subarray! : printf("Element is present at index
if (arr[mid] > x) return binarySearch(arr, l, mid-1, x);!
%d", result);!
!
// Else the element can only be present in right return 0;!
subarray! }
return binarySearch(arr, mid+1, r, x);!
}!
!
// We reach here when element is not present in array!
return -1;!
} 171
Binary Search Tree (BST)
❖ Binary Search Tree, is a node-based binary tree data structure which has the following
properties:!
❖ ! The left subtree of a node contains only nodes with keys less than the node’s key.!
❖ ! The right subtree of a node contains only nodes with keys greater than the node’s key.!
❖ ! The left and right subtree each must also be a binary search tree.!
❖ ! There must be no duplicate nodes.!
❖ Searching a BST for a key (or given value)!
❖ First compare key with root, if the key is present at root, return root. !
❖ If key is greater than root’s key, recur for right subtree of root node. !
❖ Otherwise recur for left subtree.!
❖ If key is not found, return error code

172
Depth-First-Search (DFS)
❖ Start with the root node!
59
❖ Examine all nodes up to the
leaf node for each node
starting with the leftmost
40 65 child.!
❖ Continue going down each
branch of the tree!

29 45 55 70
❖ Iterate or recurse until node is
found!
❖ In this example, the order of
node access is
16 35 59-40-29-16-45-35-65-55-70
173
Breadth-First-Search
❖ Start with the root node!
❖ Examine all nodes at the
immediate child level!
❖ Starting from the left
child continue with next
levels. !
❖ Iterate or recurse until
node is found!
❖ Order of nodes examined
in this case is abcdefgh
174
Matrices
❖ Rectangular array of numbers, symbols or arithmetic
expressions arranged in rows and columns!
❖ Order of a Matrix is the Rows x Columns.!
❖ Two matrices can be added and subtracted if they have the
same number of rows and columns!
❖ Two matrices can be multiplied if the number of columns in the
first is equal to the number of rows in the second!
❖ A square matrix is one which has equal number of rows and
columns!
❖ A rectangular matrix is one whose rows are not equal to the
175
Matrices
❖ Size of a Matrix - number of rows * number of columns!
❖ Basic operations include:!
Matrix A Matrix B
❖ Addition, Subtraction!
3 5 8 2 0 1000
❖ Scalar Multiplication! 2 0 9 1 0 0
1 2 4 100 -2 4
❖ Matrix Multiplication! Ai,j = A[i] [j], is the element in row i, column j
!
❖ Transposition! A[3][2] = 2, B[1][1] = 2

❖ Matrices are represented by two-dimensional arrays!


❖ Applications in !
❖ Graph theory, Probability theory and statistics, transformations in
physics, Electronics, many others…
176
Matrix Addition / Subraction

177
Matrix Multiplication

178
Matrix Inverse
❖ Only square matrices can
have an inverse!
❖ Division of two matrices is
equivalent to multiplying
one matrix by the inverse of
the other.!
❖ If the “divisor” matrix is not
a square matrix, a solution is
not possible.

179
Matrix Transpose
❖ Transpose of a matrix is a new matrix
with rows and columns are
Transpose of a square matrix
interchanged, meaning whose rows are
the columns of the original and vice
versa. !
❖ Elements at row, column [r][c] in the
original matrix is placed at row,column
[c][r] in the transposed matrix.!
Transpose of a rectangular matrix
❖ The transpose of the transpose results
in the original matrix.! AT

❖ Usually square matrices are transposed


but we can transpose rectangular (AT)T
matrices as well.

180
Big O (Algorithm execution times)
❖ Notation used to express the efficiency of an algorithm. !
❖ Expressed in terms of the increase in running time as the
problem size or input becomes arbitrarily large.!
❖ The growth rate is also called the Order of the algorithm,
hence Big O.!
❖ Running Time is expressed as a function in terms of the
CPU time used or the number of steps (time complexity)
and amount of storage - primarily memory- (space
complexity).!
❖ Used in both Computer Science and Mathematics
181
Big O (Algorithm execution times)
❖ Measures how efficiently an algorithm uses computing resources:!
❖ CPU (time) usage!
❖ memory usage!
❖ disk usage!
❖ network usage!
❖ Two aspects of an algorithm!
❖ Performance: how much time/memory/disk/... is actually used when a
program is run. This depends on the machine, compiler, etc. as well as the
code.!
❖ Complexity: how do the resource requirements of a program or algorithm
scale. Complexity affects performance but not the other way around.

182
Big O Definition
❖ “Big O notation is a mathematical notation that describes the limiting behavior of a function
when the argument tends towards a particular value or infinity.”!
❖ Source: !
❖ A function T(N) is O(F(N)) if for some constant c and for values of N greater than some value n0:!
❖ T(N) <= c * F(N)!
❖ T(N) is the exact complexity of an algorithm expressed as a function of the problem size N!
❖ F(N) is an upper-bound on that complexity (i.e., the actual time/space or whatever for a
problem of size N will be no worse than F(N)). !
❖ The smaller the F(N), the more efficient the algorithm!
❖ For example:!
❖ T(N) = 3 * N2 + 5. !
❖ T(N) approximates to O(N2) for large values of N

183
Big O (Algorithm execution times)
❖ For a problem of size N,!
❖ a constant-time algorithm is "order 1": O(1)!
❖ example, basic arithematic operations!
❖ a linear-time algorithm is "order N": O(N)!
❖ single for loop with basic operations!
❖ a quadratic-time algorithm is "order N squared": O(N2)!
❖ average case for bubble sort, selection sort and insertion sort and
worst case for Quick Sort!
❖ a logarthimic time algorithm is “order N log N” : O(log N)!
❖ Binary Search Tree
184
References on the Internet
❖ Download a copyright free pdf of
C Programming Language by Kernigan & Ritchie at http://
www.iups.org/media/meeting_minutes/C.pdf
❖ Few other online References
http://www.tutorialspoint.com/
http://geeksforgeeks.org
http://thecrazyprogrammer.com
http://stackoverflow.com

185

Das könnte Ihnen auch gefallen