SlideShare uma empresa Scribd logo
1 de 41
Multidimensional Arrays
• Define multidimensional arrays as array of arrays.
• Data in multidimensional arrays are stored in tabular form (in row major
order).
Syntax
data_type array_name[size1][size2]....[sizeN];
• Three dimensional array: int three_d[10][20][30];
• Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
• Initializing & Accessing 3-DArray:
– Initialization & Accessing is same as that of 2D arrays.
– The difference is the number of dimension increases so the number of
nested braces and number of loops will also increase.
Method 1:
int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23};
Better Method:
int x[2][3][4] = { { {0,1,2,3}, {4,5,6,7}, {8,9,10,11} }, { {12,13,14,15},
{16,17,18,19}, {20,21,22,23} } };
Functions
Functions
• A function is a block of code that performs a specific task.
• A function is a self contained block of statements that perform a logical
task of some kind.
• C allows the user to define functions according to our need. These
functions are known as user-defined functions.
• Complex Large problem is easier to solve by dividing it into several smaller,
self-contained parts that perform a specific task called Functions ---
Modularization Concept
Advantages of Functions
• Logical clarity – decomposing a program into several concise functions
– Makes program easier to understand.
– Easier to write
– Easier to debug
• Separates the concept (what is done) from the implementation (how it is
done).
• Avoids (redundant) repeated programming of same instructions
Repeated Instructions are placed inside function
Access to function many times with different data when needed
• To build customized library of frequently used routines contains system-
dependent features
• Portability – programs are written that are independent of system-
dependent features
Introduction
• One important function is main()
• Execution always begin and end by instructions in main()
• Additional functions will be subordinate to main
• Sub Function definitions may appear in any order
• One function cannot be embedded within another
• Same function can be called from different places of program
• C supports lot of predefined functions known as Library Functions
• User is free to define its own functions and use it called as user-defined
functions
– Function Body
– Function Call
– Function Prototype
• Information is passed to the function via special identifiers called
arguments (parameters)
• Information is returned via return statement
Defining a Function/ Function Definition
• It contains block of code to perform a specific task
• When a function is called, the compiler starts
executing the codes inside the body of a function.
Syntax:
returnType functionName(type1 arg1, type2 arg2, ...)
{
//body of the function
}
• The first line is known as function header and the statements within the
opening and closing braces is known as the function body.
• Function header:-
– Consists of return type, the function name, and the formal
parameter list.
– Function name is any valid identifier
– Return type specifies the type of value that the function is expected to
return to the program calling the function. By default it is integer type.
– The parameter list called formal parameters declares the variables that
will receive the data sent by the calling program.
– Formal parameters are local to function
• Function body:-
– Contains the declaration and executable statements necessary for
performing the required task.
– It is enclosed with open and closed braces
void sum(int a, int b)
{
int c;
c = a + b;
printf(“Sum = %d”,c);
}
display()
{
printf(“Welcome”);
}
//By default, return type of the function is int
display()
{
printf(“Welcome”);
return;
}
Function Call/ Accessing a Function
• A function can be called by using its name followed by a list of
actual arguments.
• During function call, control of the program is transferred to the
user-defined function
• It is the statement inside the main( ) or sub function
Syntax:
functionName(arg1, arg2, ...);
• Here, value of actual argument is transferred into function and
assigned to formal argument
add(2,3);
display();
FUNCTION PROTOTYPE
• It is the declaration of a function
• It specifies function's name, parameters and return type
• It doesn't contain function body
• It gives information to the compiler that the function may later be used
in the program.
• It is usually written in the beginning of the program
Syntax:
returnType functionName(type1 arg1, type2 arg2,...);
• It is not needed if the function is defined before the main( ) function.
• C prefers top-down approach.
• Argument names can be omitted since these are “dummy arguments”
that are not used inside our programs
• Function Prototypes are not mandatory in C
void add(int, int);
void add(int x, int y);
int display();
void display();
#include<stdion.h>
void add(int, int); //Function Prototype
void main()
{
int a=10, b=30;
add(a,b); //Function Call
}
//Function Definition
void add(int x,int y) //Function Header
{
int sum; // Function Body
sum = x + y; “
printf(“Sum = %d”,sum); “
}
#include<stdion.h>
//Function Definition
void add(int x,int y) //Function Header
{
int sum; // Function Body
sum = x + y; “
printf(“Sum = %d”,sum); “
}
void main()
{
int a=10, b=30;
add(a,b); //Function Call
}
• Actual arguments:
– Arguments passed in a function call are called actual arguments.
– These arguments are defined in the calling function.
• Formal arguments:
– Parameters/arguments in a function definition
– Scope of formal arguments is local to the function definition in
which they are used.
– Belongs to the called function
– Copy of the actual arguments.
– A change in formal arguments would not be reflected in the
actual arguments.
PASSING ARGUMENTS TO FUNCTIONS
• Argument refers to the variable passed to the function.
• In the above example, two variables a and b are passed during function
call. These arguments are called actual arguments
• The parameters x and y in function definition accepts the passed
arguments. These arguments are called formal parameters.
• We can pass arguments by value – Copies of data passed
• We can pass arguments by reference – Original copy of data is passed
• We can pass array to function – address of first array element is passed
Call by Value vs. Call by Reference
Call by Value Call by Reference
This is the usual method to call a function in
which value of the variable is passed as an
argument
In this method, the address of the variable
is passed as an argument
Any alternation in the value of the argument
passed is local to the function and is not
accepted in the calling program
Any alternation in the value of the
argument passed is accepted in the calling
program
Memory location occupied by formal and
actual arguments values are different
Memory location occupied by formal and
actual arguments values are same
Since a new location is created, this method
is slow
Since the existing memory location is used
through its address, this method is fast
There is no possibility of wrong data
manipulation since the arguments are
directly used in an application
There is a possibility of wrong data
manipulation since the addresses are used
in an expression. A good skill of
programming is required here
• Example Program:
– Swap Two Numbers using Call by Value
– Swap Two Numbers using Call by Reference
Passing Array to a function
• To pass an entire array to a function, only the name of the array is passed as an
argument.
functionname(arrayname); //Function Call
• Define function in one of the ways:
• First way:
return_type function(type arrayname[])
Declaring blank subscript notation [] is the widely used technique.
• Second way:
return_type function(type arrayname[SIZE])
Optionally, we can define size in subscript notation [].
• Third way:
return_type function(type *arrayname)
• Elements are not passed to function
• Passes the address of the first array element
• Now, formal argument becomes the pointer to the first array element
• Example Program:
– Search an element in an array using functions
RETURN STATEMENT
• The return statement terminates the execution of a function and returns a
value to the calling function.
• The program control is transferred to the calling function after return
statement.
Syntax:
return (expression);
Example:
return a;
return (a+b);
• The type of value returned from the function and the return type specified
in function prototype and function definition must match.
• The value of variable result is returned to the variable sum in the main( )
function.
• Program can have number of return statements.
• main() returns 0 or 1 to OS by default: 0 --- successful completion, 1 –
Unsuccessful/ Interruption
• Sub function returns 0 or 1 to the calling function: 0 – unsuccessful, 1 –
successful execution
void greatest(int a,int b)
{
if (a > b)
return a;
else
return b;
}
• User-defined functions can be categorized as:
– Function with no arguments and no return value
– Function with no arguments and a return value
– Function with arguments and no return value
– Function with arguments and a return value
1) No arguments passed and no
return Value
#include <stdio.h>
void addNumbers( ); // function prototype
void main()
{
addNumbers( ); // function call without args & return
}
void addNumbers( ) // function definition
{
int n1,n2, sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = n1+n2;
printf("sum = %d",sum);
}
• The addNumbers( ) function takes no arguments and doesn’t return any
value
• The empty parentheses in addNumbers( ); statement inside the main()
function indicates that no argument is passed to the function.
• The return type of the function is void. Hence, no value is returned from
the function.
2) No arguments passed but a return
value
#include <stdio.h>
int addNumbers( ); // function prototype
void main()
{
sum = addNumbers( ); // function call with return
printf("sum = %d",sum);
}
int addNumbers( ) // function definition
{
int n1,n2, result;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
result = n1+n2;
return result; // return statement
}
• The empty parentheses in sum = addNumbers( ); statement indicates that
no argument is passed to the function.
• The value returned from the function is assigned to sum.
• Here, the addNumbers( ) function takes input from the user and returns
resultant value to the main( ).
3) Argument passed but no return
value
#include <stdio.h>
void addNumbers(int a, int b); // function prototype
void main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
addNumbers(n1, n2); // function call with arguments
}
void addNumbers(int a,int b) // function definition
{
int result;
result = a+b;
printf("sum = %d",result); //No Return Statement
}
• The integer values entered by the user is passed to addNumbers(n1,n2)
function.
• This function calculates and prints the result.
4) Argument passed and a return
value
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
void main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
}
int addNumbers(int a,int b) // function definition
{
int result;
result = a+b;
return result; // return statement
}
• The input from the user is passed to function.
• The function checks calculates and returns the result
• Then, the result is displayed from the main() function
RECURSION FUCTION
• A function that calls itself is known as a recursive function. And, this
technique is known as recursion.
• The recursion continues until some condition is met to prevent it.
• To prevent infinite recursion, if...else statement can be used where one
branch makes the recursive call and other doesn't.
• A recursive function performs the tasks by dividing it into the subtasks.
• Recursion program consists of two parts:
– Base case: It is a termination condition defined in the
function. It stops the recursion. It returns the final result.
– Recursive case: where the function keeps calling itself to
perform a subtask
Example: Factorial Calculation using recursion
long fact (int);
void main()
{
int n;
long f;
printf("Enter the number : ");
scanf("%d“,&n);
f = fact(n);
printf(“Factorial of %d is %ld",n, f);
}
long fact(int n)
{
if (n==0)
return 0;
else
return n*fact(n-1);
}
Output
Enter the number : 5
Factorial of 5 is 120

Mais conteúdo relacionado

Mais procurados (20)

Function in c language(defination and declaration)
Function in c language(defination and declaration)Function in c language(defination and declaration)
Function in c language(defination and declaration)
 
Storage Class in C Progrmming
Storage Class in C Progrmming Storage Class in C Progrmming
Storage Class in C Progrmming
 
Modular Programming in C
Modular Programming in CModular Programming in C
Modular Programming in C
 
python.pptx
python.pptxpython.pptx
python.pptx
 
Features of c
Features of cFeatures of c
Features of c
 
C formatted and unformatted input and output constructs
C  formatted and unformatted input and output constructsC  formatted and unformatted input and output constructs
C formatted and unformatted input and output constructs
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
SPL 9 | Scope of Variables in C
SPL 9 | Scope of Variables in CSPL 9 | Scope of Variables in C
SPL 9 | Scope of Variables in C
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Main method in java
Main method in javaMain method in java
Main method in java
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Scope of variables
Scope of variablesScope of variables
Scope of variables
 
Exceptions in python
Exceptions in pythonExceptions in python
Exceptions in python
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2
 
Stack and heap
Stack and heapStack and heap
Stack and heap
 
Storage classes
Storage classesStorage classes
Storage classes
 
Function lecture
Function lectureFunction lecture
Function lecture
 
C++ concept of Polymorphism
C++ concept of  PolymorphismC++ concept of  Polymorphism
C++ concept of Polymorphism
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 

Semelhante a Functions (20)

CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
Function
Function Function
Function
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
4th unit full
4th unit full4th unit full
4th unit full
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
Functions
Functions Functions
Functions
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
Functions
FunctionsFunctions
Functions
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
Function
FunctionFunction
Function
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 

Último

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 

Último (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 

Functions

  • 1. Multidimensional Arrays • Define multidimensional arrays as array of arrays. • Data in multidimensional arrays are stored in tabular form (in row major order). Syntax data_type array_name[size1][size2]....[sizeN]; • Three dimensional array: int three_d[10][20][30]; • Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
  • 2.
  • 3. • Initializing & Accessing 3-DArray: – Initialization & Accessing is same as that of 2D arrays. – The difference is the number of dimension increases so the number of nested braces and number of loops will also increase. Method 1: int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23}; Better Method: int x[2][3][4] = { { {0,1,2,3}, {4,5,6,7}, {8,9,10,11} }, { {12,13,14,15}, {16,17,18,19}, {20,21,22,23} } };
  • 5. Functions • A function is a block of code that performs a specific task. • A function is a self contained block of statements that perform a logical task of some kind. • C allows the user to define functions according to our need. These functions are known as user-defined functions. • Complex Large problem is easier to solve by dividing it into several smaller, self-contained parts that perform a specific task called Functions --- Modularization Concept
  • 6.
  • 7. Advantages of Functions • Logical clarity – decomposing a program into several concise functions – Makes program easier to understand. – Easier to write – Easier to debug • Separates the concept (what is done) from the implementation (how it is done). • Avoids (redundant) repeated programming of same instructions Repeated Instructions are placed inside function Access to function many times with different data when needed • To build customized library of frequently used routines contains system- dependent features • Portability – programs are written that are independent of system- dependent features
  • 8. Introduction • One important function is main() • Execution always begin and end by instructions in main() • Additional functions will be subordinate to main • Sub Function definitions may appear in any order • One function cannot be embedded within another • Same function can be called from different places of program • C supports lot of predefined functions known as Library Functions • User is free to define its own functions and use it called as user-defined functions – Function Body – Function Call – Function Prototype • Information is passed to the function via special identifiers called arguments (parameters) • Information is returned via return statement
  • 9. Defining a Function/ Function Definition • It contains block of code to perform a specific task • When a function is called, the compiler starts executing the codes inside the body of a function. Syntax: returnType functionName(type1 arg1, type2 arg2, ...) { //body of the function }
  • 10. • The first line is known as function header and the statements within the opening and closing braces is known as the function body. • Function header:- – Consists of return type, the function name, and the formal parameter list. – Function name is any valid identifier – Return type specifies the type of value that the function is expected to return to the program calling the function. By default it is integer type. – The parameter list called formal parameters declares the variables that will receive the data sent by the calling program. – Formal parameters are local to function • Function body:- – Contains the declaration and executable statements necessary for performing the required task. – It is enclosed with open and closed braces
  • 11. void sum(int a, int b) { int c; c = a + b; printf(“Sum = %d”,c); }
  • 12. display() { printf(“Welcome”); } //By default, return type of the function is int display() { printf(“Welcome”); return; }
  • 13. Function Call/ Accessing a Function • A function can be called by using its name followed by a list of actual arguments. • During function call, control of the program is transferred to the user-defined function • It is the statement inside the main( ) or sub function Syntax: functionName(arg1, arg2, ...); • Here, value of actual argument is transferred into function and assigned to formal argument
  • 15. FUNCTION PROTOTYPE • It is the declaration of a function • It specifies function's name, parameters and return type • It doesn't contain function body • It gives information to the compiler that the function may later be used in the program. • It is usually written in the beginning of the program Syntax: returnType functionName(type1 arg1, type2 arg2,...); • It is not needed if the function is defined before the main( ) function. • C prefers top-down approach. • Argument names can be omitted since these are “dummy arguments” that are not used inside our programs • Function Prototypes are not mandatory in C
  • 16. void add(int, int); void add(int x, int y); int display(); void display();
  • 17. #include<stdion.h> void add(int, int); //Function Prototype void main() { int a=10, b=30; add(a,b); //Function Call } //Function Definition void add(int x,int y) //Function Header { int sum; // Function Body sum = x + y; “ printf(“Sum = %d”,sum); “ }
  • 18. #include<stdion.h> //Function Definition void add(int x,int y) //Function Header { int sum; // Function Body sum = x + y; “ printf(“Sum = %d”,sum); “ } void main() { int a=10, b=30; add(a,b); //Function Call }
  • 19. • Actual arguments: – Arguments passed in a function call are called actual arguments. – These arguments are defined in the calling function. • Formal arguments: – Parameters/arguments in a function definition – Scope of formal arguments is local to the function definition in which they are used. – Belongs to the called function – Copy of the actual arguments. – A change in formal arguments would not be reflected in the actual arguments.
  • 20. PASSING ARGUMENTS TO FUNCTIONS • Argument refers to the variable passed to the function. • In the above example, two variables a and b are passed during function call. These arguments are called actual arguments • The parameters x and y in function definition accepts the passed arguments. These arguments are called formal parameters. • We can pass arguments by value – Copies of data passed • We can pass arguments by reference – Original copy of data is passed • We can pass array to function – address of first array element is passed
  • 21.
  • 22. Call by Value vs. Call by Reference Call by Value Call by Reference This is the usual method to call a function in which value of the variable is passed as an argument In this method, the address of the variable is passed as an argument Any alternation in the value of the argument passed is local to the function and is not accepted in the calling program Any alternation in the value of the argument passed is accepted in the calling program Memory location occupied by formal and actual arguments values are different Memory location occupied by formal and actual arguments values are same Since a new location is created, this method is slow Since the existing memory location is used through its address, this method is fast There is no possibility of wrong data manipulation since the arguments are directly used in an application There is a possibility of wrong data manipulation since the addresses are used in an expression. A good skill of programming is required here
  • 23. • Example Program: – Swap Two Numbers using Call by Value – Swap Two Numbers using Call by Reference
  • 24. Passing Array to a function • To pass an entire array to a function, only the name of the array is passed as an argument. functionname(arrayname); //Function Call • Define function in one of the ways: • First way: return_type function(type arrayname[]) Declaring blank subscript notation [] is the widely used technique. • Second way: return_type function(type arrayname[SIZE]) Optionally, we can define size in subscript notation []. • Third way: return_type function(type *arrayname) • Elements are not passed to function • Passes the address of the first array element • Now, formal argument becomes the pointer to the first array element
  • 25. • Example Program: – Search an element in an array using functions
  • 26. RETURN STATEMENT • The return statement terminates the execution of a function and returns a value to the calling function. • The program control is transferred to the calling function after return statement. Syntax: return (expression); Example: return a; return (a+b); • The type of value returned from the function and the return type specified in function prototype and function definition must match.
  • 27. • The value of variable result is returned to the variable sum in the main( ) function. • Program can have number of return statements. • main() returns 0 or 1 to OS by default: 0 --- successful completion, 1 – Unsuccessful/ Interruption • Sub function returns 0 or 1 to the calling function: 0 – unsuccessful, 1 – successful execution
  • 28. void greatest(int a,int b) { if (a > b) return a; else return b; }
  • 29. • User-defined functions can be categorized as: – Function with no arguments and no return value – Function with no arguments and a return value – Function with arguments and no return value – Function with arguments and a return value
  • 30. 1) No arguments passed and no return Value #include <stdio.h> void addNumbers( ); // function prototype void main() { addNumbers( ); // function call without args & return } void addNumbers( ) // function definition { int n1,n2, sum; printf("Enters two numbers: "); scanf("%d %d",&n1,&n2); sum = n1+n2; printf("sum = %d",sum); }
  • 31. • The addNumbers( ) function takes no arguments and doesn’t return any value • The empty parentheses in addNumbers( ); statement inside the main() function indicates that no argument is passed to the function. • The return type of the function is void. Hence, no value is returned from the function.
  • 32. 2) No arguments passed but a return value #include <stdio.h> int addNumbers( ); // function prototype void main() { sum = addNumbers( ); // function call with return printf("sum = %d",sum); } int addNumbers( ) // function definition { int n1,n2, result; printf("Enters two numbers: "); scanf("%d %d",&n1,&n2); result = n1+n2; return result; // return statement }
  • 33. • The empty parentheses in sum = addNumbers( ); statement indicates that no argument is passed to the function. • The value returned from the function is assigned to sum. • Here, the addNumbers( ) function takes input from the user and returns resultant value to the main( ).
  • 34. 3) Argument passed but no return value #include <stdio.h> void addNumbers(int a, int b); // function prototype void main() { int n1,n2,sum; printf("Enters two numbers: "); scanf("%d %d",&n1,&n2); addNumbers(n1, n2); // function call with arguments } void addNumbers(int a,int b) // function definition { int result; result = a+b; printf("sum = %d",result); //No Return Statement }
  • 35. • The integer values entered by the user is passed to addNumbers(n1,n2) function. • This function calculates and prints the result.
  • 36. 4) Argument passed and a return value #include <stdio.h> int addNumbers(int a, int b); // function prototype void main() { int n1,n2,sum; printf("Enters two numbers: "); scanf("%d %d",&n1,&n2); sum = addNumbers(n1, n2); // function call printf("sum = %d",sum); } int addNumbers(int a,int b) // function definition { int result; result = a+b; return result; // return statement }
  • 37. • The input from the user is passed to function. • The function checks calculates and returns the result • Then, the result is displayed from the main() function
  • 38. RECURSION FUCTION • A function that calls itself is known as a recursive function. And, this technique is known as recursion. • The recursion continues until some condition is met to prevent it. • To prevent infinite recursion, if...else statement can be used where one branch makes the recursive call and other doesn't. • A recursive function performs the tasks by dividing it into the subtasks.
  • 39. • Recursion program consists of two parts: – Base case: It is a termination condition defined in the function. It stops the recursion. It returns the final result. – Recursive case: where the function keeps calling itself to perform a subtask
  • 40.
  • 41. Example: Factorial Calculation using recursion long fact (int); void main() { int n; long f; printf("Enter the number : "); scanf("%d“,&n); f = fact(n); printf(“Factorial of %d is %ld",n, f); } long fact(int n) { if (n==0) return 0; else return n*fact(n-1); } Output Enter the number : 5 Factorial of 5 is 120