SlideShare una empresa de Scribd logo
1 de 19
Descargar para leer sin conexión
Ramesh Bandaru Page 1
Functions
Top Down Design
When we consider larger programs, it is not possible to understand all aspects of such programs without
reducing them to smaller parts. The planning for large programs is as follows
• Understand the problems as a whole
• Break it into simpler, understandable parts.
• Solve individual parts and combine them.
Each part of a program is termed as module. The process of sub-dividing a problem into manageable
parts is called top-down design.
In top-down design, a program is divided into a main module and its related modules. Each module in
turn is divided into sub modules until the resulting modules are intrinsic; that is until they are implicitly
understood without further division. This process is known as factoring.
Top-down design is usually done using a visual representation of the modules known as a structure
chart. The structure chart shows the relation between each module and its sub-modules. The structure
chart is read top-down, left-right. The reading starts from main module followed by reading of sub-
modules of main from left to right.
The main module is called calling module because it has sub modules. The sub modules are known
as called modules. Communication between modules in a structure chart is allowed only through a
calling module. No communication takes place directly between modules that do not have a calling-called
relationship. The technique used to pas data to a function is known as parameter passing. The
parameters are contained in a list that is a definition of data passed to the function by the caller.
Functions in C
In C, idea of top-down is done using functions. A C program is made of one or more functions,
one and only one of which be called main. The execution of the program always starts with main, but it
can call other functions to do some part of job.
Definiton : A function is an independent module that will be called to do a specific task.
Advantages of functions:
1. Problem can be factored into understandable and manageable parts.
2. Provides a way to reuse code that is required in more than one place in a program.
Ramesh Bandaru Page 2
3. Used to protect data. Local data in function is available only to function when it is executing.
When the function is not running, the data are not accessible.
4. Improve the code efficiency and saves programming effort.
Functions mainly classified into two categories. They are as follows
1. Library Functions (System defined functions)
2. User Defined Functions
Library functions are prewritten and precompiled by the compiler vendor and comes along with
the compiler software as the library of functions. Ex. printf(), scanf(), clrscr() etc
The functions defined by the user are termed as user defined functions. There are three steps
involved in creating and using a user defined functions. They are
 Function Declaration
 Function Definition
 Function Call
