SlideShare a Scribd company logo
1 of 33
C
Contents 
 Binary Search 
 Functions 
 Pointers
Binary Search 
Binary search is a searching algorithm that works 
efficiently with a sorted list. The algorithm finds the 
position of a particular element in the array. This 
algorithm doesn’t work with the unsorted list. 
For Example, The analogy of a telephone directory. 
When we search for a particular name in the 
directory, we first open the dictionary from the 
middle and then decide whether to look in the first 
part or the second part of the directory. Again, we 
open some page in the middle and the whole process is 
repeated until we have the name.
Advantages 
 The binary search is fast as compared to linear 
search. 
 Time complexity is high in both average and worst 
case. 
 Most Suitable for sorted arrays.
DISADVANTAGES 
 The main disadvantage of binary search is that it 
only works with an array of sorted array.
Functions 
Function is a set of self contained block of statements 
that performs a specific task of some kind. A function 
is small, complete & independent program. The 
specified task is repeated each time the program 
calls the function. It breaks the large computing tasks 
into smaller ones. 
In C there are two types of functions: 
1. Library Functions 
2. User defined functions
Library Functions 
Library functions are predefined 
built-in functions. These functions 
are permanently stored in the 
library of C compiler. We can’t 
change the meaning of these 
functions. Such functions are 
stored in header file. A header file 
has an extension “.h”
Header Files Functions Defined 
stdio.h Printf(), scanf(), getchar(), 
putchar(), gets(), puts(), fopen(), 
fclose() 
conio.h Clrscr(), getch() 
Ctype.h Toupper(), tolower() 
Math.h Pow(), sqrt(), cos(), log() 
Stdlib.h exit() 
String.h Strlen(), strcpy(), strupr()
USER DEFINED FUNCTIONS 
Defined by user at the time of writing 
the program. 
There are three aspect of working with 
user-defined functions: 
1.Function Declaration, also known as 
function prototype 
2.Function Definition 
3.Function use, also known as function 
call or function invocation
Function Declaration : we declare the prototype and number 
of argument required for function. 
Syntax : 
return_type function_name (argument1,argument2.....) 
eg : int div(int , int) { } 
1 - int is a return type of function. 
2 - div is a name for function. 
3 - two int are arguments required to call the function.
Function Definition : Function Definition, also known as 
function implementation, means composing a function. 
Every Function definition consists of two Parts: 
 Header of the function, 
 Body of the function. 
return_type function_name(parameter_list) 
{ 
// Function body 
} 
Example- int greatest(int a, int b,int c)/*formal arguments*/ 
{ 
//Body of the function 
}
How to access & execute a function 
User defined functions are accessed in same way 
as of the library functions i.e. we can access the 
function by referring its name, including actual 
arguments. 
Example- int greatest(10,20,30)/* know as dummy 
variables*/
return Statement : The return statement is used 
in a function to transfer the control from the 
called function back to the calling function at the 
point of reference. We can also return the value 
through return statement to the calling function. 
Example : return; 
or 
return(exp);
Passing Arguments to a function 
We pass data to a function via argument list . These 
are enclosed with brackets or parenthesis after 
function name. 
There are two ways to pass arguments to a 
function: 
1. Call by value 
2. Call by reference
 Call by Value: 
In this method the values of actual arguments are 
passed to the function. When the control is 
transferred to the called function the formal 
arguments of function are replaced by the actual 
arguments & then the body of function is 
executed. 
 Call by reference: 
In this the address of the actual arguments are 
passed to the function. Here the dummy 
arguments are declared as pointer to types that 
match the data types of actual arguments.
Function call 
Depending upon their inputs (i.e. parameters) and 
outputs, functions are classified as: 
 Function with no argument (I)& no return 
value(O). 
 Function with argument and no return value. 
 Function with arguments and a return value. 
 Function with no arguments and a return value.
Recursion 
Recursion is a function who called function repeatedly 
by itself. A recursive function may have following two 
properties: 
 A function must call itself 
 There should be a stopping condition so that a 
