SlideShare a Scribd company logo
1 of 56
FUNCTIONS
UNIT-II
DBS INSTITUTE OF TECHNOLOGY , Kavali, A.P, INDIA
• A function is a block of statements that performs a specific task. Let’s say
you are writing a C program and you need to perform a same task in that
program more than once. In such case you have two options:
• a) Use the same set of statements every time you want to perform the
task
b) Create a function to perform that task, and just call it every time you
need to perform that task.
• Using option (b) is a good practice and a good programmer always uses
functions while writing code in C.
• In c, we can divide a large program into the basic building blocks known as
function. The function contains the set of programming statements
enclosed by {}. A function can be called multiple times to provide
reusability and modularity to the C program. In other words, we can say
that the collection of functions creates a program. The function is also
known as procedureor subroutinein other programming languages.
Advantage of functions in C
There are the following advantages of C functions.
• By using functions, we can avoid rewriting same
logic/code again and again in a program.
• We can call C functions any number of times in a
program and from any place in a program.
• We can track a large C program easily when it is
divided into multiple functions.
• Reusability is the main achievement of C functions.
• However, Function calling is always a overhead in a C
program.
Types of functions
1) Predefined standard library functions
• Standard library functions are also known as built-in
functions. Functions such as puts(), gets(), printf(), scanf() etc
are standard library functions. These functions are already
defined in header files (files with .h extensions are called
header files such as stdio.h), so we just call them whenever
there is a need to use them.
• For example, printf() function is defined in <stdio.h> header
file so in order to use the printf() function, we need to include
the <stdio.h> header file in our program using #include
<stdio.h>.
2) User Defined functions
• The functions that we create in a program are known
as user defined functions or in other words you can say
that a function created by user is known as user
defined function.
• C programming functions are divided into three
activities such as,
• Function declaration
• Function definition
• Function call
Syntax of a function
return_type function_name (argument list)
{
Set of statements – Block of code
}
return_type: Return type can be of any data type such as int, double, char,
void, short etc.
function_name: It can be anything, however it is advised to have a
meaningful name for the functions so that it would be easy to understand the
purpose of function just by seeing it’s name.
argument list: Argument list contains variables names along with their data
types. These arguments are kind of inputs for the function. For example – A
function which is used to add two integer variables, will be having two integer
argument.
Block of code: Set of C statements, which will be executed whenever a call
will be made to the function.
return_type addition(argument list)
return_type addition(int num1, int num2)
int addition(int num1, int num2);
• Function Declaration
• The function declaration tells the compiler about function name, the data
type of the return value and parameters. The function declaration is also
called a function prototype. The function declaration is performed before
the main function
Function declaration syntax -
returnType functionName(parametersList);
• In the above syntax, returnType specifies the data type of the value which
is sent as a return value from the function definition. The functionName is
a user-defined name used to identify the function uniquely in the
program. The parametersList is the data values that are sent to the
function definition.
Function Declaration
#include <stdio.h>
/*Function declaration*/
int add(int a,b);
/*End of Function declaration*/
int main() {
Function Definition
• The function definition provides the actual code of that function. The function
definition is also known as the body of the function. The actual task of the function is
implemented in the function definition. That means the actual instructions to be
performed by a function are written in function definition. The actual instructions of a
function are written inside the braces "{ }".
Function definition syntax -
returnType functionName(parametersList)
{
Actual code...
}
Function Definition
int add(int a,int b) //function body
{
int c;
c=a+b;
return c;
}
Function Call
• The function call tells the compiler when to execute the function
definition. When a function call is executed, the execution control jumps
to the function definition where the actual code gets executed and returns
to the same functions call once the execution completes. The function call
is performed inside the main function or any other function or inside the
function itself.
• Function call syntax -
functionName(parameters);
Function call
result = add(4,5);
#include <stdio.h>
int add(int a, int b); //function declaration
int main()
{
int a=10,b=20;
int c=add(10,20); //function call
printf("Addition:%dn",c);
getch();
}
int add(int a,int b) //function body
{
int c;
c=a+b;
return c;
}
Addition:30
TYPES OF USER DEFINED FUNCTIONS
• A function may or may not accept any argument. It
may or may not return any value. Based on these
facts, There are four different aspects of function
calls.
• function without arguments and without return
value
• function without arguments and with return value
• function with arguments and without return value
• function with arguments and with return value
function without arguments and without return value
#include<stdio.h>
void sum();
void main()
{
printf("nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
OUTPUT:
Going to calculate the sum of two numbers:
Enter two numbers 10
24
The sum is 34
Function without argument and with return value
#include<stdio.h>
int sum();
void main()
{
int result;
printf("nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
OUTPUT:
Going to calculate the sum of two numbers:
Enter two numbers 10
24
The sum is 34
Function with argument and without return value
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("nGoing to calculate the sum of
two numbers:");
printf("nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("nThe sum is %d",a+b);
}
OUTPUT:
Going to calculate the sum of two numbers:
Enter two numbers 10
24
The sum is 34
Function with argument and with return value
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("nGoing to calculate the sum of two numbers:");
printf("nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Going to calculate the sum of two numbers:
Enter two numbers:10
20
The sum is : 30
In the concept of functions, the function call is known as "Calling Function" and
the function definition is known as "Called Function".
Parameter Passing in C
When a function gets executed in the program, the execution control is
transferred from calling-function to called function and executes function
definition, and finally comes back to the calling function. When the execution
control is transferred from calling-function to called-function it may carry one
or number of data values. These data values are called as parameters.
Parameters are the data values that are passed from calling function to called
function.
In C, there are two types of parameters and they are as follows...
Actual Parameters
Formal Parameters
• The actual parameters are the parameters that are
speficified in calling function. The formal parameters are
the parameters that are declared at called function.
When a function gets executed, the copy of actual
parameter values are copied into formal parameters.
• In C Programming Language, there are two methods to
pass parameters from calling function to called function
and they are as follows...
• Call by Value
• Call by Reference
#include<stdio.h>
#include<conio.h>
void swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void main()
{
int a=100, b=200;
clrscr();
swap(a, b); // passing value to function
printf("nValue of a: %d",a);
printf("nValue of b: %d",b);
getch();
}
Value of a: 200
Value of b: 100
Call by Value
#include<stdio.h>
#include<conio.h>
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int a=100, b=200;
clrscr();
swap(&a, &b); // passing value to function
printf("nValue of a: %d",a);
printf("nValue of b: %d",b);
getch();
}
Value of a: 200
Value of b: 100
Call by reference
C Recursion
A function that calls itself is known as a recursive function. And, this technique
is known as recursion.
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
Storage allocation
• Dynamic Memory Allocation in C Programming Language - C
language provides features to manual management of memory, by
using this feature we can manage memory at run time, whenever
we require memory allocation or reallocation at run time by
using Dynamic Memory Allocation functions we can create amount
of required memory.
• Dynamic memory allocation in c language is possible by 4 functions
of stdlib.h header file.
• malloc()
• calloc()
• realloc()
• free()
static memory allocation dynamic memory allocation
memory is allocated at compile
time.
memory is allocated at run time.
memory can't be increased while
executing program.
memory can be increased while
executing program.
used in array. used in linked list.
malloc() method
“malloc” or “memory allocation” method in C is used to dynamically allocate a single
large block of memory with the specified size. It returns a pointer of type void which
can be cast into a pointer of any form. It initializes each block with default garbage
value.
Syntax:
ptr = (cast-type*) malloc(byte-size)
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of
memory. And, the pointer ptr holds the address of the first byte in the
allocated memory
If space is insufficient,
allocation fails and
returns a NULL
pointer
calloc() method
calloc” or “contiguous allocation” method in C is used to dynamically allocate the
specified number of blocks of memory of the specified type. It initializes each block
with a default value ‘0’.
Syntax:
ptr = (cast-type*)calloc(n, element-size);
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the
size of the float.
free() method
“free” method in C is used to dynamically de-allocate the memory. The memory
allocated using functions malloc() and calloc() is not de-allocated on their own.
Hence the free() method is used, whenever the dynamic memory allocation takes
place. It helps to reduce wastage of memory by freeing it.
Syntax:
free(ptr);
realloc() method
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'
Storage Classes in C
• storage classes in C are used to determine the
lifetime, visibility, memory location, and initial value
of a variable. There are four types of storage classes
in C
• Automatic
• External
• Static
• Register
Automatic
Automatic variables are allocated memory automatically at runtime.
The visibility of the automatic variables is limited to the block in which they
are defined.
The automatic variables are initialized to garbage by default.
The memory assigned to automatic variables gets freed upon exiting from
the block.
The keyword used for defining automatic variables is auto.
Every local variable is automatic in C by default.
Static
Default initial value of the static integral variable is 0 otherwise null.
The visibility of the static global variable is limited to the file in which it has
declared.
The keyword used to define static variable is static.
Register
The variables defined as the register is allocated the memory into the CPU
registers depending upon the size of the memory remaining in the CPU.
We can not dereference the register variables, i.e., we can not use
&operator for the register variable.
The access time of the register variables is faster than the automatic
variables.
The initial default value of the register local variables is 0.
External
The external storage class is used to tell the compiler that the variable
defined as extern is declared with an external linkage elsewhere in the
program.
We can only initialize the extern variable globally, i.e., we can not initialize
the external variable within any block or method.
Storage
Classes
Storage
Place
Default
Value
Scope Lifetime
auto RAM Garbage
Value
Local Within function
extern RAM Zero Global Till the end of the main
program Maybe declared
anywhere in the program
static RAM Zero Local Till the end of the main
program, Retains value
between multiple
functions call
register Register Garbage
Value
Local Within the function
Strings
• The string can be defined as the one-dimensional array of
characters terminated by a null ('0').
• The character array or the string is used to manipulate text
such as word or sentences.
• Each character in the array occupies one byte of memory, and
the last character must always be 0.
• The termination character ('0') is important in a string since it
is the only way to identify where the string ends.
• When we define a string as char s[10], the character s[10] is
implicitly initialized with the null in the memory.
There are two ways to declare a string in c language.
By char array
By string literal
String I/O in C programming
String Example
#include<stdio.h>
#include <string.h>
int main(){
char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '0'};
char ch2[11]="javatpoint";
printf("Char Array Value is: %sn", ch);
printf("String Literal Value is: %sn", ch2);
return 0;
}
Char Array Value is: javatpoint
String Literal Value is: javatpoint
String Handling Functions
C programming language provides a set of pre-defined
functions called string handling functions to work with string
values.
The string handling functions are defined in a header file
called string.h.
 Whenever we want to use any string handling function we
must include the header file called string.h.
No. Function Description
1) strlen(string_name) returns the length of string
name.
2) strcpy(destination, source) copies the contents of source
string to destination string.
3) strcat(first_string, second_string) concats or joins first string
with second string. The result
of the string is stored in first
string.
4) strcmp(first_string, second_string) compares the first string with
second string. If both strings
are same, it returns 0.
5) strrev(string) returns reverse string.
6) strlwr(string) returns string characters in
lowercase.
7) strupr(string) returns string characters in
uppercase.
strlen() function
The strlen() function returns the length of the given string. It doesn't count
null character '0'.
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
Output:
Length of string is: 10
strcpy()
The strcpy(destination, source) function copies the source string in destination.
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}
Output:
Value of second string is: javatpoint
strrev()
The strrev(string) function returns reverse of the given string
strlwr()
The strlwr(string) function returns string characters in lowercase
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("nLower String is: %s",strlwr(str));
return 0;
}
Output:
Enter string: JAVATpoint
String is: JAVATpoint
Lower String is: javatpoint
strupr()
The strupr(string) function returns string characters in uppercase.
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("nUpper String is: %s",strupr(str));
return 0;
}
Output:
Enter string: javatpoint
String is: javatpoint
Upper String is: JAVATPOINT
structures
• In C, there are cases where we need to store multiple
attributes of an entity.
• It is not necessary that an entity has all the
information of one type only.
• It can have different attributes of different data
types.
• For example, an entity Student may have its name
(string), roll number (int), marks (float).
Structure in c is a user-defined data type that enables us to store the
collection of different data types.
Each element of a structure is called a member.
The ,struct keyword is used to define the structure. Let's see the syntax to
define the structure in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Let's see the example to define a structure for an entity employee in c.
struct employee
{ int id;
char name[20];
float salary;
};
Declaring structure variable
We can declare a variable for the structure so that we can access the member
of the structure easily. There are two ways to declare structure variable:
•By struct keyword within main() function
•By declaring a variable at the time of defining the structure.
Accessing members of the structure
There are two ways to access structure members:
By . (member or dot operator)
By -> (structure pointer operator)
Unions
Like structure, Union in c language is a user-defined data type that is
used to store the different type of elements.
At once, only one member of the union can occupy the memory. In
other words, we can say that the size of the union in any instance is equal
to the size of its largest element.
Advantage of union over structure
It occupies less memory because it occupies the size of the largest
member only.
Command Line Arguments
The arguments passed from command line are called command line
arguments. These arguments are handled by main() function.
To support command line argument, you need to change the structure of
main() function as given below.
int main(int argc, char *argv[] )
Here, argc counts the number of arguments. It counts the file name as the first
argument.
The argv[] contains the total number of arguments. The first argument is the file
name always.
The command line arguments are supperated with SPACE.
Always the first command line argument is file path.
Only string values can be passed as command line arguments.
All the command line arguments are stored in a character pointer array called argv[ ].
Total count of command line arguments including file path argument is stored in a
integer parameter called argc.
Pointers
The pointer in C language is a variable which stores the address of another
variable. This variable can be of type int, char, array, function, or any other
pointer. The size of the pointer depends on the architecture. However, in 32-
bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the
address of an integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the a
ddress of the variable n of type integer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known
as indirection pointer used to dereference a pointer.
int *a;//pointer to int
char *c;//pointer to char
Pointer Example
Double Pointer (Pointer to Pointer)
As we know that, a pointer is used to store the address of a variable in
C. Pointer reduces the access time of a variable.
However, In C, we can also define a pointer to store the address of
another pointer. Such pointer is known as a double pointer (pointer to
pointer).
The first pointer is used to store the address of a variable whereas the
second pointer is used to store the address of the first pointer. Let's
understand it by the diagram given below.
The syntax of declaring a double pointer is given below.
int **p; // pointer to a pointer which is pointing to an integer.