Function Declaration
Function declarations consists only of a function header, they contain no code. The header
consists of three parts: the return type, the function name and the formal parameters list. The function
definition is terminated with a semi-colon.
The return type and parameter list are required entries. If the program has no return type, we
write void as function return type. Function name is user defined name just like any other C variable
name. If there are no parameters to a function, we can code void in parenthesis. If a function have
multiple parameters, we separate each type-identifier with commas. The C standard does not require
identifier names in a function declaration’s formal parameters.
Syntax : return_type function-name(formal_parameters_list);
Example : int sum(int a, int b); (or) int sum(int, int);
Here sum is function name and the function returns integer value. The functions
take two arguments of integer data types.
Example : void sum(void)
Here sum is function name and the function don’t return any value. The functions
have no parameters. So void is coded in parentheses.
The function declarations are placed in the global declaration section before main. Grouping all the
function declarations at the beginning of the program makes them available whenever they are needed.
Function declarations also provide an excellent quick reference for functions used in the program, making
them excellent documentation.
Ramesh Bandaru Page 3
Function Definition
In function definition, we write the actual lines of code required to accomplish the task assigned to
the function. It is made up of two parts: the function header and the function body.
The function header consists of return type, function name and formal parameter list. A semi
colon is not used at the end of the function header.
The return type specifies the data type of the value being returned by the function. If the program
has no return type, we write void as function return type.
Function name is user defined name just like any other C variable name. All rules of variables are
applicable for function name. The function name in function declaration statement and function definition
header need not to be same but the return type must be same.
The formal parameter list defines and declares the variables that will contain the data received by
the function. The parameter list is always required. If the function has no parameters – that is, if it does
not receive any data from the calling function, then void is coded in parentheses.
The function body is a compound statement i.e. it must have opening and closing braces. It
contains the local declarations and function statements. After function statements, a return statement can
be coded. If a function return type is void, it can be written without return statement.
Syntax : return-type function-name(formal-parameter-list)
{
// Local Declarations
//Lines of code;
}
Example: int sum(int x, int y)
{
int z;
z = x+y;
return z;
}
In the above example, sum is the function accepting two parameters int x, int y named as x, y of
integer data type. The function sum performs addition of two number and return the result value with help
of statement return z. As the function returns an integer value the data-type of function is given as int.
Function Call
Function call is a statement we use in your programs to invoke the services of the function. A
function call is a postfix expression. The operand in a function call is the function name; the operator is
the parentheses, which contain actual parameters. The actual parameters identify the values that are to
be sent to the called function. They match the functions formal parameters in type and order in the
parameter list. If there are multiple actual arguments, they are separated by commas.
Syntax : function-name(actual-parameters-list);
Ramesh Bandaru Page 4
Example sum(10,20);
Here we are calling the function named sum by passing two values 10  20
Note : There are many different ways to call a function.
Return Statement
A function may or may not send back any value to the calling function. If it does, it is done
through the return statement. While it is possible to pass any number of values to the called function, the
called function can return only a single value per call, at the most. A return statement terminates a
function. When there is no return statement at the end of function, the system inserts one with a void
return value.
Syntax : return expression.
Example : return 1; // 1 is a value
return z; // z is a variable
return (a+b); // (a+b) is an expression
Working of Function
Example:
void sum(int , int ); (Function Declaration)
int a,b; (Global Variable Declartion)
void main()
{
int num1, num2; (Local Variable Declaration)
-----;
sum(num1,num2); (Function Call)
-----;
}
void sum(int x,int y) (Function Definition)
{
------;
}
Calling Function : A function which makes call to another function is termed as calling function. In the
above example, main() is defined as calling function. i.e. it makes a call to function named sum().
Called Function : A called function receives control from a calling function. When the called function
completes it task, it returns control o the calling function. It may or may not return a value to the caller. In
the above example, sum() is defined as called function. This function is being called from main() function.
Actual Parameters : The actual parameters are the expressions in the calling statement. In the example
num1,num2 are actual parameters.
Formal Parameters : The variables that are declared in the header of the function definition are called
formal parameters. In the example x, y are called formal parameters.
Note : Formal and actual parameters must match exactly in type, order and he number. Their names,
however do not need to match.
Ramesh Bandaru Page 5
Local Variables : The local variables are defined inside a function and used without having any role in
the communication between functions. The variable defined is local to that function or block only. Other
functions can not access these variables. In the above example num1, num2 are local variables to the
function main(), x,y are local variables to the function sum().
Global Variables : The global variables are defined outside the main() function and used for
communication between functions. The global variables can be used by multiple functions in the program.
In the above example a,b are global variables.
Basic Function Designs
Functions are classified based on their return values and their parameter lists. Functions either
return a value or they don’t. Functions that don’t return a value are known as void functions. Functions
may have parameters or they don’t. Combining return types and parameter lists results in following four
basic designs.
1. void Functions without Parameters
2. void Functions with Parameters
3. Non-void Functions without Parameters
4. Non-void Functions with Parameters
1. void Functions without Parameters
Neither the data is passed through the calling function nor the data is sent back from the called
function. There is no data transfer between calling and the called functions. The function is only executed
and nothing is obtained.
/*Program to add sum of two numbers using functions */
#includestdio.h
void sum();
void main()
{
clrscr();
sum();
getch();
}
void sum(void)
{
int a,b,c;
printf(Enter two numbers :);
scanf(%d%d,a,b);
c=a+b;
printf(Sum = %d,c);
}
Output
Enter two numbers : 20 30
Sum = 50
Ramesh Bandaru Page 6
2. void Function with Parameters
Parameters are passed through the calling function. The called function operates in the
values. But no result is sent back. Such functions are partly dependent on calling function. The result
obtained is utilized by the called function and there is no gain to main().
/* Program to calculate sum to two numbers */
#includestdio.h
void sum(int,int);
void main()
{
int a,b,result;
clrscr();
printf(Enter two numbers :);
scanf(%d%d,a,b);
sum(a,b);
getch();
}
void sum(int x, int y)
{
int z;
z=x+y;
printf(Sum = %d,z);
}
Output
Enter two numbers : 12 13
Sum = 25
3. Non-void Functions without Parameters
No parameters are passed from the calling function, but the called function returns the
values. The called function is independent. It reads values from the keyboard or generates from
initialization and returns the value. Here both calling and called functions are partly communicated with
each other.
/* Program to calculate sum of two numbers */
#includestdio.h
int sum();
void main()
{
int result;
clrscr();
result = sum();
printf(Sum = %d,result);
getch();
}
int sum(void)
{
int a,b,c;
printf(Enter two numbers :);
scanf(%d%d,a,b);
c=a+b;
Ramesh Bandaru Page 7
return c;
}
Output
Enter two numbers : 20 32
Sum = 52
4. Non-void Functions with Parameters
The data is being sent from calling function to called function in terms of parameters. The
called function does the operations based on the data received and returns back the result to the calling
function. Here the communication between calling and called function is fully utilized.
/*Program to calculate sum of two numbers */
#includestdio.h
int sum(int,int);
void main()
{
int a,b,result;
clrscr();
printf(Enter two numbers :);
scanf(%d%d,a,b);
result = sum(a,b);
printf(Sum = %d,result);
getch();
}
int sum(int x, int y)
{
int z;
z=x+y;
return z;
}
Output
Enter two numbers : 12 13
Sum = 25
Recursion Function
Two approaches are used to write repetitive algorithms. One approach uses loops, the other uses
recursion. Recursion is a repetitive process in which a function calls itself. Some older languages like
COBOL do not support recursion.
A repetitive function is defined recursively whenever the function appears within the definition
itself. All recursive functions have two elements : each call either solves one part of the problem or it
reduces the size of the problem. The statement that solves the problem is known as base case. Every
recursive function must have a base case. The rest of function is known as the general case.
Rules for designing a Recursive Function
• First, determine the base case.
• Then, determine the general case.
• Finally combine the base case and general case into a function
Ramesh Bandaru Page 8
Limitations of Recursive Functions
• Recursion solutions involve extensive overhead because they use function calls.
• Each time we make a call, it uses some of memory allocation. If the recursion is deep, that is, if
the program has a large number of recursive calls, then we may run out of memory.
Examples
1. Factorial of a number
The factorial function can be defined recursively.
Factorial (n) = 1 if n=0
n * factorial (n-1) if n0
1./*Program to find factorial of a number using recursion function */
int fact(int);
void main()
{
int num,res;
clrscr();
printf(Enter a number :);
scanf(%d,num);
res = fact(num);
printf(Factorial = %d,res);
}
int fact(int n)
{
int f=1;
if(n==0)
return 1;
else
{
f = n * fact(n-1);
return f;
}
}
Output:
Enter a number : 5
Factorial = 120
In this example, the base case is return 1 statement. The general case is return f i.e. n* fact(n-1)
statement. In this problem, once the base case has been reached, the solution begins. The program has
found one part of the answer and can return that part to the next more general statement. As, the
program solves each general case, the program can solve the next higher general statements until it
finally solves the most general case, the original problem.
2. Fibonacci Series
The Fibonacci series for few numbers is as follows
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
The function of Fibonacci series is
Ramesh Bandaru Page 9
Given : Fibonacci0 = 0
Fibonacci1 = 1
Then : Fibonacci n = Fibonacci n-1 + Fibonacci n-2
/*Program to print Fibonacci series using recursion function */
int fib(int);
void main()
{
int n,i;
clrscr();
printf(Enter a number :);
scanf(%d,n);
for(i=0; i=n; i++)
printf(“%d”, fib(i));
}
int fib(int num)
{
if(num==0 || num==1)
return num;
else
return (fib(num-1)+ fib(num-2));
}
Output:
Enter a number : 8
Fibonacci Series : 0 1 1 2 3 5 8 13 21
3. Towers of Hanoi
According to legend, the monks in a remote monastery knew how to predict when the world
would end. They had a set of three diamond needles. Stacked on the first diamond needle were 64 gold
disks of decreasing size. The monks moved one disk to another needle each hour, subject to the
following rules
a) Only one disk could be moved at a time
b) A larger disk must never b stacked above a smaller one.
c) One and only one auxiliary needle could be used for the intermediate storage of disks.
Generalized solution for problem is
1) Move n-1 disks from source to auxiliary needle. (General Case)
2) Move one disk from source to destination needle. (Base Case)
3) Move n-1 disks from auxiliary to destination needle. (General Case)
Our solution requires four parameters : the number of disks to be moved, the source needle, the
destination needle, and the auxiliary needle. Using the above pseudo code, three moves are
1) Call Towers(n-1, source, auxiliary, destination)
2) Move one disk from source to destination
3) Call Towers(n-1, auxiliary, destination, source)
Ramesh Bandaru Page 10
/* Program to implement Towers of Hanoi using Recursion function*/
void towers(int, char, char, char);
void main()
{
int num;
clrscr();
printf(“Enter number of disks :”);
scanf(“%d”,num);
towers(num, ‘A’,’C’,’B’);
}
void towers(int n, char src, char dest, char aux)
{
if(n==1)
printf(“Move from %c to %cn”,src,dest);
else
{
towers(n-1, src, aux, dest);
printf(“Move from %c to %cn”,src,dest);
towers(n-1, aux, dest, src);
}
}
Output
Enter number of disks : 3
Move from A to C
Move from A to B
Move from C to B
Move from A to C
Move from B to A
Move from B to C
Move from A to C
Standard Library Functions
C provides a rich collection of standard functions whose definition have been written and are
ready to be used in our programs. To include functions, we must include their function declarations. The
function declarations for these functions are grouped together and collected in several header files.
Instead of adding individual function declarations of each function, we simply include the headers at the
top of our file.
Math Functions
Many important library functions are available for mathematical calculations. Most of the function
declarations for these functions are in either math header file (math.h) or standard library (stdlib.h). In
general, the integer functions are found in stdlib.h.
1) Absolute Value functions
An absolute value is the positive rendering of the value regardless of its sign. There are three
integer functions and three real functions.The integer functions are abs, labs, llabs. The real
functions are fabs, fabsf, fabsl. Examples are
abs(6) returns 6
Ramesh Bandaru Page 11
fabs(-3.4) returns 3.4
Function Prototype Library
int abs(int number); stdlib.h
long labs (long number); stdlib.h
long long llabs(long long number); stdlib.h
double fabs(double number); math.h
float fabsf(float number); math.h
long double fabsl(long double number); math.h
2) Ceiling Function
A ceiling is the smallest integral value greater than or equal to a number. Although the ceiling
functions determine an integral value, the return type is defined as a real value that corresponds to the
argument.
Examples
ceil(-1.9) returns 1.0
ceil(1.1) returns 2.0
Function Prototype Library
float ceilf(float number); math.h
double ceil(double number); math.h
long double ceill(long double number); math.h
3) Floor Functions
A floor is the largest integral value that is equal to or less than a number.
Examples
floor(-1.1) returns -2.0
floor(1.9) returns 1.0
Function Prototype Library
float floorf(float number); math.h
double floor(double number); math.h
long double floorl(long double number); math.h
4) Truncate Functions
The truncate functions returns the integral in the direction of 0. They are the same as floor
function for positive numbers and the same as ceiling function for negative numbers.
Ramesh Bandaru Page 12
Examples
trunc (-1.1)returns -1.0
trunc (1.9) returns 1.0
Function Prototype Library
float truncf(float number); math.h
double trunc(double number); math.h
long double truncl(long double number); math.h
5) Round Functions
The round functions return the nearest integral value.
Examples
round (-1.1)returns -1.0
round (1.9) returns 2.0
round(-1.5) returns -2.0
Function Prototype Library
float roundf(float number); math.h
double round(double number); math.h
long double roundl(long double number); math.h
long int lround(double number); stdlib.h
long int lroundf(float number); stdlib.h
long int lroundl(long double number); stdlib.h
long long int llround(double number); stdlib.h
long long int llroundf( float number); stdlib.h
long long int llroundl(long double number); stdlib.h
6) Power Function
The power function returns the value of the x raised to the power y i.e. x
y
. An error occurs if he
base is negative and the exponent is not an integer, or if the base is zero and the exponent in not
positive.
Examples
pow(3.0, 4.0) returns 81.0
pow(3.4, 2.3) returns 16.68893
Function Prototype Library
float powf(float n1, float n2); math.h
double pow(double n1, double n2); math.h
long double powl(long double n1, long double n2); math.h
Ramesh Bandaru Page 13
7) Square Root Function
The square root functions return the non-negative square root of a number. An error occurs if the
number is negative.
Examples
sqrt(25) returns 5.0
Function Prototype Library
float sqrtf(float number); math.h
double sqrt(double number); math.h
long double sqrtl(long double number); math.h
Random Numbers
A random number is a number selected from a set in which all members have the same
probability of being selected. Random numbers are useful in many areas of Computer Science. Two
examples are application testing and gaming.
C provides tow functions to build random number series. They are seed random (srand) and
random (rand) functions. These functions are found in stdlib.h
1)Seed Random Number Function
The seed random function creates the starting seed for a number series. The function declaration
is
void srand(unsigned int seed);
Examples
1) srand(997)
Generates the same number series in each run, we can either omit srand or we can
provide a constant seed random, preferably a prime number such as 997.
2) srand(time(NULL))
Generates the different series in each run, we use the time of day as seed. C call fo the
time which requires the time.h library.
2) Random Number Function
The random number function returns a pseudorandom integer between 0 and RAND_MAX, which
is defined in the standard library as the largest number that rand can generate. Each call generates the
next number in a random number series. The function declaration is
int rand(void);
Example rand();
/* Program to generate random numbers in range 10-20 */
#includestdio.h
Ramesh Bandaru Page 14
#includestdlib.h
#includetime.h
void main()
{
int range;
srand(time(NULL));
range = (20 – 10) + 1;
printf(“Random Numbers :%dt”, rand() % range + 10);
printf(“%dt”, rand() % range + 10);
printf(“%d”, rand() % range + 10);
}
Output
Random Numbers : 10 11 16
-o0o-
Storage Classes
Scope
Scope determines the region of the program in which a defined object is visible – that is, the part
of the program in which we can use the objects name. Scope pertains to any object that can be declared,
such as variable or a function declaration. Scope is a source program concept. It has no direct bearing on
run-time program.
Statements enclosed in the set of braces are called a block. A function body is enclosed in set of
braces, thus a body is also a block. An object’s scope extends from its declaration until the end of its
block. A variable is in scope if it is visible to the statement being examined. Variables are in scope from
their point of declaration until the end of block.
Global Scope
The scope of object defined in the global area of program is termed as global scope i.e. the
object’s scope is up to end of the program. Global scope variables are visible every where in the program.
Local Scope
Variables defined within a block have local scope. They exist only from the point of their
declaration until the end of the block (usually a function) in which they are declared. Outside the block
they are invisible.
Object Storage Attributes
Ramesh Bandaru Page 15
Storage class specifiers control three attributes of an object’s storage. They are scope, extent
and linkage.
Scope
Scope defines the visibility of an object; it defines where an object can be referenced. In C, an
object can have four levels of scope. They are block, file, function and function-prototype.
When scope of object is block, it is visible only in the block in which it is defined. When scope of
object is file, it is visible through the entire source file. When the scope of object is function, it is visible in
that function body in which it is declared.
Extent
The extent of an object defines the duration for which the computer allocates memory for it. The
extent of an object is also known as storage function. In C, an object can be automatic, static extent or
dynamic extent.
An object with an automatic scope is created each time its declaration is encountered and is
destroyed each time its block is exited.
An object with a static extent is created when the program is loaded fro execution and destroyed
when execution stops.
An object with dynamic extent is created by the program through the malloc and its related library
functions.
Linkage
A large application broken into modules, with each module potentially written by programmer in
separate source file with its own objects. Different modules ma be related when the program is link
edited. In C, linkage can be of two types: internal and external.
An object with an internal linkage is declared and visible in one module. Other modules refer to
this object. An object with an external linkage is declared in one module but is visible in all other modules
that declare it with a special keyword extern.
Storage Classes
Based on the object storage specifiers, C classifies four storage classes. They are auto, register,
static and extern storage classes.
Auto Variables
A variable with an auto specification has the following characteristics
Scope = Block
Extent = Automatic
Linkage = Internal
Ramesh Bandaru Page 16
By defining a variable as auto storage class, it is stored in the memory. The default value of the variable
will be garbage value. To define a variable as auto storage class, the keyword auto is used.
Syntax : auto data_type variable_name;
Example : auto int a;
Note : The keyword auto is not mandatory because the default storage class in C is auto.
/*Program to illustrate use of automatic storage class*/
void divert();
void main()
{
int i=0;
clrscr();
divert();
printf(%dn,i);
divert();
printf(%dn,i);
getch();
}
void divert()
{
int i=0;
i=i+2;
printf(%dn,i);
}
Output
2
0
2
0
Register Variable
A variable with a register specification has the following characteristics
Scope = Block
Extent = Automatic
Linkage = Internal
By defining a variable as register storage class, it is stored in the CPU register. The time required to
access a CPU register is significantly less than the time required to access a memory location. The
default value of the variable will be garbage value. To define a variable as register storage class, the
keyword auto is used.
Syntax : register data_type variable_name;
Example : register int a;
/* Program to illustrate the usage of register variable */
void main()
{
Ramesh Bandaru Page 17
register int i;
clrscr();
for(i=1; i=5; i++)
printf(%3d,i);
}
Output
1 2 3 4 5
Static Variables
A variable with a static specification has the following characteristics
Scope = Block (or) File
Extent = Static
Linkage = Internal
When a variable is declared as static, it is stored in memory. The default value of the variable will be zero.
A static variable can be initialized only once, it cannot be reinitialized. To define a variable as static
storage class, the keyword static is used.
Syntax : static data_type variable_name;
Example : static int a;
/*Program to illustrate the usage of static variables */
void divert();
void main()
{
clrscr();
divert();
printf(In main());
divert();
getch();
}
void divert()
{
static int i;
i = i+2;
printf(nThe static value in function = %d,i);
}
Output
The static value in function = 2
In main()
The static value in function = 4
Extern Variables
A variable with a extern specification has the following characteristics
Scope = File
Extent = Static
Linkage = Internal
Ramesh Bandaru Page 18
When a variable is declared as extern, it is stored in the memory. The default value is initialized to zero.
An extern variable is also called as global variable. To define a variable as extern storage class, the
keyword extern is used.
Syntax : extern data_type variable_name;
Example : extern int a;
/*Program to show the working of external variable */
extern int v=10;
void divert();
void main()
{
clrscr();
printf(In main() : %d,v);
divert();
getch();
}
void divert()
{
v=v+3;
printf(In divert() : %d,v);
}
Output :
In main() : 10
In divert() :13
Type Qualifiers
C provides three type qualifiers const, volatile and restrict. Const, volatile can be applied to any
variables, but restrict qualifiers may only applied to pointer.
Const Variable
A variable value can be made unchanged during program execution by declaring the variable as
constant. The keyword const is placed before the declaration. For a const pointer, place the keyword
between * and identifier.
Ex : const int a;
Here a is a constant and its value cannot be changed.
int * const x;
In the above example, the pointer to x is constant. The value that x points can be changed, but the value
of x cannot be changed.
Volatile Variable
Variables that can be changed at any time by external programs or the same program are called
volatile variables. The keyword volatile is placed before declaration. To make a variable value
changeable by the current program and unchangeable by other programs, declare the variable, declare it
as volatile and constant.
Ramesh Bandaru Page 19
Ex : volatile int x;
int * volatile z;
The variable x and pointer variable z can be changed by any program at any time.
volatile const int y;
The variable y can be changed by current program but not by external program.
Restrict Variable
The restrict type qualifier may only be applied to a pointer. A pointer declaration that uses this
type qualifier establishes a special association between the pointer and the object it accesses, making the
pointer and expressions based on that pointer, the only ways to directly or indirectly access the vale of
that object. The restrict type qualifier is an indication to the compiler that, if the memory addressed by the
restrict qualified pointer is modified, no other pointer will access that same memory.
Ex : int * restrict z;
-o0o-