function should not call itself an infinite number of 
times.
Array & Functions 
Array can be passed to a function in C. An 
array name can be used as an argument 
for the declaration. No subscripts or 
square brackets are required to invoke a 
function using array.
Pointers 
Just another kind of “placeholder” to hold “address” of 
memory location. 
 - Address is also a number 
 - Itself resides on some memory location 
Memory Address Value 
0x8004 …. 
0x8008 129 
0x800C …. 
0x8010 0x8008 
0x8014 ... 
variable A 
address of A
Declaration of Pointer Variables 
 Declare variables a, b 
int a, b; 
 Declare a pointer 
int* pa; 
 Set value of a 
a = 10; 
 Point pa to address of a 
pa = &a; 
 Set value of a using pa 
*pa = 12; pa = &b;
Pointer Operators 
 “address-of” operator: & 
Gets address of a variable 
De-referencing operator: * 
- Accesses the memory location 
this pointer holds address of
Pointer Arithmetic/Expressions 
 Arithmetic operators work as usual on ordinary 
data types. 
int a = 1; a++; // a == 2 
 It gets a bit complicated when arithmetic operators 
are used on pointers 
 int* p = 0x8004; p++; 
 What does p hold now? 0x8005??? 
 Compiler knows that p is a pointer to integer type 
data, so an increment to it should point to next 
integer in memory. Hence 0x8008.
Pointers and Functions 
 A function can be passed arguments usingbasic data 
types 
- int prod(int a, int b) { return a*b; } 
 How to return multiple values from function? 
- void prod_and_sum(int a, int b, int*p, int* s) 
{ *p = a*b; *s = a+b; }
Pointers and Arrays 
 Since arrays are a contiguous set of variables 
 in memory, we can access them with pointers 
 int arr[5]; 
 int *p = &arr[0]; 
 *(p+0) = 1; // arr[0] 
 *(p+1) = 2; // arr[1] 
 *(p+2) = 4; // arr[2] 
 *(p+3) = 8; // arr[3] 
 ...
Dynamic Memory Allocation 
The process of allocating memory at run time is 
known as dynamic memory allocation. Although 
c does not inherently have this facility there 
are four library routines which allow this 
functions, which can be used to allocate and 
free memory during the program execution.
Dynamic Memory Allocation Functions
sizeof() 
sizeof() is a unary operator. This operator gives the size 
of its argument in terms of bytes. The argument can 
be variable, array or any data type(int, float, char 
etc.). This operator also gives the size of any 
structure. 
Example-sizeof( 
int); 
This gives the bytes occupied by the int data type , that 
is 2.
malloc() 
A block of memory may be allocated using the function 
malloc. The malloc function reserves a block of 
memory of specified size and returns a pointer of 
type void. This means that we can assign it to any type 
of pointer. It takes the following form: 
ptr=(cast-type*)malloc(byte-size); 
ptr is a pointer of type cast-type the malloc returns a 
pointer (of cast type) to an area of memory with size 
byte-size
malloc() Example 
Example: 
x=(int*)malloc(100*sizeof(int)); 
On successful execution of this statement a 
memory equivalent to 100 times the area of 
int bytes is reserved and the address of the 
first byte of memory allocated is assigned to 
the pointer x of type int.
Calloc 
 Calloc is another memory allocation function 
that is normally used to request multiple 
blocks of storage each of the same size and 
then sets all bytes to zero. The general form 
of calloc is: 
ptr=(cast-type*) calloc(n,elem-size); 
ptr=(int*)calloc(5,2)
Calloc(Contd.) 
calloc() allocates contiguous space for n blocks 
each size of elements size bytes. All bytes are 
initialized to zero and a pointer to the first 
byte of the allocated region is returned. If 
there is not enough space a null pointer is 
returned.
free() 
Compile time storage of a variable is allocated 
and released by the system in accordance with 
its storage class. With the dynamic runtime 
allocation, it is our responsibility to release 
the space when it is not required. 
free(ptr); 
ptr is a pointer that has been created by using 
malloc or calloc
realloc 
The memory allocated by using calloc or malloc 
might be insufficient or excess sometimes in 
both the situations we can change the memory 
size already allocated with the help of the 
function realloc. This process is called 
reallocation of memory. The general 
statement of reallocation of memory is : 
ptr=realloc(ptr,newsize);

