SlideShare a Scribd company logo
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

More Related Content

What's hot

Software Concepts Notes
Software Concepts NotesSoftware Concepts Notes
Software Concepts Notes
Prof. Dr. K. Adisesha
 
Structure in C language
Structure in C languageStructure in C language
Structure in C language
CGC Technical campus,Mohali
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
VedaGayathri1
 
Variables in python
Variables in pythonVariables in python
Variables in python
Jaya Kumari
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
 
Pointers in C
Pointers in CPointers in C
Pointers in C
Kamal Acharya
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
Neeru Mittal
 
Strings in python
Strings in pythonStrings in python
Strings in python
Prabhakaran V M
 
C function presentation
C function presentationC function presentation
C function presentation
Touhidul Shawan
 
Unit 3. Input and Output
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
Ashim Lamichhane
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
Md. Ashraful Islam
 
Array and string
Array and stringArray and string
Array and string
prashant chelani
 
Arrays in c
Arrays in cArrays in c
Arrays in c
vampugani
 
Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C Programming
Kamal Acharya
 
Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
Marcos Rebelo
 
Unit 1-introduction to perl
Unit 1-introduction to perlUnit 1-introduction to perl
Unit 1-introduction to perl
sana mateen
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
Sreedhar Chowdam
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programming
Harshita Yadav
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 

What's hot (20)

Software Concepts Notes
Software Concepts NotesSoftware Concepts Notes
Software Concepts Notes
 
Structure in C language
Structure in C languageStructure in C language
Structure in C language
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
C function presentation
C function presentationC function presentation
C function presentation
 
Unit 3. Input and Output
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 
Array and string
Array and stringArray and string
Array and string
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C Programming
 
Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 
Unit 1-introduction to perl
Unit 1-introduction to perlUnit 1-introduction to perl
Unit 1-introduction to perl
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programming
 
Java Streams
Java StreamsJava Streams
Java Streams
 

Similar to Functions

CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
ArshiniGubbala3
 
Function
Function Function
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
4th unit full
4th unit full4th unit full
4th unit full
Murali Saktheeswaran
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
SaraswathiTAsstProfI
 
Functions
Functions Functions
Functions
Dr.Subha Krishna
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
Venkatesh Goud
 
Functions
FunctionsFunctions
Functions
Pragnavi Erva
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
Ashwini Raut
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
Bharath904863
 
Function
FunctionFunction
Function
Saniati
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
LadallaRajKumar
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
JVenkateshGoud
 
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
Ashim Lamichhane
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
NirmalaShinde3
 
Function C programming
Function C programmingFunction C programming
Function C programming
Appili Vamsi Krishna
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
Sampath Kumar
 

Similar to 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
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
 
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
 
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
 

Recently uploaded

Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 

Recently uploaded (20)

Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 

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