Más contenido relacionado

La actualidad más candente

Algorithm Development
Algorithm DevelopmentAlgorithm Development
Algorithm DevelopmentALI RAZA
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CSowmya Jyothi
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in Crgnikate
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of ConstructorsDhrumil Panchal
 
10. switch case
10. switch case10. switch case
10. switch caseWay2itech
 
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)VC Infotech
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and typesimtiazalijoono
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#khush_boo31
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control StructureSokngim Sa
 
Fundamentals of algorithms
Fundamentals of algorithmsFundamentals of algorithms
Fundamentals of algorithmsAmit Kumar Rathi
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While LoopAbhishek Choksi
 

La actualidad más candente (20)

Algorithm Development
Algorithm DevelopmentAlgorithm Development
Algorithm Development
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
 
10. switch case
10. switch case10. switch case
10. switch case
 
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)
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
Procedural programming
Procedural programmingProcedural programming
Procedural programming
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
Function in C Language
Function in C Language Function in C Language
Function in C Language
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Fundamentals of algorithms
Fundamentals of algorithmsFundamentals of algorithms
Fundamentals of algorithms
 
C if else
C if elseC if else
C if else
 
Scope of variables
Scope of variablesScope of variables
Scope of variables
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
C tokens
C tokensC tokens
C tokens
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
 

