SlideShare ist ein Scribd-Unternehmen logo
1 von 61
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.
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();
... .. ...
}
RECURSION
#include<stdio.h>
int main()
{
printf("Hello world");
main();
return 0;
}
In this program, we are calling main() from main() which is
recursion. But we haven’t defined any condition for the
program to exit. Hence this code will print “Hello world”
infinitely in the output screen.
FACTORIAL USING RECURSION
• main()
• {
• int n;
• printf(“enter n value”);
• scanf(“%d”,&n);
• res=fact(n);
• printf(“%d”,res);
• }
• int fact(int n)
• {
• int res;
• if(n==0)
• res=1;
• else
• res=n*fact(n-1);
• return res;
• }
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()
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
Syntax:
storage-specifier data-type variable-name;
Example
int marks;
auto int marks;
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)
STRUCTURE
• struct Student
• {
• char name[25];
• int age;
• char branch[10];
• char gender;
• };
• int main()
• {
• struct Student s1;
• /*
• s1 is a variable of Student type and
• age is a member of Student
• */
• s1.age = 18;
• /* using string function to add name*/
• strcpy(s1.name, "Viraaj");
• /*displaying the stored values*/
• printf("Name of Student 1: %sn", s1.name);
• printf("Age of Student 1: %dn", s1.age);
• return 0;
• }
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[] )
{
// body;
}
Compile and run CMD programs
• Command line arguments are not compile and run like
normal C programs, these programs are compile and run on
command prompt. To Compile and Link Command Line
Program we need TCC Command.
• First open command prompt
• Follow you directory where your code saved.
• For compile -> C:/TC/BIN>TCC mycmd.c
• For run -> C:/TC/BIN>mycmd 10 20
• Explanation: Here mycmd is your program file name and
TCC is a Command. In "mycmd 10 20" statement we pass
two arguments.
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
Expressions involving pointers:
• Arithmetic Operators
• We can perform arithmetic operations to pointer variables using arithmetic
operators. We can add an integer or subtract an integer using a pointer pointing to
that integer variable.
• Examples:
• *ptr1 + *ptr2
• *ptr1 * *ptr2
• *ptr1 + *ptr2 - *ptr3
• Relational Operators
• Relational operations are often used to compare the values of the variable based
on which we can take decisions.
• Example:
• *ptr1 > *ptr2
• *ptr1 < *ptr2
• The value of the relational expression is either 0 or 1 that is false or true. The
expression will return value 1 if the expression is true and it’ll return value 0 if
false.

Weitere ähnliche Inhalte

Ähnlich wie unit_2.pptx (20)

Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
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
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
C function
C functionC function
C function
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Function in c
Function in cFunction in c
Function in c
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Unit 4.pdf
Unit 4.pdfUnit 4.pdf
Unit 4.pdf
 
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...
 
Function in c
Function in cFunction in c
Function in c
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Functions
Functions Functions
Functions
 
cp Module4(1)
cp Module4(1)cp Module4(1)
cp Module4(1)
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
Function
Function Function
Function
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptx
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
 
Functions
FunctionsFunctions
Functions
 
Presentation 2 (1).pdf
Presentation 2 (1).pdfPresentation 2 (1).pdf
Presentation 2 (1).pdf
 
Module 3-Functions
Module 3-FunctionsModule 3-Functions
Module 3-Functions
 

Kürzlich hochgeladen

Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxVelmuruganTECE
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating SystemRashmi Bhat
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...Amil Baba Dawood bangali
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptMadan Karki
 
The SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsThe SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsDILIPKUMARMONDAL6
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptJasonTagapanGulla
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 

Kürzlich hochgeladen (20)

Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptx
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating System
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.ppt
 
The SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsThe SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teams
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.ppt
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 

unit_2.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. 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>.
  • 4. 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
  • 5. 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.
  • 6. 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.
  • 7. Function Declaration #include <stdio.h> /*Function declaration*/ int add(int a,b); /*End of Function declaration*/ int main() {
  • 8. 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... }
  • 9. Function Definition int add(int a,int b) //function body { int c; c=a+b; return c; }
  • 10. 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);
  • 11. #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
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. • 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
  • 19. #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
  • 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 reference
  • 21. 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(); ... .. ... }
  • 22. RECURSION #include<stdio.h> int main() { printf("Hello world"); main(); return 0; } In this program, we are calling main() from main() which is recursion. But we haven’t defined any condition for the program to exit. Hence this code will print “Hello world” infinitely in the output screen.
  • 23. FACTORIAL USING RECURSION • main() • { • int n; • printf(“enter n value”); • scanf(“%d”,&n); • res=fact(n); • printf(“%d”,res); • } • int fact(int n) • { • int res; • if(n==0) • res=1; • else • res=n*fact(n-1); • return res; • }
  • 24. 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()
  • 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
  • 31. 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
  • 32. 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.
  • 33. There are two ways to declare a string in c language. By char array By string literal
  • 34. String I/O in C programming
  • 35. 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
  • 36. 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.
  • 37. 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.
  • 38. 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
  • 39. 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
  • 40. strrev() The strrev(string) function returns reverse of the given string
  • 41. 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
  • 42. 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
  • 43. 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).
  • 44. 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; };
  • 45.
  • 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. STRUCTURE • struct Student • { • char name[25]; • int age; • char branch[10]; • char gender; • }; • int main() • { • struct Student s1; • /* • s1 is a variable of Student type and • age is a member of Student • */ • s1.age = 18; • /* using string function to add name*/ • strcpy(s1.name, "Viraaj"); • /*displaying the stored values*/ • printf("Name of Student 1: %sn", s1.name); • printf("Age of Student 1: %dn", s1.age); • return 0; • }
  • 50. 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.
  • 51.
  • 52.
  • 53. 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[] ) { // body; }
  • 54. Compile and run CMD programs • Command line arguments are not compile and run like normal C programs, these programs are compile and run on command prompt. To Compile and Link Command Line Program we need TCC Command. • First open command prompt • Follow you directory where your code saved. • For compile -> C:/TC/BIN>TCC mycmd.c • For run -> C:/TC/BIN>mycmd 10 20 • Explanation: Here mycmd is your program file name and TCC is a Command. In "mycmd 10 20" statement we pass two arguments.
  • 55.
  • 56. 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
  • 58.
  • 59.
  • 61. • Arithmetic Operators • We can perform arithmetic operations to pointer variables using arithmetic operators. We can add an integer or subtract an integer using a pointer pointing to that integer variable. • Examples: • *ptr1 + *ptr2 • *ptr1 * *ptr2 • *ptr1 + *ptr2 - *ptr3 • Relational Operators • Relational operations are often used to compare the values of the variable based on which we can take decisions. • Example: • *ptr1 > *ptr2 • *ptr1 < *ptr2 • The value of the relational expression is either 0 or 1 that is false or true. The expression will return value 1 if the expression is true and it’ll return value 0 if false.