0% found this document useful (0 votes)
8 views57 pages

FUNCTIONS-unit3

Uploaded by

G Balaji
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
8 views57 pages

FUNCTIONS-unit3

Uploaded by

G Balaji
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 57

Unit-3

FUNCTIONS
ECE Branch
What is a function in C

A function is a block of statements or group of statements that can be used to
perform a task.
• A function is known with various names like a method or a subroutine or a
procedure, etc.
• Functions are used to break up large programs into named sections or methods.
• Functions are used to write some piece of code once that has to run multiple
times.
• To create a function we need to know Function declaration, Definition and calling.
• A function declaration tells the compiler about a function's name, return type, and
parameters.
• A function definition provides the actual body of the function.
• Call a Function: Declared functions are not executed immediately. They are "saved
for later use", and will be executed when they are called. To call a function, write
the function's name followed by two parentheses () and a semicolon ;
Diagram of function
• It is much easier to write a structured program where a large
program can be divided into a smaller, simpler task.
• Allowing the code to be called many times
• Easier to read and update
• It is easier to debug a structured program where there error is easy
to find and fix. (OR)
1 Easy to implement and update.
2 Easy to read and understand.
3 Easy to debug.
4 Modularity can be achieved – Divides the large program in to
smaller ones.
5 Code re-usability
6 Reduces the code duplication(redundancy).
7 Length of the program can be reduced.
DEFINING A FUNCTION
• In C language A function definition consists of
function header and function body.
• The general form of a function Definition is as
follows:

• Return_datatype function_name(parameters list)


{
declarations;
statements; Body of the function.
return(expression);
}
Example of Function definition
PARTS OF A FUNCTION
 Here are all the parts of a function:
 Return Type: A function may or may not have return type value. The return type is
depends on the data type of the value . If you don’t want to return a result from a
function, you can use the Keyword void return type.
• Function Name: This is the actual name of the function. The function name and the
parameter list together represent the function signature.
Parameters list: A parameter is like a placeholder. Arguments are written within
parenthesis at the time of function call or function definition. Parameters are optional;
some times a function may contain no parameters.
Function definition: The function body contains a collection of statements that define
what the function does.
Called function: the function which is called by another function to execute is known
as called function.
Calling function: the function which calls another function to execute is known as
calling function.
Function Return statement
• It is the last statement of the function that return
certain values.
• It return certain types of values to the place from
where the function was invoked.
• Syntax:
– return(variable-name or constant);
• It Can be return any of C‟s data type:
• Char, int, float ,long………
• Examples:
– int func1(...) /* Returns a type int. */
– float func2(...) /* Returns a type float. */
– void func3(...) /* Returns nothing. */
CALLING A FUNCTION
• When a program calls a function, program
control is transferred to the called function. A
called function performs defined task and
when it is return statement is executed or when
its function-ending closing brace is reached, it
returns program control back to the main
program.
• To call a function, you simply need to pass the
required parameters along with function name,
and if function returns a value, then you can
store returned value. For example:
Code for calling a function
GLOBAL AND LOCAL VARIABLES
• Local variable:
– A local variable is a variable that is declared inside
a function.
– A local variable can only be used with in the
function where it is declared.
• Global variable:
– A global variable is a variable that is declared
outside all functions.
– A global variable can be used in all functions.
• See the following example( see the next slide )
GLOBAL AND LOCAL VARIABLES

• As you can see two


global variables are declared,
A and B.
These variables can be used
in main() and Add().
• The local variable
answer can only be used in
main().
• Example program for function
• In this program I take the max().This function takes two parameters num1 and num2 and
returns the maximum between the two:
Explanation about previous program
Example2:Finding cube of the function program
Types of Functions
• In ‘C’ language, functions are classified into two categories:
1.User-Defined functions :
• User defined functions are self-contained blocks of statements which are
written by the user to compute or perform a task.
• They can be called by the main program repeatedly as per the
requirement.
– Example: main() is user-defined functions
2. Library functions :
classification of User-defined Functions
User defined functions are 4 types those are:

1. Function with no arguments and no return value.


2. Function with no arguments and a return value.
3. Function with arguments and no return value.
4. Function with arguments and a return value.
Note:
• If the return data type of a function is “void”, then, it can’t
return any values to the calling function.
• If the return data type of the function is other than void such as
“int, float, double etc”, then, it can return values to the calling
function.
1.Function with no arguments and no return value
void add()
{
int i, int j;
i = 10; j = 20;
printf("Result : %d",i+j);
}
add();
2. Function with no arguments and a return value
int add()
{
int i, int j;
i = 10;
j = 20;
return i + j;
}
result = add();
3. Function with arguments and no return value
void add(int i, int j)
{
printf("%d",i+j);
}
sum(2,3);
4. Function with arguments and a return value.