Similar a Functions-Computer programming

Similar a Functions-Computer programming (20)

Functions assignment
Functions assignmentFunctions assignment
Functions assignment
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
 
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdfUSER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
C functions list
C functions listC functions list
C functions list
 
FUNCTION CPU
FUNCTION CPUFUNCTION CPU
FUNCTION CPU
 
Functions
Functions Functions
Functions
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Chapter 1.ppt
Chapter 1.pptChapter 1.ppt
Chapter 1.ppt
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
 
Amit user defined functions xi (2)
Amit  user defined functions xi (2)Amit  user defined functions xi (2)
Amit user defined functions xi (2)
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Functions in c language
Functions in c languageFunctions in c language
Functions in c language
 
unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdf
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
 
4. function
4. function4. function
4. function
 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 

Más de nmahi96

Matlab lab manual
Matlab lab manualMatlab lab manual
Matlab lab manualnmahi96
 
Heat transfer(HT) lab manual
Heat transfer(HT) lab manualHeat transfer(HT) lab manual
Heat transfer(HT) lab manualnmahi96
 
Personal Survival Techniques(PST)
Personal Survival Techniques(PST)Personal Survival Techniques(PST)
Personal Survival Techniques(PST)nmahi96
 
Personal Survival and Social Responsibilities(PSSR)
Personal Survival and Social Responsibilities(PSSR)Personal Survival and Social Responsibilities(PSSR)
Personal Survival and Social Responsibilities(PSSR)nmahi96
 
Fire prevention and Fire Fighting(FPFF)
Fire prevention and Fire Fighting(FPFF)Fire prevention and Fire Fighting(FPFF)
Fire prevention and Fire Fighting(FPFF)nmahi96
 
Elementary First Aid(EFA)
Elementary First Aid(EFA)Elementary First Aid(EFA)
Elementary First Aid(EFA)nmahi96
 