More Related Content

Similar to unit_2 (1).pptx

function in in thi pdf you will learn what is fu...
function in  in thi pdf you will learn   what                           is fu...function in  in thi pdf you will learn   what                           is fu...
function in in thi pdf you will learn what is fu...kushwahashivam413
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 
UNIT3.pptx
UNIT3.pptxUNIT3.pptx
UNIT3.pptxNagasaiT
 
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
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfBoomBoomers
 
Unit 4.pdf
Unit 4.pdfUnit 4.pdf
Unit 4.pdfthenmozhip8
 
Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxsangeeta borde
 
Presentation 2 (1).pdf
Presentation 2 (1).pdfPresentation 2 (1).pdf
Presentation 2 (1).pdfziyadaslanbey
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&unionUMA PARAMESWARI
 
C structure
C structureC structure
C structureankush9927
 
Presentation on function
Presentation on functionPresentation on function
Presentation on functionAbu Zaman
 

Similar to unit_2 (1).pptx (20)

function in in thi pdf you will learn what is fu...
function in  in thi pdf you will learn   what                           is fu...function in  in thi pdf you will learn   what                           is fu...
function in in thi pdf you will learn what is fu...
 
C function
C functionC function
C function
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
UNIT3.pptx
UNIT3.pptxUNIT3.pptx
UNIT3.pptx
 
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
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdf
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Unit 4.pdf
Unit 4.pdfUnit 4.pdf
Unit 4.pdf
 
