cds -unit 3
TRANSCRIPT
-
8/3/2019 CDS -Unit 3
1/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
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 pass 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.
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 follows1. Library Functions (System defined functions)
I YEAR B.TECH MECH Page 1 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
2/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
2. User Defined FunctionsLibrary functions are prewritten and precompiled by the compiler vendor and come 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 voidas
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 voidin 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 declarations 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 integervalue. The functions take two
arguments of integer data types.
Example : void sum(void)
Here sum is function name and the function dont 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.
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 voidas function return type.
I YEAR B.TECH MECH Page 2 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
3/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
Function nameis 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 voidis 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 ynamed 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);
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.
I YEAR B.TECH MECH Page 3 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
4/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
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.
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
I YEAR B.TECH MECH Page 4 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
5/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
Functions are classified based on their return values and their parameter lists. Functions either return a value
or they dont. Functions that dont return a value are known as void functions. Functions may have parameters or they
dont. 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 */
#includevoid 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);
}
OutputEnter two numbers : 20 30
Sum = 50
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 */#include
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)
{
I YEAR B.TECH MECH Page 5 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
6/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
int z;
z=x+y;
printf("Sum = %d",z);
}
OutputEnter 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 */#include
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;
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 thecommunication between calling and called function is fully utilized.
/*Program to calculate sum of two numbers */#include
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);
I YEAR B.TECH MECH Page 6 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
7/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
getch();
}
int sum(int x, int y)
{
int z;
z=x+y;
return z;
}
Output
Enter two numbers : 12 13
Sum = 25
Inter Function Communication
Although calling and called functions are two different entities, they need to communicate to exchange data.
The data flow is classified into three strategies. They are
Downward Flow
Upward Flow
Bi-directional Flow
Downward Flow
In downward communication, the calling function sends data to the called function. No data flows in the
opposite direction. In this strategy, copies of the data items are passed from the calling function to the called function.
The called function may change the values passed, but the original values in the calling function remain unchanged.
C language uses pass-by-value mechanism to implement this communication. A variable is declared and
defined in the called function for each value to be received from the calling function. The calling function sends a copy
of each value to the called function; no data flows upward.
/* Program to demonstrate pass by value mechanism (or) downward communication */void downFun(int,int);
void main()
{
int a=10,b=20;
clrscr();
printf("Before Function : a = %d, b = %d",a,b);
fun(a,b);
printf("\nAfter Function : a = %d, b = %d",a,b);
}
void downFun(int x, int y)
{
printf("\nIn function before operation: x = %d, y = %d",x,y);
x = x * 10;
y = y * 10;
printf("\nIn function after operation: x = %d, y = %d ",x,y);
}
Output:Before Function : a= 10, b = 20
In function before operation : x = 10, y = 20
In function after operation : x = 100, y = 200
After Function : a = 10 , b = 20
Rules
I YEAR B.TECH MECH Page 7 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
8/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
Use values in the function call to pass data.
Use appropriate data types in the function parameter list to receive the data values.
Use the parameter identifiers in the called function to access the local copies of the data.
Upward Flow
Upward communication occurs when the called function sends data back to the called function with our
receiving any data from it. A good example is when the called function reads data from keyboard that needs to be
passed back to the called function.
C provides only one upward direction flow, i.e. return statement. While it works well, only one data item can be
returned. The only way that a called function can pass multiple data items up to the calling function is to access
variables in the calling function and deposit there. This is done by calling function by passing address of variable to
the called function.
Given the variables address, the called function can then put the data in the calling function. The calling
function needs to declare a data variable to receive the data. The called function needs to declare a variable to store
the address that it receives from the calling function.
In C, a variable can store data of different type. But here the called function needs a special variable which
stores the address of variable. It is called as pointer variable. To pass address of a variable, we use address
operator(&). To receive the address of variable we use asterisk(*) after the type. Asterick(*) is known as indirection
operator. The mechanism used for this communication is pass-by-reference mechanism.
/* Program to demonstrate the usage of upward communication*/void upFun(int*,int*);
void main()
{
int a,b;
clrscr();
fun(&a,&b);
printf("\nAfter Function : a = %d, b = %d",a,b);
}
void upFun(int *x, int *y)
{
*x = 28;
*y = 38;
printf("\nIn function after operation: *x = %d, *y = %d ",*x,*y);
}
Output:In function after operation : *x = 28, *y = 38
After Function : a = 28 , b = 38
Rules
Use &variableNamein the function call to pass a reference to the variable.
Use type*in the function parameter list to receive the variables address.
Use *parameterName in the function to reference the original variable.
I YEAR B.TECH MECH Page 8 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
9/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
Bi-directional Flow
Bi-directional communication occurs when the calling function sends data down to the called function. During
or at the end of its processing, the called function then sends data up to the calling function. For example, the calling
function may send data to the called function, which it manipulates and sends up the calling function.
The strategy used for upward direction can be augmented to allow the communications in both directions. The
only difference is that the indirect reference must be used in both sides of the assignment statement. The variable in
the called function first is accessed for retrieving using address variable in the right hand side. The same parameter is
accessed again to sore a vale in the left-hand side. The mechanism used for this communication is pass-by-reference.
/* Program to demonstrate the usage of birectional communication*/void biFun(int*,int*);
void main()
{
int a=10,b=20;
clrscr();
printf("Before Function : a = %d, b = %d",a,b);
biFun(&a,&b);
printf("\nAfter Function : a = %d, b = %d",a,b);
}
void biFun(int *x, int *y)
{
printf("\nIn function before operation: *x = %d, *y = %d",*x,*y);
*x = *x * 5;
*y = *y * 5;
printf("\nIn function after operation: *x = %d, *y = %d ",*x,*y);
}
Output:Before Function : a= 10, b = 20
In function before operation : *x = 50, *y = 100
In function after operation : *x = 50, *y = 100
After Function : a = 50 , b = 100
/* Program to exchange two numbers using functions*/void xChange(int*,int*);
void main()
{
int a,b;
clrscr();
printf("Enter two numbers :);
scanf(%d%d,&a,&b);printf(\nBefore Function : a = %d, b= %d,a,b);
xChange(&a,&b);
printf("\nAfter Function : a = %d, b = %d",a,b);
}
void xChange(int *x, int *y)
{
int temp;
printf("\nIn function before operation: *x = %d, *y = %d",*x,*y);
temp = *x;
*x = *y;
*y = temp;
printf("\nIn function after operation: *x = %d, *y = %d ",*x,*y);
}Output:
I YEAR B.TECH MECH Page 9 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
10/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
Enter two numbers : 44 55
Before Function : a = 44, b = 55
In function before operation : *x = 44, *y = 55
In function after operation : *x = 55, *y = 44
After Function : a = 55 , b = 44
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
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 n>0
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;
I YEAR B.TECH MECH Page 10 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
11/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
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
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
-
8/3/2019 CDS -Unit 3
12/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
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)
/* 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 %c\n,src,dest);
else{
towers(n-1, src, aux, dest);
printf(Move from %c to %c\n,src,dest);
towers(n-1, aux, dest, src);
}
}
OutputEnter 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 AMove 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
I YEAR B.TECH MECH Page 12 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
13/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
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
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.
Examplesceil(-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
I YEAR B.TECH MECH Page 13 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
14/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
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.
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
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
I YEAR B.TECH MECH Page 14 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
15/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
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 beingselected. 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 randcan 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 */#include
#include
#include
void main()
{int range;
srand(time(NULL));
range = (20 10) + 1;
printf(Random Numbers :%d\t, rand() % range + 10);
printf(%d\t, rand() % range + 10);
printf(%d, rand() % range + 10);
}
Output
Random Numbers : 10 11 16
-o0o-
I YEAR B.TECH MECH Page 15 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
16/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
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 objects 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 objects 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
Storage class specifiers control three attributes of an objects 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 for execution and destroyed when
execution stops.
An object with dynamic extent is created by the program through the mallocand its related library functions.
Linkage
I YEAR B.TECH MECH Page 16 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
17/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
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
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 autois 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("%d\n",i);
divert();
printf("%d\n",i);
getch();
}void divert()
{
int i=0;
i=i+2;
printf("%d\n",i);
}
Output
2
0
2
0
Register Variable
I YEAR B.TECH MECH Page 17 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
18/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
A variable with a registerspecification has the following characteristics
Scope = Block
Extent = Automatic
Linkage = Internal
By defining a variable as registerstorage 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 registerstorage class, the keyword autois used.
Syntax : register data_type variable_name;
Example : register int a;
/* Program to illustrate the usage of register variable */void main()
{
register int i;
clrscr();
for(i=1; i
-
8/3/2019 CDS -Unit 3
19/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
OutputThe 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
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 constis placed before the declaration. For a constpointer, 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 xis constant. The value that xpoints can be changed, but the value ofx cannot
be changed.
I YEAR B.TECH MECH Page 19 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
20/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
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.
Ex : volatile int x;
int * volatile z;
The variablexand pointer variable zcan be changed by any program at any time.
volatile const int y;
The variable ycan 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-
I YEAR B.TECH MECH Page 20 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
21/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
Preprocessor Directives
Preprocessing is one of the step involved in the process of compilation of C program. The preprocessor is a
program that processes the source program before it is passed on the compiler. The source code is given to
preprocessor that includes some directive definitions and then passes it to the compiler.
One of the most important features of C language is to offer preprocessing commands. The preprocessor
commands are always initialized at the beginning of the program. It begins with a symbol (#) hash. It can be placedanywhere quite often it is declared at the beginning before the main() function or any particular function.
The #define directive
This directive is used to define macro templates. The macro templates generally declared with capital letters
for quick identification. One can define macros with small letters.
Syntax : #define identifier
Example : #define MAX 50
In the above example, during preprocessing the preprocessor replaces every occurrence of MAX with 50. The macro
templates and its expansions must be separated by blank space. It is not necessary to provide space between # and
define. It is optional to programmer. The macro definition can be terminated with semi-colon and it is optional.
/*Program to demonstrate #define directive*/#define cls clrscr()
#define display printf
#define greater >
#define MAX 50
#define square(a) a*a
void main()
{
int a=5;
cls;if(a greater MAX)
display(%d is greater,a);
else
display(%d is greater,MAX);
display(\nSquare = %d,square(10));
}
Output50 is greater
Square = 100
The #undef directive
I YEAR B.TECH MECH Page 21 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
22/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
A macro defined with #define directives can be undefined with #undefdirective. It is useful when we do not
want to allow the use of macros in any portion of the program.
Syntax : #undef identifier
Example : #undef MAX
Stringizing Operators
In this operation macro argument is converted to the string. The sign # carries the operation. It is placed
before the argument.
/*Program to carry out stingizing operation*/#define say(m) printf(#m)
void main()
{
clrscr();
say(Hello);
}Output :Hello
In the above program, after conversion the statement say(Hello) is treated as printf(Hello). It is not essential to
enclose the text in quotation marks in the stringizing operator.
The #include directive
The #include directive loads specified file in the current program. The macros and functions of loaded file can
be called in the current program. The included is file is also compiled with the current program.
Syntax : #include (or) #include filename Examples : #include
#include string.h
Conditional Compilation directives
The most frequently used conditional compilation directives are #ifdef, #else, #endif, #ifndef etc. These
directives allow the programmer to include the portion o the codes based on the conditions. The compiler compiles
selected portion of the source code based on conditions.
Syntax : #ifdef
Statements;
#else
Statements;
#endif
The #ifdef preprocessor tests whether the identifier has defined substitute text or not. If the identifier is defined then #if
block is compiled and executed. The compiler ignores #else block even if errors are intentionally made. Error
messages will not be displayed.
The #ifndef preprocessor works exactly opposite to the #ifdef. The #ifndef preprocessor tests whether the
identifier has defined substitute text or not, if the identifier is defined then #else block is compiled and executed.
I YEAR B.TECH MECH Page 22 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
23/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
/*Program to demonstrate use of conditional compilation directives*/#define MAX 50
void main()
{
clrscr();
#ifdef MAX
printf(Max = %d,MAX);
#else
printf(MAX is not defined);
#endif
}
OutputMax = 50
The #error directive
The #error is used to display user defined message during compilation of program. The syntax is as follows
#error
The #line directive
The syntax of line directive is as follows
#line
It causes the compiler to imagine the number of the next source line as given by and gives the
current input file. If is absent, then current file name remains unchanged.
Example : #line 15 sample.c
Predefined Macros in ANSI and Turbo C
1) ANSI C predefined Macros
The list of pre-defined macros according to ANSI standard are as follows
Predefined Macros Function
_DATE_ Displays system data in string format
_TIME_ Displays system time in string format
_LINE_ Displays line number as integer
_FILE_ Displays current file name in string format
_STDC_ In ANSI C the value returned will be non-zero
There are five pre-defined macros and are always visible to the programmer for use. They can not be undefined.
Every macro name is defined with two underscores as prefix and suffix. The macros are useful for finding system
information such as date, time, file name and line number.
2) Turbo C predefined Macros
The pre-defined macros in Turbo C are listed in the table.
Predefined Macros Function
_TURBOC_ Displays current turboc version.
_PASCAL_ 1 if Calling convention pascal options
chosen, other wise undefined
_CDECL_ 1 if Calling convention .C option is chosen,
other wise undefined.
_MSDOS_ The integer constant 1.By setting option of code generation in option menu one can test next two macros.
I YEAR B.TECH MECH Page 23 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
24/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
3) Memory Model Macros
The following six macros are defined based on the memory models chosen by the user. There are six memory
models and only one is defined which is currently in use and remaining all are undefined.
Predefined Macros
_TINY_ _SMALL_
_MEDIUM_ _COMPACT_
_LARGE_ _HUGE_
Standard I/O Predefined Streams in stdio.h
The predefined streams automatically opens when the program is started. The following table describes their
macro expansion defined in stdio.h header file.
Macros Definition
stdin Standard Input Device
stdout Standard Output Device
stderr Standard error Output Device
stdaux Standard Auxiliary Device
stdprn Standard Printer
The Predefined Macro in ctype.h
The header file ctype.h contains a set of macros that checks character. The following table describes all the
macros. These macros take an argument of integer type and return an integer.
Macros Returns true(!0) value if
isalpha(d) d is a letter
isupper(d) d is a capital letter
islower(d) d is a small letter
isdigit(d) d is a digit
isalnum(d) d is a letter or digit
isxdigit(d) d is a hexadecimal digit
isspace(d) d is a space
ispunct(d) d is a punctuation symbol
isprint(d) d is a printable character
isgraph(d) d is printable, but not be a space
iscntrl(d) d is a control character
isascii(d) d is an ASCII code
-o0o-
Arrays
I YEAR B.TECH MECH Page 24 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
25/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
Array is a collection of similar data types in which each element is unique one and located in separate
memory locations.
Declaration of Array
data-type array-variable[size];
Ex : int a[10];
char ch[10];
float avg[10];
The first example tells to the compiler that a is an integer type of array and can store 5 integers. The compiler
reserves 2 bytes of memory for each integer array element. Total space of 10 bytes are allocated to variable a
Array Initialization
The array initialization is done is given below
int a[5] = {12, 14, 16, 17, 18};
Here 5 elements are stored in an array a. The array elements are stored sequentially in separate locations. Reading
of array elements begins from 0. Array elements are called by array names followed by the element numbers. The 5
elements are referred as
Subscripted variable a[0] refers to the first element of array a, 12 i.e. a[0]=12
Subscripted variable a[1] refers to the first element of array a, 14 i.e. a[1]=14
Subscripted variable a[2] refers to the first element of array a, 16 i.e. a[2]=16
Subscripted variable a[3] refers to the first element of array a, 17 i.e. a[3]=17
Subscripted variable a[4] refers to the first element of array a ,18 i.e. a[4]=18
If the array size is declared as 5. The elements are stored from index 0 to 4. i.e. If a[5] has been declared, then values
are stored from a[0] to a[4].
The integer enclosed in brackets is the array subscript, and its value must be in the range from zero to one
less than the number of memory cells in the array.
Sample Programs
1. /*Program to read an array of 10 numbers and print them */
void main(){
int a[10],i;
clrscr();
printf("Enter 10 values :");
for(i=0; i
-
8/3/2019 CDS -Unit 3
26/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
void main()
{
int a[10],i,sum=0;
float avg;
clrscr();
printf("Enter 6 subject marks :");
for(i=0; i
-
8/3/2019 CDS -Unit 3
27/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
We can pass individual elements by either passing their data values or by passing their addresses.
a) Passing Data Values
We can pass data values, that is individual array elements, just like we pass any data value. As long as the
array element type matches the function parameter type, it can be passed.
Example: void main(){
int arr[10];
---;
fun(arr[3]);
---;
}
void fun(int x)
{
Statements;
}
In the above example, only one element is passed by using the indexed expression arr[3]. Since the value of this
expression is integer, it matches the formal parameter type in the function.
b) Passing Addresses
We can use two-way communication by passing the address. We can pass the address of an individual
element in an array just like we can pass the address of any variable.
Example : void main(){
int arr[10];
----;
fun(&arr[3]);
-----;
}
void fun(int* x)
{
Statements;
}
To pass address of array element, we prefix the address operator to the elements indexed reference. Passing an
address of an array element requires two changes in the called function. First, it must declare that it is receiving an
address. Second, it must use the indirection operator (*) to refer to the elements value.
Passing the Whole Array
In C, the name of an array is a primary expression whose value is the address of the first element in the array.
Since indexed references are simply calculated addresses, all we need to refer to any of the elements in the array is
the address of the array. Because the name of the array is in fact its address, passing the array name, as opposed to
a single element, allows the called function to refer to the array back in the calling function.
Fixed length Arrays
To pass the whole array, we simply use the array name of the actual parameter. In the called function, we
declare that the corresponding formal parameter is an array. We do not need to specify the number of elements in
fixed-length array.
I YEAR B.TECH MECH Page 27 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
28/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
Example : void main(){
int arr[10];
----;
fun(arr);
-----;
}
void fun(int x[])
{
Statements;
}
The function declaration for an array can declare the array in two ways
1. First, it can use an array declaration with an empty set of brackets in the parameter list.
2. Second, it can specify that the array parameter as a pointer
Variable-length arrays
When the called function receives a variable-length array, we must declare and define it as variable length. In
a function declaration, we declare an array as variable using an asterisk for the array size or by using a variable for
the array size. In function definition, we must use the variable name, and following standard syntax rules, it must be
defined before the array.
Example : void main(){
int arr[size],size;
----;
fun(arr);
-----;
}
void fun(int x[*])
{
Statements;
}
Passing an Array as a Constant
When a function receives an array and doesnt change it, the array should be received as a constant array.
This prevents the function from accidentally changing the array. To declare an array as a constant, we prefix its type
with the type qualifierconst.
Example : double average(const int arr[], int size);
Rules to pass whole array to a function
1. The function must be called passing only the name of the array.
2. In the function definition, the formal parameter must be an array type, either fixed or variable.
3. The size of fixed-length array does not need to be specified.
4. The size of variable-length array in the function prototype must be asterisk or a variable.
5. The size of variable-length array in the function definition must be a variable that is in the functions scope, as
a previously specified variable parameter.
I YEAR B.TECH MECH Page 28 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
29/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
/*Program to calculate sum of array elements by passing entire array to function */int sum(int[],int);
void main()
{
int num,i,a[20],res=0;
printf("Enter a number :");
scanf("%d",&num);
printf("Enter %d elements :",num);
for(i=0; i
-
8/3/2019 CDS -Unit 3
30/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
Declaration:
int a[3][2];
Here 3 indicates the no. of rows and 2 indicates columns
Initialization:
int a[3][2] = { 21, 22, 23, 24, 25, 26};
The values are stored in the following pattern
Col0 Col1Row0 21 22
Row1 23 24
Row2 25 26
The values are represented as
a[0][0] = 21; a[0][1] = 22;a[1][0] = 23; a[1][0] = 24;
a[2][0] = 25; a[2][1] = 26;
The total number of elements in two dimensional array is product of no. of rows and no. of columns.
Example : int a [3][2] ; stores 3x2=6 values conceptually stored in matrix form.
/* Program to read elements of two-dimensional array and print them in matrix format*/void main()
{
int a[3][2],i,j;
clrscr();
printf("Enter elements of 3x2 matrix :");for(i=0; i
-
8/3/2019 CDS -Unit 3
31/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
/* Program to perform addition and subtraction of two matrices*/void main()
{
int a[3][2],b[3][2],c[3][2],d[3][2],i,j;
clrscr();
printf("Enter elements of 3x2 matrix A:");
for(i=0; i
-
8/3/2019 CDS -Unit 3
32/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
4 4
/* Program to perform multiplication of two matrices*/void main()
{
int a[3][2],b[2][3],c[3][3],i,j,k;
clrscr();
printf("Enter elements of 3x2 matrix A:");
for(i=0; i
-
8/3/2019 CDS -Unit 3
33/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
clrscr();
printf("Enter elements of 3x3 matrix :");
for(i=0; i
-
8/3/2019 CDS -Unit 3
34/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
Passing a row of an array means we pass a whole row by indexing the array name with only the row number.
When we pass the row, therefore, the function receives a one-dimensional aray.
Example : void main(){
int arr[3][2];
----;
fun(arr[1]);
}
void fun(int x[])
{
Statements;
}
Passing whole array
When we pass a two-dimensional array to a function, we use the array name as the actual parameter just as
we did with one-dimensional arrays. The formal parameter in the called function header, must indicate that the array
has two dimensions, To pass two dimensional arrays to functions
1. The function must be called by passing only the array name.
2. In the function definition, the formal parameter is a two-dimensional array, with the size of second dimension
required for a fixed-length array.
3. In the function definition for a variable length array, the size of all dimensions must be specified.
Example : void main(){
int arr[3][2];
----;
fun(arr);
}void fun(int x[][2])
{
Statements;
}
Multidimensional Arrays
Multidimensional arrays have three, four or more dimensions. The first dimension is called plane, which
consists of rows and columns. Arrays of four or more dimensions can be created and used, but difficult to draw.
Three-dimensional array can be defined as array of two-dimensional arrays. In other words, it is an array of
arrays of array.
Declaration:
int a[2][3][4];
Here2 indicates a plane consisting of 3 rows and 4 columns
Initialization
int a[2][3][4] = {
{
{0,1,2,3},
{4,5,6,7},
{8,9,10,11}
},{
I YEAR B.TECH MECH Page 34 N.Vamshi Krishna
-
8/3/2019 CDS -Unit 3
35/35
Computer Programming and Data Structures Unit III Vignana Bharathi Institute ofTechnology
{12,13,14,15},
{16,17,18,19},
{20,22,23,24}
}
};