INERT GAS SYSTEM(IG)
INERT GAS SYSTEM(IG)INERT GAS SYSTEM(IG)
INERT GAS SYSTEM(IG)nmahi96
 
Practical Marine Electrical Knowledge 2ed 1999
Practical Marine Electrical Knowledge 2ed 1999Practical Marine Electrical Knowledge 2ed 1999
Practical Marine Electrical Knowledge 2ed 1999nmahi96
 
Graduate marine engineering(GME)important questions
Graduate marine engineering(GME)important questionsGraduate marine engineering(GME)important questions
Graduate marine engineering(GME)important questionsnmahi96
 
FEA intro patran_nastran
FEA intro patran_nastranFEA intro patran_nastran
FEA intro patran_nastrannmahi96
 
Ansys beam problem
Ansys beam problemAnsys beam problem
Ansys beam problemnmahi96
 
Screw thread measurement
Screw thread measurementScrew thread measurement
Screw thread measurementnmahi96
 
Optical measuring instruments
Optical measuring instrumentsOptical measuring instruments
Optical measuring instrumentsnmahi96
 
Tolerance and Fits
Tolerance and FitsTolerance and Fits
Tolerance and Fitsnmahi96
 
Ignition system
Ignition systemIgnition system
Ignition systemnmahi96
 
Clutch system
Clutch systemClutch system
Clutch systemnmahi96
 
Braking system
Braking systemBraking system
Braking systemnmahi96
 

Más de nmahi96 (20)

Matlab lab manual
Matlab lab manualMatlab lab manual
Matlab lab manual
 
Heat transfer(HT) lab manual
Heat transfer(HT) lab manualHeat transfer(HT) lab manual
Heat transfer(HT) lab manual
 
STSDSD
STSDSDSTSDSD
STSDSD
 
Personal Survival Techniques(PST)
Personal Survival Techniques(PST)Personal Survival Techniques(PST)
Personal Survival Techniques(PST)
 
Personal Survival and Social Responsibilities(PSSR)
Personal Survival and Social Responsibilities(PSSR)Personal Survival and Social Responsibilities(PSSR)
Personal Survival and Social Responsibilities(PSSR)
 
Fire prevention and Fire Fighting(FPFF)
Fire prevention and Fire Fighting(FPFF)Fire prevention and Fire Fighting(FPFF)
Fire prevention and Fire Fighting(FPFF)
 
Elementary First Aid(EFA)
Elementary First Aid(EFA)Elementary First Aid(EFA)
Elementary First Aid(EFA)
 
INERT GAS SYSTEM(IG)
INERT GAS SYSTEM(IG)INERT GAS SYSTEM(IG)
INERT GAS SYSTEM(IG)
 
Practical Marine Electrical Knowledge 2ed 1999
Practical Marine Electrical Knowledge 2ed 1999Practical Marine Electrical Knowledge 2ed 1999
Practical Marine Electrical Knowledge 2ed 1999
 
Sensors
SensorsSensors
Sensors
 
Graduate marine engineering(GME)important questions
Graduate marine engineering(GME)important questionsGraduate marine engineering(GME)important questions
Graduate marine engineering(GME)important questions
 
FEA intro patran_nastran
FEA intro patran_nastranFEA intro patran_nastran
FEA intro patran_nastran
 
Ansys beam problem
Ansys beam problemAnsys beam problem
Ansys beam problem
 
Ansys
Ansys Ansys
Ansys
 
Screw thread measurement
Screw thread measurementScrew thread measurement
Screw thread measurement
 
Optical measuring instruments
Optical measuring instrumentsOptical measuring instruments
Optical measuring instruments
 
Tolerance and Fits
Tolerance and FitsTolerance and Fits
Tolerance and Fits
 
Ignition system
Ignition systemIgnition system
Ignition system
 
Clutch system
Clutch systemClutch system
Clutch system
 
Braking system
Braking systemBraking system
Braking system
 

Último

Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdfKamal Acharya
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxMuhammadAsimMuhammad6
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxSCMS School of Architecture
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiessarkmank1
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdfKamal Acharya
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesRAJNEESHKUMAR341697
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilVinayVitekari
 
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEGEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEselvakumar948
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"mphochane1998
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 

Último (20)

Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech Civil
 
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEGEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 