Function in c program
Function in c programFunction in c program
Function in c program
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
Presentation 2 (1).pdf
Presentation 2 (1).pdfPresentation 2 (1).pdf
Presentation 2 (1).pdf
 
Functions
FunctionsFunctions
Functions
 
Functions
Functions Functions
Functions
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
C structure
C structureC structure
C structure
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 

Recently uploaded

ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoĂŁo Esperancinha
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 

Recently uploaded (20)

ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 

unit_2 (1).pptx

  • 1. FUNCTIONS UNIT-II DBS INSTITUTE OF TECHNOLOGY , Kavali, A.P, INDIA
  • 2. • A function is a block of statements that performs a specific task. Let’s say you are writing a C program and you need to perform a same task in that program more than once. In such case you have two options: • a) Use the same set of statements every time you want to perform the task b) Create a function to perform that task, and just call it every time you need to perform that task. • Using option (b) is a good practice and a good programmer always uses functions while writing code in C. • In c, we can divide a large program into the basic building blocks known as function. The function contains the set of programming statements enclosed by {}. A function can be called multiple times to provide reusability and modularity to the C program. In other words, we can say that the collection of functions creates a program. The function is also known as procedureor subroutinein other programming languages.
  • 3. Advantage of functions in C There are the following advantages of C functions. • By using functions, we can avoid rewriting same logic/code again and again in a program. • We can call C functions any number of times in a program and from any place in a program. • We can track a large C program easily when it is divided into multiple functions. • Reusability is the main achievement of C functions. • However, Function calling is always a overhead in a C program.
  • 4. Types of functions 1) Predefined standard library functions • Standard library functions are also known as built-in functions. Functions such as puts(), gets(), printf(), scanf() etc are standard library functions. These functions are already defined in header files (files with .h extensions are called header files such as stdio.h), so we just call them whenever there is a need to use them. • For example, printf() function is defined in <stdio.h> header file so in order to use the printf() function, we need to include the <stdio.h> header file in our program using #include <stdio.h>.
  • 5. 2) User Defined functions • The functions that we create in a program are known as user defined functions or in other words you can say that a function created by user is known as user defined function. • C programming functions are divided into three activities such as, • Function declaration • Function definition • Function call
  • 6. Syntax of a function return_type function_name (argument list) { Set of statements – Block of code } return_type: Return type can be of any data type such as int, double, char, void, short etc. function_name: It can be anything, however it is advised to have a meaningful name for the functions so that it would be easy to understand the purpose of function just by seeing it’s name. argument list: Argument list contains variables names along with their data types. These arguments are kind of inputs for the function. For example – A function which is used to add two integer variables, will be having two integer argument. Block of code: Set of C statements, which will be executed whenever a call will be made to the function.
  • 7. return_type addition(argument list) return_type addition(int num1, int num2) int addition(int num1, int num2); • Function Declaration • The function declaration tells the compiler about function name, the data type of the return value and parameters. The function declaration is also called a function prototype. The function declaration is performed before the main function Function declaration syntax - returnType functionName(parametersList); • In the above syntax, returnType specifies the data type of the value which is sent as a return value from the function definition. The functionName is a user-defined name used to identify the function uniquely in the program. The parametersList is the data values that are sent to the function definition.
  • 8. Function Declaration #include <stdio.h> /*Function declaration*/ int add(int a,b); /*End of Function declaration*/ int main() {
  • 9. Function Definition • The function definition provides the actual code of that function. The function definition is also known as the body of the function. The actual task of the function is implemented in the function definition. That means the actual instructions to be performed by a function are written in function definition. The actual instructions of a function are written inside the braces "{ }". Function definition syntax - returnType functionName(parametersList) { Actual code... }
  • 10. Function Definition int add(int a,int b) //function body { int c; c=a+b; return c; }
  • 11. Function Call • The function call tells the compiler when to execute the function definition. When a function call is executed, the execution control jumps to the function definition where the actual code gets executed and returns to the same functions call once the execution completes. The function call is performed inside the main function or any other function or inside the function itself. • Function call syntax - functionName(parameters); Function call result = add(4,5);
  • 12. #include <stdio.h> int add(int a, int b); //function declaration int main() { int a=10,b=20; int c=add(10,20); //function call printf("Addition:%dn",c); getch(); } int add(int a,int b) //function body { int c; c=a+b; return c; } Addition:30
  • 13. TYPES OF USER DEFINED FUNCTIONS • A function may or may not accept any argument. It may or may not return any value. Based on these facts, There are four different aspects of function calls. • function without arguments and without return value • function without arguments and with return value • function with arguments and without return value • function with arguments and with return value
  • 14. function without arguments and without return value #include<stdio.h> void sum(); void main() { printf("nGoing to calculate the sum of two numbers:"); sum(); } void sum() { int a,b; printf("nEnter two numbers"); scanf("%d %d",&a,&b); printf("The sum is %d",a+b); } OUTPUT: Going to calculate the sum of two numbers: Enter two numbers 10 24 The sum is 34
  • 15. Function without argument and with return value #include<stdio.h> int sum(); void main() { int result; printf("nGoing to calculate the sum of two numbers:"); result = sum(); printf("%d",result); } int sum() { int a,b; printf("nEnter two numbers"); scanf("%d %d",&a,&b); return a+b; } OUTPUT: Going to calculate the sum of two numbers: Enter two numbers 10 24 The sum is 34
  • 16. Function with argument and without return value #include<stdio.h> void sum(int, int); void main() { int a,b,result; printf("nGoing to calculate the sum of two numbers:"); printf("nEnter two numbers:"); scanf("%d %d",&a,&b); sum(a,b); } void sum(int a, int b) { printf("nThe sum is %d",a+b); } OUTPUT: Going to calculate the sum of two numbers: Enter two numbers 10 24 The sum is 34
  • 17. Function with argument and with return value #include<stdio.h> int sum(int, int); void main() { int a,b,result; printf("nGoing to calculate the sum of two numbers:"); printf("nEnter two numbers:"); scanf("%d %d",&a,&b); result = sum(a,b); printf("nThe sum is : %d",result); } int sum(int a, int b) { return a+b; } Going to calculate the sum of two numbers: Enter two numbers:10 20 The sum is : 30
  • 18. In the concept of functions, the function call is known as "Calling Function" and the function definition is known as "Called Function". Parameter Passing in C When a function gets executed in the program, the execution control is transferred from calling-function to called function and executes function definition, and finally comes back to the calling function. When the execution control is transferred from calling-function to called-function it may carry one or number of data values. These data values are called as parameters. Parameters are the data values that are passed from calling function to called function. In C, there are two types of parameters and they are as follows... Actual Parameters Formal Parameters
  • 19. • The actual parameters are the parameters that are speficified in calling function. The formal parameters are the parameters that are declared at called function. When a function gets executed, the copy of actual parameter values are copied into formal parameters. • In C Programming Language, there are two methods to pass parameters from calling function to called function and they are as follows... • Call by Value • Call by Reference
  • 20. #include<stdio.h> #include<conio.h> void swap(int a, int b) { int temp; temp=a; a=b; b=temp; } void main() { int a=100, b=200; clrscr(); swap(a, b); // passing value to function printf("nValue of a: %d",a); printf("nValue of b: %d",b); getch(); } Value of a: 200 Value of b: 100 Call by Value
  • 21. #include<stdio.h> #include<conio.h> void swap(int *a, int *b) { int temp; temp=*a; *a=*b; *b=temp; } void main() { int a=100, b=200; clrscr(); swap(&a, &b); // passing value to function printf("nValue of a: %d",a); printf("nValue of b: %d",b); getch(); } Value of a: 200 Value of b: 100 Call by reference
  • 22. C Recursion A function that calls itself is known as a recursive function. And, this technique is known as recursion. void recurse() { ... .. ... recurse(); ... .. ... } int main() { ... .. ... recurse(); ... .. ... }
  • 23. Storage allocation • Dynamic Memory Allocation in C Programming Language - C language provides features to manual management of memory, by using this feature we can manage memory at run time, whenever we require memory allocation or reallocation at run time by using Dynamic Memory Allocation functions we can create amount of required memory. • Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file. • malloc() • calloc() • realloc() • free()
  • 24. static memory allocation dynamic memory allocation memory is allocated at compile time. memory is allocated at run time. memory can't be increased while executing program. memory can be increased while executing program. used in array. used in linked list.
  • 25. malloc() method “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It initializes each block with default garbage value. Syntax: ptr = (cast-type*) malloc(byte-size) ptr = (int*) malloc(100 * sizeof(int)); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory If space is insufficient, allocation fails and returns a NULL pointer
  • 26. calloc() method calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. It initializes each block with a default value ‘0’. Syntax: ptr = (cast-type*)calloc(n, element-size); ptr = (float*) calloc(25, sizeof(float)); This statement allocates contiguous space in memory for 25 elements each with the size of the float.
  • 27. free() method “free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it. Syntax: free(ptr);
  • 28. realloc() method ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'
  • 29. Storage Classes in C • storage classes in C are used to determine the lifetime, visibility, memory location, and initial value of a variable. There are four types of storage classes in C • Automatic • External • Static • Register
  • 30. Automatic Automatic variables are allocated memory automatically at runtime. The visibility of the automatic variables is limited to the block in which they are defined. The automatic variables are initialized to garbage by default. The memory assigned to automatic variables gets freed upon exiting from the block. The keyword used for defining automatic variables is auto. Every local variable is automatic in C by default. Static Default initial value of the static integral variable is 0 otherwise null. The visibility of the static global variable is limited to the file in which it has declared. The keyword used to define static variable is static.
  • 31. Register The variables defined as the register is allocated the memory into the CPU registers depending upon the size of the memory remaining in the CPU. We can not dereference the register variables, i.e., we can not use &operator for the register variable. The access time of the register variables is faster than the automatic variables. The initial default value of the register local variables is 0. External The external storage class is used to tell the compiler that the variable defined as extern is declared with an external linkage elsewhere in the program. We can only initialize the extern variable globally, i.e., we can not initialize the external variable within any block or method.
  • 32. Storage Classes Storage Place Default Value Scope Lifetime auto RAM Garbage Value Local Within function extern RAM Zero Global Till the end of the main program Maybe declared anywhere in the program static RAM Zero Local Till the end of the main program, Retains value between multiple functions call register Register Garbage Value Local Within the function
  • 33. Strings • The string can be defined as the one-dimensional array of characters terminated by a null ('0'). • The character array or the string is used to manipulate text such as word or sentences. • Each character in the array occupies one byte of memory, and the last character must always be 0. • The termination character ('0') is important in a string since it is the only way to identify where the string ends. • When we define a string as char s[10], the character s[10] is implicitly initialized with the null in the memory.
  • 34. There are two ways to declare a string in c language. By char array By string literal
  • 35. String I/O in C programming
  • 36. String Example #include<stdio.h> #include <string.h> int main(){ char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '0'}; char ch2[11]="javatpoint"; printf("Char Array Value is: %sn", ch); printf("String Literal Value is: %sn", ch2); return 0; } Char Array Value is: javatpoint String Literal Value is: javatpoint
  • 37. String Handling Functions C programming language provides a set of pre-defined functions called string handling functions to work with string values. The string handling functions are defined in a header file called string.h.  Whenever we want to use any string handling function we must include the header file called string.h.
  • 38. No. Function Description 1) strlen(string_name) returns the length of string name. 2) strcpy(destination, source) copies the contents of source string to destination string. 3) strcat(first_string, second_string) concats or joins first string with second string. The result of the string is stored in first string. 4) strcmp(first_string, second_string) compares the first string with second string. If both strings are same, it returns 0. 5) strrev(string) returns reverse string. 6) strlwr(string) returns string characters in lowercase. 7) strupr(string) returns string characters in uppercase.
  • 39. strlen() function The strlen() function returns the length of the given string. It doesn't count null character '0'. #include<stdio.h> #include <string.h> int main(){ char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '0'}; printf("Length of string is: %d",strlen(ch)); return 0; } Output: Length of string is: 10
  • 40. strcpy() The strcpy(destination, source) function copies the source string in destination. #include<stdio.h> #include <string.h> int main(){ char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '0'}; char ch2[20]; strcpy(ch2,ch); printf("Value of second string is: %s",ch2); return 0; } Output: Value of second string is: javatpoint
  • 41. strrev() The strrev(string) function returns reverse of the given string
  • 42. strlwr() The strlwr(string) function returns string characters in lowercase #include<stdio.h> #include <string.h> int main(){ char str[20]; printf("Enter string: "); gets(str);//reads string from console printf("String is: %s",str); printf("nLower String is: %s",strlwr(str)); return 0; } Output: Enter string: JAVATpoint String is: JAVATpoint Lower String is: javatpoint
  • 43. strupr() The strupr(string) function returns string characters in uppercase. #include<stdio.h> #include <string.h> int main(){ char str[20]; printf("Enter string: "); gets(str);//reads string from console printf("String is: %s",str); printf("nUpper String is: %s",strupr(str)); return 0; } Output: Enter string: javatpoint String is: javatpoint Upper String is: JAVATPOINT
  • 44. structures • In C, there are cases where we need to store multiple attributes of an entity. • It is not necessary that an entity has all the information of one type only. • It can have different attributes of different data types. • For example, an entity Student may have its name (string), roll number (int), marks (float).
  • 45. Structure in c is a user-defined data type that enables us to store the collection of different data types. Each element of a structure is called a member. The ,struct keyword is used to define the structure. Let's see the syntax to define the structure in c. struct structure_name { data_type member1; data_type member2; . . data_type memeberN; }; Let's see the example to define a structure for an entity employee in c. struct employee { int id; char name[20]; float salary; };
  • 46.
  • 47. Declaring structure variable We can declare a variable for the structure so that we can access the member of the structure easily. There are two ways to declare structure variable: •By struct keyword within main() function •By declaring a variable at the time of defining the structure.
  • 48. Accessing members of the structure There are two ways to access structure members: By . (member or dot operator) By -> (structure pointer operator)
  • 49. Unions Like structure, Union in c language is a user-defined data type that is used to store the different type of elements. At once, only one member of the union can occupy the memory. In other words, we can say that the size of the union in any instance is equal to the size of its largest element. Advantage of union over structure It occupies less memory because it occupies the size of the largest member only.
  • 50.
  • 51. Command Line Arguments The arguments passed from command line are called command line arguments. These arguments are handled by main() function. To support command line argument, you need to change the structure of main() function as given below. int main(int argc, char *argv[] ) Here, argc counts the number of arguments. It counts the file name as the first argument. The argv[] contains the total number of arguments. The first argument is the file name always. The command line arguments are supperated with SPACE. Always the first command line argument is file path. Only string values can be passed as command line arguments. All the command line arguments are stored in a character pointer array called argv[ ]. Total count of command line arguments including file path argument is stored in a integer parameter called argc.
  • 52. Pointers The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer. The size of the pointer depends on the architecture. However, in 32- bit architecture the size of a pointer is 2 byte. Consider the following example to define a pointer which stores the address of an integer. int n = 10; int* p = &n; // Variable p of type pointer is pointing to the a ddress of the variable n of type integer. Declaring a pointer The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection pointer used to dereference a pointer. int *a;//pointer to int char *c;//pointer to char
  • 54.
  • 55.
  • 56. Double Pointer (Pointer to Pointer) As we know that, a pointer is used to store the address of a variable in C. Pointer reduces the access time of a variable. However, In C, we can also define a pointer to store the address of another pointer. Such pointer is known as a double pointer (pointer to pointer). The first pointer is used to store the address of a variable whereas the second pointer is used to store the address of the first pointer. Let's understand it by the diagram given below. The syntax of declaring a double pointer is given below. int **p; // pointer to a pointer which is pointing to an integer.