Unit 4
Unit 4
3
When the program grows into larger,
may have many disadvantages.
They solved problems that could be understood without too much effort.
5
Top-down design is usually done using a visual representation of the
modules known as a structured chart.
Structure Chart
6
FUNCTIONS IN C
If any module has sub modules that is called as calling module and sub
modules are called modules.
the main function called by the operating system, in turn main function
calls the other function to do some task.
.
7
FUNCTIONS IN C
A function is a self-contained block of code that carries out some
specific and well-defined task.
8
FUNCTIONS IN C (contd…)
Library Functions:
These are the built in functions available in standard library of C.
Example:
abs (a) function gives the absolute value of a, available in <math.h>
9
FUNCTIONS IN C (contd…)
Example: main (), sum (), fact () , show(), display() and etc.,
Note:
In C, a program is made of one or more functions, one and only one of
which must be called main.
The execution of the program always starts with main, but it can call
other functions to do some part of the job. 10
Advantages of User-defined Functions
11
Structure Chart for a C Program
12
User-defined Functions
Like every other object in C, functions must be both declared and
defined.
13
The general form of a C user-defined function:
14
The general form of a C user-defined function
(contd…)
return-type:
Specifies the type of value that a function returns using the return
statement.
It can be any valid data type.
If no data type is specified the function is assumed to return an integer
result.
function-name:
Must follow same rules of variable names in C.
No two functions have the same name in a C program.
argument declaration:
It is a comma-separated list of variables that receive the values of the
argument when function is called.
If there is no argument declaration the bracket consists of keyword void.
15
User-defined Functions (Contd…)
Note: The prototype normally goes near the top of the program and must
appear before any call is made to the function.
16
User-defined Functions (Contd…)
17
User-defined Functions (Contd…)
User-defined Functions (Contd…)
The Function Call:
A function call is a postfix expression.
The operand in a function is the function name.
The operator is the parameter lists (…), which contain the actual
parameters.
Example:
void main ()
{
sum (a, b);
}
When the compiler encounters the function call ,the control is transferred
to the function sum().
The function is executed line by line and produces the output for the sum
of two numbers and then control is transferred back to the main function.18
User-defined Functions (Contd…)
Function Definition: The function definition contains the code for a
function.
Function Definition
20
User-defined Functions (Contd…)
void main()
{
fun1();
}
21
User-defined Functions (Contd…)
Any function can be called from any other function. Even main
can be called from other functions.
22
Each function is called in the sequence we have specified in the main function.
void fun1(); void fun2(); void fun3();
void main()
{
printf(“\n I am calling other functions”);
func1();
func2();
func3(); Output:
printf(“all functions are called\n”);
}//main I am calling other function
func1() in func1
{ in func2
in func3
printf(“in func1\n”);
all functions are called.
}//func1
func2()
{
printf(“in func2\n”);
}//func2
func3()
{
printf(“in func3\n”);
}//func3
After each function task is over the control passed to the calling function(main()).
7 One function can also call the other function which has already been called
void fun1(); void fun2(); void fun3();
void main()
{
printf(“I am in main\n”);
func1();
printf(“I back in main\n”);
}//main
void func1()
{
printf(“in func1\n”);
func2();
printf(“I back in func1\n”);
}//func1
void func2()
{
printf(“In func2\n”);
func3();
printf(“I back in func2\n”); }//func2
void func3()
{
printf(“in fun3\n”); }//func3
a function cannot be defined inside the other function.
main()
{
func1();
func2();
}//main
func1()
{
printf(“\nthis is func1”);
func2()
{
printf(“\nthis is func2”);
}//func2()
}//func1()
called function may or may not send information (data) back
to the calling function.
If called function return some value to the calling function at
the end of the function definition (before }) use return
statement.
void func1();
void main()
{
func1(); return; this statement says that does not return any
printf(“\nhai”); value. This may or may not used in void functions.
}//main
void func1() return(expression);- it return some value to the calling
{ function.
printf(“hello”);
return; Note- a function return only single value.
}//func1()
Categories of functions
Functions may belong to one of the following
categories.
1. functions with no arguments and no return value.
2. functions with no arguments and return value.
3. functions with arguments and no return value.
4. functions with arguments and return value.
1. functions with no arguments and no return value.
If the function has no arguments, it does not receive any
arguments/ parameters from the calling function.
It does not return any value to the calling function.
In this case, return type must be specified as void and put
empty parenthesis.
#include<stdio.h>
void msg()
void msg(); {
int main() printf(“learning c is easy”);
{ }
msg();
return 0;
}//main
#include <stdio.h>
void add(); // function declaration or
prototype
int main()
{
add(); // function call
return 0;
}
void add() // function definition
{
int a,b,c;
printf(“enter a, b values”);
scanf(“%d%d”, &a,&b);
c=a+b;
printf(“ a+b =%d”,c);
}
2.functions with no arguments and return value.
In which called function does not receive in arguments from
calling function. However, end of its task it return some value
to the calling function.
In this case, return value must be specified and parenthesis is
empty
#include<stdio.h>
char msg()
char msg(); {
int main() char ch;
{ printf(“enter character”);
char x; scanf(“%c”,&ch);
x=msg(); return ch;
printf(“%c”,x); }
return 0;
}//main
#include <stdio.h>
int add(); // function declaration
int main()
{
int x;
x=add(); // function call
printf(“addition=%d”,x);
return 0;
}
int add() // function definition
{
int a,b,c;
printf(“enter a, b values”);
scanf(“%d%d”, &a,&b);
c=a+b;
return c;
}
User-defined Functions (Contd…)
Generally, there are two ways that a function terminates execution and
returns to the caller.
When the last statement in the function has executed and conceptually
33
3. functions with arguments and no return value.
Called function receives arguments from the calling function and called
function doesn’t return any value to calling function.
In function prototype, we have to specifies no of arguments in the
parenthesis and specify return type as void.
In this category there is data transfer from the calling function to the
called function using parameters.
But, there is no data transfer from called function to the calling
function.
Local Variables:
Variables that are defined within a function are called local variables.
A local variable comes into existence when the function is entered and
is destroyed upon exit.
36
User-defined Functions (Contd…)
Functions with arguments and no return values (Contd…)
Actual Arguments/Parameters:
Actual parameters that are passed in function call are called actual
parameters
These are the parameters present in the calling function.
Actual parameters can be variables, constants or expressions.
Formal Arguments/Parameters:
Formal parameters are the variables that are declared in the header of
the function definition.
These are the parameters present in the called function
Formal parameters can be only variables,.
Note: Actual and Formal parameters must match exactly in type, order,
and number. Their names however, do not need to match.
37
4. functions with arguments and with return value.
Called function receives arguments from the calling function and called
function return any value to calling function.
In function prototype, we have to specifies no of arguments in the
parenthesis and specify return type .
Called function
#include <stdio.h>
void prime(int n)
{
int i,cn=0;
for(i=2;i<n;i++)
{
if(n%i==0)
cn++;
}
cn==0?printf("prime"):printf("not prime");
}
int main() {
int n;
printf("enter n");
scanf("%d",&n);
prime(n);
return 0;
Bidirectional Communication
In this strategy, both called and calling
function can send the data to each other.
Called
function
Calling
function
#include <stdio.h>
int prime( int n) {
int i,cn=0;
for(i=2;i<n;i++)
{
if(n%i==0)
cn++; }
return( cn==0?1: 0);
}
int main() {
int f,n;
printf("enter n");
scanf("%d",&n);
f=prime(n);
f==1?printf(“prime”):printf(“not prime”);
return 0;
}
Nesting of functions
C permits nesting of functions, main function can call function1,
function1 can call function2, which in turn calls function3 ..,
There is no limit as how deeply functions can be nested.
In the below example ,when the main() function finds the function call
sum(), then the control is transferred from main() to the function sum(),
there sum() is calling the function read(), then the control is transferred
to read() function, then the body of the function read() executes, then the
control is transferred back to sum(). Again read() function is invoked.
Observe the chain of control transfers between the nested functions.
48
#include<stdio.h> //Example program for nested-functions
int read ();
int sum (int, int);
int main ()
{
printf (“%d”, sum ());
return 0;
}
int sum (int x, int y)
{
x=read ();
y=read ();
return x + y;
}
int read ()
{
int p;
printf (“\n Enter any value: “);
scanf (“%d”, &p);
return p;
49
}
Standard Functions
C provides a rich collection of standard functions whose definitions
have been written and are ready to be used in our programs.
52
Absolute Functions:
An absolute value is the positive rendering of the values
regardless of its sign.
The integer functions are abs, labs, llabs.
Syntax:
int abs(int number);
long labs(long number);
long long llabs(long long number);
53
Ceil Function:
A ceil computes the nearest integer value which is greater than or equal
to a number.
Format of ceil function:
double ceil(double number);
float ceilf(float number);
long double ceill(long double number);
Example:
ceil(-1.9) gives -1.0
ceil(1.1) gives 2.0
Floor Function:
A floor computes the nearest integer value that is less than or equal to a
number.
Format of floor function:
double floor(double number);
float floorf(float number);
long double floorl(long double number);
Example:
floor(-1.1) gives -2.0 54
floor(1.9) gives 1.0
Ceiling Function
55
Floor Function
56
Truncate Function:
The truncate function return the integral in the direction of 0.
Format of trunc function:
double trunc(double number);
float truncf(float number);
long double truncl(long double number);
Example:
trunc(-1.1) gives -1.0
trunc(1.9) gives 1.0
Round Function:
The round function returns the nearest integral value.
Format of round function:
double round(double number);
float roundf(float number);
long double roundl(long double number);
Example:
round(-1.1) gives -1.0
round(1.9) gives 2.0
round(-1.5) gives -2.0 57
Power Function:
The power function returns the value of the x raised to the power y that
is xy.
Example:
pow(2,5) gives 32
Example:
sqrt(4.0) gives 2.0 58
Scope
59
Rules for Local Scope(Block Scope):
Variables are in scope from their point of declaration until the end of
the block.
They are visible in that block scope only. Outside the block they are
not visible.
60
//Example for local scope or block scope
{
int a = 2;
printf (“%d\n”, a); /* outer block a 2 is printed */
{
int a = 5;
printf (“%d\n”, a); /* inner block a 5 is printed */
}
printf (“%d\n”, a); /* 2 is printed */
}
/* a no longer defined */ Outer “a” Masked.
File scope generally includes all declarations outside function and all
function headers.
File scope includes the entire source file for a program, including any
files included in it.
An object with file scope has visibility through the whole source file
in which it is declared.
62
//Example program for global scope
void fun1();
void fun2();
int g=10;
void main()
{
g++;
printf(“main=%d”,g);
fun1();
printf(“back in main=%d”,g);
}
void fun1()
{
g=30;
printf(“fun1 = %d\n“,g);
fun2();
}
void fun2()
{
g++;
printf(“fun2=%d”,g);
}
63
//Example program for global scope
void fun1();
void fun2();
int count;
void main()
{
count = 100;
fun1();
}
void fun1()
{
printf("Count is = %d\n",count);
fun2();
} Output:
void fun2() Count is = 100
{ *****
int count;
for(count = 0;count < 5;count++)
printf("*");
} 64
Local Variables:
Global Variables:
Global variables are known throughout the entire program and may be
used in any piece of code.
Also, they will hold their values during the entire execution of the
program.
Global variables are created by declaring them outside of the function
and they can be accessed by any expression.
In general we are declaring global variable at the top of the program.
65
Rules for Function Scope:
66
Parameter Passing Techniques
Call-by-value
Call-by-reference
Call-by-value:
73
Recursion in C
In C, functions can call themselves .
The recursion step is done until the problem converges to become the
simplest case.
This simplest case will be solved by the function which will then
return the answer to the previous copy of the function.
The sequence of returns will then go all the way up until the original
call of the function finally return the result.
75
Example: Recursive Factorial Function
Iteration Definition:
Recursion Definition:
76
#include<stdio.h>
long factorial (long); /* function prototype */
void main (void)
{
long int n;
printf(“enter n”);
scanf(“%ld”,&n);
printf ("%ld! = %1d\n“,n, factorial (n)); /* function call */
}
long factorial (long n) /* function definition */
{
if (n = =0)
return 1;
else
return (n * factorial (n-1));
}
OUTPUT:
4! = 24
77
Designing a Recursive Function:
In the above program, once the base condition has reached, the solution begins.
The program has found one part of the answer and can return that part to the next
more general statement.
Thus, after calculating factorial (0) is 1, and then it returns 1.That leads to solve
the next general case,
factorial (1) 1*factorial (0) 1*1 1
The program now returns the value of factorial (1) to next general case,
factorial (2),
factorial (2) 2*factorial (1) 2*1 2
As the program solves each general case in turn, the program can solve the next
higher general case, until it finally solves the most general case, the original
problem.
Disadvantages:
80
Fibonacci using recursion Ackerman using recursion
#include<stdio.h>
int fib(int n);
void main()
{
int n,res;
printf(“enter n”);
scanf(“%d”,&n);
res=fib(n);
printf(“Nth Fibonacci term=%d”, res);
}
int fib(int n)
{
if (n==1)
return 0;
else if(n==2)
return 1;
else
return(fib(n-1)+fib(n-2));
}
Difference between Iteration and Recursion
ITERATION RECURSION
Iteration explicitly uses Recursion achieves repetition by
repetition structure. calling the same function repeatedly.
Iteration is terminated when Recursion is terminated when base
the loop condition fails case is satisfied.
May have infinite loop if the Recursion is infinite if there is no base
loop condition never fails case or if base case never reaches.
82
Storage classes in c
The storage class determines the part of member storage is allocated
for an object and how long the storage allocation continues to exit.
A scope specifies the part of the program which a variable name is
1. Variables must be declared with the key word static. static int x;
2. Storage- variable stored in computer memory.
3. Default initial value- zero.
4. Scope- local to the block in which they are declared.
5. Life –value of the variable persists between the different function calls.
6. Static automatic variables continue to exist even after the block in which
they are defined terminates. Thus, the value of a static variable in a
function is retained between repeated function calls to the same
function.
7. In the case of recursive function calls we use static storage class.
8. Static variables may be initialized in their declarations; however, the
initializes must be constant expressions, and initialization is done only
once at compile time when memory is allocated for the static variable.
9. Static and auto variables are differ in their life and initial value.
Difference between static and auto
Out put 1 1 1
Out put 1 2 3
4. External storage class
1. All variables we have seen so far have had limited scope (the
block in which they are declared) and limited lifetimes (as for
automatic variables).
2. These variables are declared with keyword extern as
extern int x; ( extern keyword may be omitted).
3. Storage- Memory.
4. Default initial value- zero.
5. Scope- as long as the programs execution.
6. Life- doesn’t come to an end.
7. External variables are declared outside the all the functions. So
that they are available to all the functions in a program.
int i; local variable has highest If any variable declared
void main() preference than global out side of the main is
{ variable so that local treated as extern variable/
printf(“%d”,i);->0 variable value gets printed. global variable.
add();--------1 If any variable declared
add();------2 extern int x=100; as global variable inside
sub();------1 void main() of the main that must be
sub();----0 { declared with key word
}//main() int x=200; extern and defined outside
add() printf(“x=%d”,x); of the main.
{ display();
i++; }// int x=20;
printf(“i=%d”i); display() void main()
}//add() { {
Sub() printf(“%d”,x); extern int y;
{ } printf(“%d %d”,x,y);
i--; }
printf(“i=%d”,i);
int y=20;
}//sub()
int var; -> declaration and definition
extern int var ; -> declaration
When we write extern some_data_type some_variable_name; no memory is
allocated
When an extern variable is initialized, then memory for this is allocated and it
extern but not defined later or the file in which the definition of the variable is
present is not included in the program
Example1: Example2: Example3:
extern int a; //declaration extern int a =10; extern int a; // declaration
void main() // declaration and void main()
{ defination {
printf("%d", a); void main()
} { printf("%d", a);
printf("%d", a); }
Output: error } int a=5; //defination
Output: 10
Output: 5
Uses of C Extern Variable
when a particular files need to access a variable from another file.
Create a global common variable that can be used in all files that are linked
together.
A C extern function is a global function that can be declared in a file and called
from another file.
Syntax: extern return_type function_name(parameter1,paremeter2,...);
there is no need to use the C extern keyword before a function because functions
are always handled as global by the compiler
umath.h Test.c
int IT=12; #include<stdio.h>
#define sqre(a) a*a #include "umath.h"
#define rect(x,y) x*y extern int IT;
void main()
int fact(int n)
{
{ printf("IT=%d\n",IT);
int i,f=1; printf("area of square=%d\n",sqre(5));
for(i=1;i<=n;i++) printf("fact=%d\n",fact(6));
f*=i; }
return f;
}
Save as 2dreadprint.c
#include<stdio.h> Add.c
void read(int x[][5],int r,int c)
{ #include<stdio.h>
int i,j; #include "2dreadprint.c"
printf("enter elements"); void main()
for(i=0;i<r;i++)
{ {
for(j=0;j<c;j++) int x[5][5],y[5][5],z[5][5],i,j;
scanf("%d",&x[i][j]);
read(x,3,3);
}
} read(y,3,3);
void print(int x[][5],int r,int c) for(i=0;i<3;i++)
{
{
int i,j;
printf("elements are:"); for(j=0;j<3;j++)
for(i=0;i<r;i++) z[i][j]=x[i][j]+y[i][j];
{
}
for(j=0;j<c;j++)
{ print(z,3,3);
printf("%3d",x[i][j]); }
}
printf("\n"); }
Macros
Preprocessor Commands:
The C compiler is made of two functional parts: a preprocessor and a
translator.
93
Symbolic Constants:
Macro definition without arguments is referred as a constant.
The body of the macro definition can be any constant value
including integer, float, double, character, or string.
However, character constants must be enclosed in single quotes and
string constants in double quotes.
Example:
#define PI 3.142
#define T ‘h’
#define AND && #include <stdio.h>
#define LESSTHAN < #define PI 3.1415
#define MES “Welcome to C” int main()
{
#include<stdio.h> #include <stdio.h> float r, a;
#define T ‘h’ #define L “hello” printf("Enter the radius: ");
int main() int main() scanf(“%f", &r);
{ { a=PI*r*r;
printf(“ %c", T); printf(L); printf("Area=%f",a);
return 0; return 0 ; return 0;
} } } 94
#include <stdio.h>
#include<stdio.h> #define P printf(“welcome”);\
#define L < printf(“Snist”);
int main() int main()
{ {
int a=10,b=5; printf(“start”);
if( a L b) P
printf(“ a is small”); return 0;
else }
printf(“b is small”);
return 0;
}
95
Macro Definition:
The name is called the macro name and the tokens are referred to as the
macro body.
96
Macro Definition (Cont…):
Macro must be coded on a single line.
97
1.We can also define macros that works like a function call
#include<stdio.h>
#define square(x) (x*x)
void main()
{
int a=10;
printf(“\nThe square of %d=%d”, a, square(a));
}
2.The macros can take function like arguments, the arguments are not
checked for data type.
#include<stdio.h>
#define max(x,y) x>y?x:y
void main()
{
int a,b;
float x,y;
printf(“enter a,b,x,y”);
scanf(“%d%d%x%y”,&a,&b,&x,&y);
printf(“\nmaxvalue=%d”, max(a,b));
printf(“\n max=%f”,max(x,y));
} 98
Nested Macros:
C handles nested macros by simply rescanning a line after macro
expansion.
For Example:
#define sqre(a) (a*a)
#define cube(a) (sqre(a)*a)
99
File Inclusion:
The first job of a preprocessor is file inclusion that is copying of one or
more files into programs.
The files are usually header files and external files containing functions
and data declarations.
General form is:
#include filename
2. #include “filename”
It is used to direct the preprocessor look for the files in the current
working directory and standard library.
100
//Example program to include user defined header file
#include<stdio.h>
#include “MyFile.h”
void main()
{
int a=10,b=20;
printf(“\n The sum=%d”, sum(a,b));
}
MyFile.h
#include<stdio.h>
OUTPUT: #define sum(x, y) (x+y)
The sum=30
101
Undefining Macros:
Once defined, a macro command cannot be redefined.
Example:
#define Val 30
…
#undef Val
#define Val 50
102
The Defined Operator:
The defined operator can be used only in a conditional compilation.
For Example:
#define Val 24
103
Conditional Compilation:
It allows us to control the compilation process by including or excluding
statements.
105
Conditional Compilation (Cont…):
Command Meaning
When expression is true, the code that follows is
#if expression
included for compilation.
#endif Terminates the conditional command.
#include<stdio.h>
#define val 1
void main()
{ Output:
#if !defined(number) The number = 100
#define number 100 The value of pi = 3.140000
#endif
#ifdef val
#define pi 3.14
#endif
printf(“\n The number = %d”,number);
printf(“\n The value of pi = %f”,pi);
}
107
Conditional Compilation (Cont…):
#include<stdio.h> #include<stdio.h>
void main() #define NUM 10
{ void main()
#ifdef max {
#define min 40 #if(NUM == 0)
#else printf("\nNumber is Zero");
#define min 100 #elif(NUM > 0)
#endif printf("\nNumber is Positive");
printf(“\n The number = %d”,min); #else
printf("\nNumber is Negative");
} #endif
}
108
Macro Function
Macro is Preprocessed Function is Compiled
No Type Checking Type Checking is Done
Code Length Increases Code Length remains Same
Speed of Execution is Faster Speed of Execution is Slower
Before Compilation macro name is During function call , Transfer of
replaced by macro value Control takes place
Useful where small code appears Useful where large code appears
many time many time
Generally Macros do not extend Function can be of any number of
beyond one line lines
Macro does not Check Compile Function Checks Compile Errors
Errors