Functions-Computer programming

  • 1. Ramesh Bandaru Page 1 Functions Top Down Design When we consider larger programs, it is not possible to understand all aspects of such programs without reducing them to smaller parts. The planning for large programs is as follows • Understand the problems as a whole • Break it into simpler, understandable parts. • Solve individual parts and combine them. Each part of a program is termed as module. The process of sub-dividing a problem into manageable parts is called top-down design. In top-down design, a program is divided into a main module and its related modules. Each module in turn is divided into sub modules until the resulting modules are intrinsic; that is until they are implicitly understood without further division. This process is known as factoring. Top-down design is usually done using a visual representation of the modules known as a structure chart. The structure chart shows the relation between each module and its sub-modules. The structure chart is read top-down, left-right. The reading starts from main module followed by reading of sub- modules of main from left to right. The main module is called calling module because it has sub modules. The sub modules are known as called modules. Communication between modules in a structure chart is allowed only through a calling module. No communication takes place directly between modules that do not have a calling-called relationship. The technique used to pas data to a function is known as parameter passing. The parameters are contained in a list that is a definition of data passed to the function by the caller. Functions in C In C, idea of top-down is done using functions. A C program is made of one or more functions, one and only one of which be called main. The execution of the program always starts with main, but it can call other functions to do some part of job. Definiton : A function is an independent module that will be called to do a specific task. Advantages of functions: 1. Problem can be factored into understandable and manageable parts. 2. Provides a way to reuse code that is required in more than one place in a program.
  • 2. Ramesh Bandaru Page 2 3. Used to protect data. Local data in function is available only to function when it is executing. When the function is not running, the data are not accessible. 4. Improve the code efficiency and saves programming effort. Functions mainly classified into two categories. They are as follows 1. Library Functions (System defined functions) 2. User Defined Functions Library functions are prewritten and precompiled by the compiler vendor and comes along with the compiler software as the library of functions. Ex. printf(), scanf(), clrscr() etc The functions defined by the user are termed as user defined functions. There are three steps involved in creating and using a user defined functions. They are Function Declaration Function Definition Function Call Function Declaration Function declarations consists only of a function header, they contain no code. The header consists of three parts: the return type, the function name and the formal parameters list. The function definition is terminated with a semi-colon. The return type and parameter list are required entries. If the program has no return type, we write void as function return type. Function name is user defined name just like any other C variable name. If there are no parameters to a function, we can code void in parenthesis. If a function have multiple parameters, we separate each type-identifier with commas. The C standard does not require identifier names in a function declaration’s formal parameters. Syntax : return_type function-name(formal_parameters_list); Example : int sum(int a, int b); (or) int sum(int, int); Here sum is function name and the function returns integer value. The functions take two arguments of integer data types. Example : void sum(void) Here sum is function name and the function don’t return any value. The functions have no parameters. So void is coded in parentheses. The function declarations are placed in the global declaration section before main. Grouping all the function declarations at the beginning of the program makes them available whenever they are needed. Function declarations also provide an excellent quick reference for functions used in the program, making them excellent documentation.
  • 3. Ramesh Bandaru Page 3 Function Definition In function definition, we write the actual lines of code required to accomplish the task assigned to the function. It is made up of two parts: the function header and the function body. The function header consists of return type, function name and formal parameter list. A semi colon is not used at the end of the function header. The return type specifies the data type of the value being returned by the function. If the program has no return type, we write void as function return type. Function name is user defined name just like any other C variable name. All rules of variables are applicable for function name. The function name in function declaration statement and function definition header need not to be same but the return type must be same. The formal parameter list defines and declares the variables that will contain the data received by the function. The parameter list is always required. If the function has no parameters – that is, if it does not receive any data from the calling function, then void is coded in parentheses. The function body is a compound statement i.e. it must have opening and closing braces. It contains the local declarations and function statements. After function statements, a return statement can be coded. If a function return type is void, it can be written without return statement. Syntax : return-type function-name(formal-parameter-list) { // Local Declarations //Lines of code; } Example: int sum(int x, int y) { int z; z = x+y; return z; } In the above example, sum is the function accepting two parameters int x, int y named as x, y of integer data type. The function sum performs addition of two number and return the result value with help of statement return z. As the function returns an integer value the data-type of function is given as int. Function Call Function call is a statement we use in your programs to invoke the services of the function. A function call is a postfix expression. The operand in a function call is the function name; the operator is the parentheses, which contain actual parameters. The actual parameters identify the values that are to be sent to the called function. They match the functions formal parameters in type and order in the parameter list. If there are multiple actual arguments, they are separated by commas. Syntax : function-name(actual-parameters-list);
  • 4. Ramesh Bandaru Page 4 Example sum(10,20); Here we are calling the function named sum by passing two values 10 20 Note : There are many different ways to call a function. Return Statement A function may or may not send back any value to the calling function. If it does, it is done through the return statement. While it is possible to pass any number of values to the called function, the called function can return only a single value per call, at the most. A return statement terminates a function. When there is no return statement at the end of function, the system inserts one with a void return value. Syntax : return expression. Example : return 1; // 1 is a value return z; // z is a variable return (a+b); // (a+b) is an expression Working of Function Example: void sum(int , int ); (Function Declaration) int a,b; (Global Variable Declartion) void main() { int num1, num2; (Local Variable Declaration) -----; sum(num1,num2); (Function Call) -----; } void sum(int x,int y) (Function Definition) { ------; } Calling Function : A function which makes call to another function is termed as calling function. In the above example, main() is defined as calling function. i.e. it makes a call to function named sum(). Called Function : A called function receives control from a calling function. When the called function completes it task, it returns control o the calling function. It may or may not return a value to the caller. In the above example, sum() is defined as called function. This function is being called from main() function. Actual Parameters : The actual parameters are the expressions in the calling statement. In the example num1,num2 are actual parameters. Formal Parameters : The variables that are declared in the header of the function definition are called formal parameters. In the example x, y are called formal parameters. Note : Formal and actual parameters must match exactly in type, order and he number. Their names, however do not need to match.
  • 5. Ramesh Bandaru Page 5 Local Variables : The local variables are defined inside a function and used without having any role in the communication between functions. The variable defined is local to that function or block only. Other functions can not access these variables. In the above example num1, num2 are local variables to the function main(), x,y are local variables to the function sum(). Global Variables : The global variables are defined outside the main() function and used for communication between functions. The global variables can be used by multiple functions in the program. In the above example a,b are global variables. Basic Function Designs Functions are classified based on their return values and their parameter lists. Functions either return a value or they don’t. Functions that don’t return a value are known as void functions. Functions may have parameters or they don’t. Combining return types and parameter lists results in following four basic designs. 1. void Functions without Parameters 2. void Functions with Parameters 3. Non-void Functions without Parameters 4. Non-void Functions with Parameters 1. void Functions without Parameters Neither the data is passed through the calling function nor the data is sent back from the called function. There is no data transfer between calling and the called functions. The function is only executed and nothing is obtained. /*Program to add sum of two numbers using functions */ #includestdio.h void sum(); void main() { clrscr(); sum(); getch(); } void sum(void) { int a,b,c; printf(Enter two numbers :); scanf(%d%d,a,b); c=a+b; printf(Sum = %d,c); } Output Enter two numbers : 20 30 Sum = 50
  • 6. Ramesh Bandaru Page 6 2. void Function with Parameters Parameters are passed through the calling function. The called function operates in the values. But no result is sent back. Such functions are partly dependent on calling function. The result obtained is utilized by the called function and there is no gain to main(). /* Program to calculate sum to two numbers */ #includestdio.h void sum(int,int); void main() { int a,b,result; clrscr(); printf(Enter two numbers :); scanf(%d%d,a,b); sum(a,b); getch(); } void sum(int x, int y) { int z; z=x+y; printf(Sum = %d,z); } Output Enter two numbers : 12 13 Sum = 25 3. Non-void Functions without Parameters No parameters are passed from the calling function, but the called function returns the values. The called function is independent. It reads values from the keyboard or generates from initialization and returns the value. Here both calling and called functions are partly communicated with each other. /* Program to calculate sum of two numbers */ #includestdio.h int sum(); void main() { int result; clrscr(); result = sum(); printf(Sum = %d,result); getch(); } int sum(void) { int a,b,c; printf(Enter two numbers :); scanf(%d%d,a,b); c=a+b;
  • 7. Ramesh Bandaru Page 7 return c; } Output Enter two numbers : 20 32 Sum = 52 4. Non-void Functions with Parameters The data is being sent from calling function to called function in terms of parameters. The called function does the operations based on the data received and returns back the result to the calling function. Here the communication between calling and called function is fully utilized. /*Program to calculate sum of two numbers */ #includestdio.h int sum(int,int); void main() { int a,b,result; clrscr(); printf(Enter two numbers :); scanf(%d%d,a,b); result = sum(a,b); printf(Sum = %d,result); getch(); } int sum(int x, int y) { int z; z=x+y; return z; } Output Enter two numbers : 12 13 Sum = 25 Recursion Function Two approaches are used to write repetitive algorithms. One approach uses loops, the other uses recursion. Recursion is a repetitive process in which a function calls itself. Some older languages like COBOL do not support recursion. A repetitive function is defined recursively whenever the function appears within the definition itself. All recursive functions have two elements : each call either solves one part of the problem or it reduces the size of the problem. The statement that solves the problem is known as base case. Every recursive function must have a base case. The rest of function is known as the general case. Rules for designing a Recursive Function • First, determine the base case. • Then, determine the general case. • Finally combine the base case and general case into a function
  • 8. Ramesh Bandaru Page 8 Limitations of Recursive Functions • Recursion solutions involve extensive overhead because they use function calls. • Each time we make a call, it uses some of memory allocation. If the recursion is deep, that is, if the program has a large number of recursive calls, then we may run out of memory. Examples 1. Factorial of a number The factorial function can be defined recursively. Factorial (n) = 1 if n=0 n * factorial (n-1) if n0 1./*Program to find factorial of a number using recursion function */ int fact(int); void main() { int num,res; clrscr(); printf(Enter a number :); scanf(%d,num); res = fact(num); printf(Factorial = %d,res); } int fact(int n) { int f=1; if(n==0) return 1; else { f = n * fact(n-1); return f; } } Output: Enter a number : 5 Factorial = 120 In this example, the base case is return 1 statement. The general case is return f i.e. n* fact(n-1) statement. In this problem, once the base case has been reached, the solution begins. The program has found one part of the answer and can return that part to the next more general statement. As, the program solves each general case, the program can solve the next higher general statements until it finally solves the most general case, the original problem. 2. Fibonacci Series The Fibonacci series for few numbers is as follows 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 The function of Fibonacci series is
  • 9. Ramesh Bandaru Page 9 Given : Fibonacci0 = 0 Fibonacci1 = 1 Then : Fibonacci n = Fibonacci n-1 + Fibonacci n-2 /*Program to print Fibonacci series using recursion function */ int fib(int); void main() { int n,i; clrscr(); printf(Enter a number :); scanf(%d,n); for(i=0; i=n; i++) printf(“%d”, fib(i)); } int fib(int num) { if(num==0 || num==1) return num; else return (fib(num-1)+ fib(num-2)); } Output: Enter a number : 8 Fibonacci Series : 0 1 1 2 3 5 8 13 21 3. Towers of Hanoi According to legend, the monks in a remote monastery knew how to predict when the world would end. They had a set of three diamond needles. Stacked on the first diamond needle were 64 gold disks of decreasing size. The monks moved one disk to another needle each hour, subject to the following rules a) Only one disk could be moved at a time b) A larger disk must never b stacked above a smaller one. c) One and only one auxiliary needle could be used for the intermediate storage of disks. Generalized solution for problem is 1) Move n-1 disks from source to auxiliary needle. (General Case) 2) Move one disk from source to destination needle. (Base Case) 3) Move n-1 disks from auxiliary to destination needle. (General Case) Our solution requires four parameters : the number of disks to be moved, the source needle, the destination needle, and the auxiliary needle. Using the above pseudo code, three moves are 1) Call Towers(n-1, source, auxiliary, destination) 2) Move one disk from source to destination 3) Call Towers(n-1, auxiliary, destination, source)
  • 10. Ramesh Bandaru Page 10 /* Program to implement Towers of Hanoi using Recursion function*/ void towers(int, char, char, char); void main() { int num; clrscr(); printf(“Enter number of disks :”); scanf(“%d”,num); towers(num, ‘A’,’C’,’B’); } void towers(int n, char src, char dest, char aux) { if(n==1) printf(“Move from %c to %cn”,src,dest); else { towers(n-1, src, aux, dest); printf(“Move from %c to %cn”,src,dest); towers(n-1, aux, dest, src); } } Output Enter number of disks : 3 Move from A to C Move from A to B Move from C to B Move from A to C Move from B to A Move from B to C Move from A to C Standard Library Functions C provides a rich collection of standard functions whose definition have been written and are ready to be used in our programs. To include functions, we must include their function declarations. The function declarations for these functions are grouped together and collected in several header files. Instead of adding individual function declarations of each function, we simply include the headers at the top of our file. Math Functions Many important library functions are available for mathematical calculations. Most of the function declarations for these functions are in either math header file (math.h) or standard library (stdlib.h). In general, the integer functions are found in stdlib.h. 1) Absolute Value functions An absolute value is the positive rendering of the value regardless of its sign. There are three integer functions and three real functions.The integer functions are abs, labs, llabs. The real functions are fabs, fabsf, fabsl. Examples are abs(6) returns 6
  • 11. Ramesh Bandaru Page 11 fabs(-3.4) returns 3.4 Function Prototype Library int abs(int number); stdlib.h long labs (long number); stdlib.h long long llabs(long long number); stdlib.h double fabs(double number); math.h float fabsf(float number); math.h long double fabsl(long double number); math.h 2) Ceiling Function A ceiling is the smallest integral value greater than or equal to a number. Although the ceiling functions determine an integral value, the return type is defined as a real value that corresponds to the argument. Examples ceil(-1.9) returns 1.0 ceil(1.1) returns 2.0 Function Prototype Library float ceilf(float number); math.h double ceil(double number); math.h long double ceill(long double number); math.h 3) Floor Functions A floor is the largest integral value that is equal to or less than a number. Examples floor(-1.1) returns -2.0 floor(1.9) returns 1.0 Function Prototype Library float floorf(float number); math.h double floor(double number); math.h long double floorl(long double number); math.h 4) Truncate Functions The truncate functions returns the integral in the direction of 0. They are the same as floor function for positive numbers and the same as ceiling function for negative numbers.
  • 12. Ramesh Bandaru Page 12 Examples trunc (-1.1)returns -1.0 trunc (1.9) returns 1.0 Function Prototype Library float truncf(float number); math.h double trunc(double number); math.h long double truncl(long double number); math.h 5) Round Functions The round functions return the nearest integral value. Examples round (-1.1)returns -1.0 round (1.9) returns 2.0 round(-1.5) returns -2.0 Function Prototype Library float roundf(float number); math.h double round(double number); math.h long double roundl(long double number); math.h long int lround(double number); stdlib.h long int lroundf(float number); stdlib.h long int lroundl(long double number); stdlib.h long long int llround(double number); stdlib.h long long int llroundf( float number); stdlib.h long long int llroundl(long double number); stdlib.h 6) Power Function The power function returns the value of the x raised to the power y i.e. x y . An error occurs if he base is negative and the exponent is not an integer, or if the base is zero and the exponent in not positive. Examples pow(3.0, 4.0) returns 81.0 pow(3.4, 2.3) returns 16.68893 Function Prototype Library float powf(float n1, float n2); math.h double pow(double n1, double n2); math.h long double powl(long double n1, long double n2); math.h
  • 13. Ramesh Bandaru Page 13 7) Square Root Function The square root functions return the non-negative square root of a number. An error occurs if the number is negative. Examples sqrt(25) returns 5.0 Function Prototype Library float sqrtf(float number); math.h double sqrt(double number); math.h long double sqrtl(long double number); math.h Random Numbers A random number is a number selected from a set in which all members have the same probability of being selected. Random numbers are useful in many areas of Computer Science. Two examples are application testing and gaming. C provides tow functions to build random number series. They are seed random (srand) and random (rand) functions. These functions are found in stdlib.h 1)Seed Random Number Function The seed random function creates the starting seed for a number series. The function declaration is void srand(unsigned int seed); Examples 1) srand(997) Generates the same number series in each run, we can either omit srand or we can provide a constant seed random, preferably a prime number such as 997. 2) srand(time(NULL)) Generates the different series in each run, we use the time of day as seed. C call fo the time which requires the time.h library. 2) Random Number Function The random number function returns a pseudorandom integer between 0 and RAND_MAX, which is defined in the standard library as the largest number that rand can generate. Each call generates the next number in a random number series. The function declaration is int rand(void); Example rand(); /* Program to generate random numbers in range 10-20 */ #includestdio.h
  • 14. Ramesh Bandaru Page 14 #includestdlib.h #includetime.h void main() { int range; srand(time(NULL)); range = (20 – 10) + 1; printf(“Random Numbers :%dt”, rand() % range + 10); printf(“%dt”, rand() % range + 10); printf(“%d”, rand() % range + 10); } Output Random Numbers : 10 11 16 -o0o- Storage Classes Scope Scope determines the region of the program in which a defined object is visible – that is, the part of the program in which we can use the objects name. Scope pertains to any object that can be declared, such as variable or a function declaration. Scope is a source program concept. It has no direct bearing on run-time program. Statements enclosed in the set of braces are called a block. A function body is enclosed in set of braces, thus a body is also a block. An object’s scope extends from its declaration until the end of its block. A variable is in scope if it is visible to the statement being examined. Variables are in scope from their point of declaration until the end of block. Global Scope The scope of object defined in the global area of program is termed as global scope i.e. the object’s scope is up to end of the program. Global scope variables are visible every where in the program. Local Scope Variables defined within a block have local scope. They exist only from the point of their declaration until the end of the block (usually a function) in which they are declared. Outside the block they are invisible. Object Storage Attributes
  • 15. Ramesh Bandaru Page 15 Storage class specifiers control three attributes of an object’s storage. They are scope, extent and linkage. Scope Scope defines the visibility of an object; it defines where an object can be referenced. In C, an object can have four levels of scope. They are block, file, function and function-prototype. When scope of object is block, it is visible only in the block in which it is defined. When scope of object is file, it is visible through the entire source file. When the scope of object is function, it is visible in that function body in which it is declared. Extent The extent of an object defines the duration for which the computer allocates memory for it. The extent of an object is also known as storage function. In C, an object can be automatic, static extent or dynamic extent. An object with an automatic scope is created each time its declaration is encountered and is destroyed each time its block is exited. An object with a static extent is created when the program is loaded fro execution and destroyed when execution stops. An object with dynamic extent is created by the program through the malloc and its related library functions. Linkage A large application broken into modules, with each module potentially written by programmer in separate source file with its own objects. Different modules ma be related when the program is link edited. In C, linkage can be of two types: internal and external. An object with an internal linkage is declared and visible in one module. Other modules refer to this object. An object with an external linkage is declared in one module but is visible in all other modules that declare it with a special keyword extern. Storage Classes Based on the object storage specifiers, C classifies four storage classes. They are auto, register, static and extern storage classes. Auto Variables A variable with an auto specification has the following characteristics Scope = Block Extent = Automatic Linkage = Internal
  • 16. Ramesh Bandaru Page 16 By defining a variable as auto storage class, it is stored in the memory. The default value of the variable will be garbage value. To define a variable as auto storage class, the keyword auto is used. Syntax : auto data_type variable_name; Example : auto int a; Note : The keyword auto is not mandatory because the default storage class in C is auto. /*Program to illustrate use of automatic storage class*/ void divert(); void main() { int i=0; clrscr(); divert(); printf(%dn,i); divert(); printf(%dn,i); getch(); } void divert() { int i=0; i=i+2; printf(%dn,i); } Output 2 0 2 0 Register Variable A variable with a register specification has the following characteristics Scope = Block Extent = Automatic Linkage = Internal By defining a variable as register storage class, it is stored in the CPU register. The time required to access a CPU register is significantly less than the time required to access a memory location. The default value of the variable will be garbage value. To define a variable as register storage class, the keyword auto is used. Syntax : register data_type variable_name; Example : register int a; /* Program to illustrate the usage of register variable */ void main() {
  • 17. Ramesh Bandaru Page 17 register int i; clrscr(); for(i=1; i=5; i++) printf(%3d,i); } Output 1 2 3 4 5 Static Variables A variable with a static specification has the following characteristics Scope = Block (or) File Extent = Static Linkage = Internal When a variable is declared as static, it is stored in memory. The default value of the variable will be zero. A static variable can be initialized only once, it cannot be reinitialized. To define a variable as static storage class, the keyword static is used. Syntax : static data_type variable_name; Example : static int a; /*Program to illustrate the usage of static variables */ void divert(); void main() { clrscr(); divert(); printf(In main()); divert(); getch(); } void divert() { static int i; i = i+2; printf(nThe static value in function = %d,i); } Output The static value in function = 2 In main() The static value in function = 4 Extern Variables A variable with a extern specification has the following characteristics Scope = File Extent = Static Linkage = Internal
  • 18. Ramesh Bandaru Page 18 When a variable is declared as extern, it is stored in the memory. The default value is initialized to zero. An extern variable is also called as global variable. To define a variable as extern storage class, the keyword extern is used. Syntax : extern data_type variable_name; Example : extern int a; /*Program to show the working of external variable */ extern int v=10; void divert(); void main() { clrscr(); printf(In main() : %d,v); divert(); getch(); } void divert() { v=v+3; printf(In divert() : %d,v); } Output : In main() : 10 In divert() :13 Type Qualifiers C provides three type qualifiers const, volatile and restrict. Const, volatile can be applied to any variables, but restrict qualifiers may only applied to pointer. Const Variable A variable value can be made unchanged during program execution by declaring the variable as constant. The keyword const is placed before the declaration. For a const pointer, place the keyword between * and identifier. Ex : const int a; Here a is a constant and its value cannot be changed. int * const x; In the above example, the pointer to x is constant. The value that x points can be changed, but the value of x cannot be changed. Volatile Variable Variables that can be changed at any time by external programs or the same program are called volatile variables. The keyword volatile is placed before declaration. To make a variable value changeable by the current program and unchangeable by other programs, declare the variable, declare it as volatile and constant.
  • 19. Ramesh Bandaru Page 19 Ex : volatile int x; int * volatile z; The variable x and pointer variable z can be changed by any program at any time. volatile const int y; The variable y can be changed by current program but not by external program. Restrict Variable The restrict type qualifier may only be applied to a pointer. A pointer declaration that uses this type qualifier establishes a special association between the pointer and the object it accesses, making the pointer and expressions based on that pointer, the only ways to directly or indirectly access the vale of that object. The restrict type qualifier is an indication to the compiler that, if the memory addressed by the restrict qualified pointer is modified, no other pointer will access that same memory. Ex : int * restrict z; -o0o-