More Related Content

What's hot (20)

C1320prespost
C1320prespostC1320prespost
C1320prespost
 
python Function
python Function python Function
python Function
 
Python revision tour i
Python revision tour iPython revision tour i
Python revision tour i
 
Pointers
PointersPointers
Pointers
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
Computer programming(CP)
Computer programming(CP)Computer programming(CP)
Computer programming(CP)
 
Chp3(pointers ref)
Chp3(pointers ref)Chp3(pointers ref)
Chp3(pointers ref)
 
Python advance
Python advancePython advance
Python advance
 
Pointers
PointersPointers
Pointers
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Complicated declarations in c
Complicated declarations in cComplicated declarations in c
Complicated declarations in c
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1
 
Python The basics
Python   The basicsPython   The basics
Python The basics
 

Similar to Programming in C sesion 2

Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceKrithikaTM
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxvekariyakashyap
 
C language presentation
C language presentationC language presentation
C language presentationbainspreet
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxvanshhans21102005
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
Functions in c language
Functions in c languageFunctions in c language
Functions in c languageTanmay Modi
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in Carshpreetkaur07
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpprajshreemuthiah
 

Similar to Programming in C sesion 2 (20)

Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
 
Functions
FunctionsFunctions
Functions
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
 
C language presentation
C language presentationC language presentation
C language presentation
 
Functions
FunctionsFunctions
Functions
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptx
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Functions in c language
Functions in c languageFunctions in c language
Functions in c language
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Python functions
Python functionsPython functions
Python functions
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in C
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
Functions in c
Functions in cFunctions in c
Functions in c
 

Recently uploaded

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 

Recently uploaded (20)

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 