int add(int i, int j)


{
return i + j;
}
int answer = add(2,3);
TYPE OF FUNCTION CALL
• While calling a function, the arguments can be
passed to a function in two ways those are:
CALL BY VALUE
• The call by value method of passing arguments to a
function copies the actual value of an argument into
the formal parameter of the function.
• In this case, changes made to the parameter inside
the function have no effect on the argument.
• By default, C programming language uses call by
value method to pass arguments. In general, this
means
• that code within a function cannot alter the
arguments used to call the function. Consider the
function swap() definition as follows.
CALL BY VALUE
• Consider the function swap() definition as follows.
Example program on Call by value
• Now, let us call the function swap() by passing actual values as in the
following example:

• The output shows that there is no


change in the values though they
had been changed inside the
function.
FUNCTION CALL BY REFERENCE
• The call by reference method of passing arguments to a
function copies the address of an argument into the
formal parameter.
• Inside the function, the address is used to access the
actual argument used in the call. This means that
changes made to the parameter affect the passed
argument.
• To pass the value by call by reference, argument pointers
are passed to the functions just like any other value.
• So accordingly you need to declare the function
parameters as pointer types as in the following function
swap(), which exchanges the values of the two integer
variables pointed to by its arguments.
• Call by reference shows that the
change has reflected outside of the
function as well unlike call by value
where changes does not reflect
outside of the function.
RECURSION

• 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 (or similar
approach) can be used where one branch makes the recursive
call and other doesn't.
Sum of Natural Numbers Using Recursion
Write a program to print factorial number.
Result:
input 5!=5*4*3*2*1*0!
5! 5!=5*4*3*2*1!
5!=5*4! 5!=5*4*3*2!*1
5!=5*4*3! 5!=5*4*3!*2
5!=5*4*3*2! 5!=5*4!*6
5!=5*4*3*2*1! 5!=5!*24
5!=5*4*3*2*1*0! 5!=120
String Handling Functions
• A string is a sequence of characters. Any sequence or set of
characters defined within double quotation symbols( “ ” ) is
a constant string.
• Strings are stored in memory as ASCII codes of characters
that make up the string appended with‘\0’(ASCII value of
null).
• Normally each character is stored in one byte, successive
characters are stored in successive bytes.
• The last character is the null character having ASCII value
zero.
Character A Z a z 1 9 space \0
ASCII Code 65 90 97 122 49 57 32 0
Declaration of character string.
• A string variable is declared as an array of characters.
• Syntax:
– char string_name[size];
• E.g. char name[20];
• When the compiler assigns a character string to a
character array, it automatically supplies a null
character (‘\0’) at the end of the string
• In the above code , The compiler takes care of
storing the ASCII codes of characters of the string
in the memory and also stores the null terminator
in the end.
• scanf statement has a draw back it just
terminates the statement as soon as it finds a
blank space, suppose if we type the string
‘’new york ‘’ then only the string new will be
read and since there is a blank space after
word “new” it will terminate the string.
• The function getchar/gets can be used
repeatedly to read a sequence of successive
single characters and store it in the array.
• We cannot manipulate strings, since C does not
provide any operators for string.
• For instance we cannot assign one string to
another directly.
For example:
String=”xyz”;
String1=string2;
• Are not valid. To copy the chars in one string
to
another string we may do on a character to
character basis.
Arithmetic operations on characters:
• We can also manipulate the characters as we manipulate
numbers in c language. When ever the system encounters
the character data it is automatically converted into a
integer value by the system. We can represent a character
as a interface by using the following method.
• X=’a’;
• printf(“%d\n”,x);
• Will display 97 on the screen. Arithmetic operations can
also be performed on characters for example x=’z’-1; is a
valid statement. The ASCII value of ‘z’ is 122, then the
statement will assign 121 to variable x.
Character manipulations (ctype.h)
String Functions & operations
Using string length
• The strlen function allows you to determine the length of
a string contained in an array. It returns an integer value,
which represents the length of the string contained in an
array.
Strings concatenation(join)
• The strcat string function allows you to
concatenate strings contained in an array. It
stores the second string after the first string in
an array.
String comparison

• The strcmp string function allows you to compare strings


contained in arrays. This function returns an integer value less
than 0 if the first string less than the second string.
Upper case lower case
Using string copy/ Appending
• The strcpy function allows you to copy a string
character by the character of one array into
another array.
String compares first n characters
• int strncmp(const char *str1, const char *str2, size_t n)
• size_t is for unassigned short
• It compares both the string till n characters or in other words it
compares first n characters of both the strings.

You might also like