Programming in C sesion 2

  • 1. C
  • 2. Contents  Binary Search  Functions  Pointers
  • 3. Binary Search Binary search is a searching algorithm that works efficiently with a sorted list. The algorithm finds the position of a particular element in the array. This algorithm doesn’t work with the unsorted list. For Example, The analogy of a telephone directory. When we search for a particular name in the directory, we first open the dictionary from the middle and then decide whether to look in the first part or the second part of the directory. Again, we open some page in the middle and the whole process is repeated until we have the name.
  • 4. Advantages  The binary search is fast as compared to linear search.  Time complexity is high in both average and worst case.  Most Suitable for sorted arrays.
  • 5. DISADVANTAGES  The main disadvantage of binary search is that it only works with an array of sorted array.
  • 6. Functions Function is a set of self contained block of statements that performs a specific task of some kind. A function is small, complete & independent program. The specified task is repeated each time the program calls the function. It breaks the large computing tasks into smaller ones. In C there are two types of functions: 1. Library Functions 2. User defined functions
  • 7. Library Functions Library functions are predefined built-in functions. These functions are permanently stored in the library of C compiler. We can’t change the meaning of these functions. Such functions are stored in header file. A header file has an extension “.h”
  • 8. Header Files Functions Defined stdio.h Printf(), scanf(), getchar(), putchar(), gets(), puts(), fopen(), fclose() conio.h Clrscr(), getch() Ctype.h Toupper(), tolower() Math.h Pow(), sqrt(), cos(), log() Stdlib.h exit() String.h Strlen(), strcpy(), strupr()
  • 9. USER DEFINED FUNCTIONS Defined by user at the time of writing the program. There are three aspect of working with user-defined functions: 1.Function Declaration, also known as function prototype 2.Function Definition 3.Function use, also known as function call or function invocation
  • 10. Function Declaration : we declare the prototype and number of argument required for function. Syntax : return_type function_name (argument1,argument2.....) eg : int div(int , int) { } 1 - int is a return type of function. 2 - div is a name for function. 3 - two int are arguments required to call the function.
  • 11. Function Definition : Function Definition, also known as function implementation, means composing a function. Every Function definition consists of two Parts:  Header of the function,  Body of the function. return_type function_name(parameter_list) { // Function body } Example- int greatest(int a, int b,int c)/*formal arguments*/ { //Body of the function }
  • 12. How to access & execute a function User defined functions are accessed in same way as of the library functions i.e. we can access the function by referring its name, including actual arguments. Example- int greatest(10,20,30)/* know as dummy variables*/
  • 13. return Statement : The return statement is used in a function to transfer the control from the called function back to the calling function at the point of reference. We can also return the value through return statement to the calling function. Example : return; or return(exp);
  • 14. Passing Arguments to a function We pass data to a function via argument list . These are enclosed with brackets or parenthesis after function name. There are two ways to pass arguments to a function: 1. Call by value 2. Call by reference
  • 15.  Call by Value: In this method the values of actual arguments are passed to the function. When the control is transferred to the called function the formal arguments of function are replaced by the actual arguments & then the body of function is executed.  Call by reference: In this the address of the actual arguments are passed to the function. Here the dummy arguments are declared as pointer to types that match the data types of actual arguments.
  • 16. Function call Depending upon their inputs (i.e. parameters) and outputs, functions are classified as:  Function with no argument (I)& no return value(O).  Function with argument and no return value.  Function with arguments and a return value.  Function with no arguments and a return value.
  • 17. Recursion Recursion is a function who called function repeatedly by itself. A recursive function may have following two properties:  A function must call itself  There should be a stopping condition so that a function should not call itself an infinite number of times.
  • 18. Array & Functions Array can be passed to a function in C. An array name can be used as an argument for the declaration. No subscripts or square brackets are required to invoke a function using array.
  • 19. Pointers Just another kind of “placeholder” to hold “address” of memory location.  - Address is also a number  - Itself resides on some memory location Memory Address Value 0x8004 …. 0x8008 129 0x800C …. 0x8010 0x8008 0x8014 ... variable A address of A
  • 20. Declaration of Pointer Variables  Declare variables a, b int a, b;  Declare a pointer int* pa;  Set value of a a = 10;  Point pa to address of a pa = &a;  Set value of a using pa *pa = 12; pa = &b;
  • 21. Pointer Operators  “address-of” operator: & Gets address of a variable De-referencing operator: * - Accesses the memory location this pointer holds address of
  • 22. Pointer Arithmetic/Expressions  Arithmetic operators work as usual on ordinary data types. int a = 1; a++; // a == 2  It gets a bit complicated when arithmetic operators are used on pointers  int* p = 0x8004; p++;  What does p hold now? 0x8005???  Compiler knows that p is a pointer to integer type data, so an increment to it should point to next integer in memory. Hence 0x8008.
  • 23. Pointers and Functions  A function can be passed arguments usingbasic data types - int prod(int a, int b) { return a*b; }  How to return multiple values from function? - void prod_and_sum(int a, int b, int*p, int* s) { *p = a*b; *s = a+b; }
  • 24. Pointers and Arrays  Since arrays are a contiguous set of variables  in memory, we can access them with pointers  int arr[5];  int *p = &arr[0];  *(p+0) = 1; // arr[0]  *(p+1) = 2; // arr[1]  *(p+2) = 4; // arr[2]  *(p+3) = 8; // arr[3]  ...
  • 25. Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. Although c does not inherently have this facility there are four library routines which allow this functions, which can be used to allocate and free memory during the program execution.
  • 27. sizeof() sizeof() is a unary operator. This operator gives the size of its argument in terms of bytes. The argument can be variable, array or any data type(int, float, char etc.). This operator also gives the size of any structure. Example-sizeof( int); This gives the bytes occupied by the int data type , that is 2.
  • 28. malloc() A block of memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form: ptr=(cast-type*)malloc(byte-size); ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size
  • 29. malloc() Example Example: x=(int*)malloc(100*sizeof(int)); On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int.
  • 30. Calloc  Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is: ptr=(cast-type*) calloc(n,elem-size); ptr=(int*)calloc(5,2)
  • 31. Calloc(Contd.) calloc() allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned.
  • 32. free() Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. free(ptr); ptr is a pointer that has been created by using malloc or calloc
  • 33. realloc The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is : ptr=realloc(ptr,newsize);

Editor's Notes

  1. By prerna sharma