0% found this document useful (0 votes)
37 views18 pages

Unit Iii

C programming

Uploaded by

chandram.ai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views18 pages

Unit Iii

C programming

Uploaded by

chandram.ai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 18

UNIT III

FUNCTIONS

Objective: Modular programming and recursive solution formulation FUNCTIONS-


MODULAR PROGRAMMING: functions, basics, parameter passing, storage classes
extern, auto, register, static, scope rules, block structure, user defined functions, standard
library functions, recursive functions, Recursive solutions for fibonacci series, towers of
Hanoi, header files, C Preprocessor, example c programs, Passing 1-D arrays, 2-D arrays to
functions.

SAMPLE QUESTIONS

1) What is function? Explain about function basics(function components)?


2) What are parameter parameter passing techniques(call-by-value and call-by-
referrence)?
3) Explain about storage classes ?
4) Explain about block structure and standard library functions ?
5) What is recursive function? Rules ?Advantages?Dis-advantages?Applications?
6) Explain about Fibonacci series?
7) Explain about Towers Of Hanoi?
8) Explain about header files?
9) Explain about C Preprocessor?
10) Explain about Passing 1-D arrays, 2-D arrays to functions?
Definition:- “ A block of statements is called function”. Function is also known as sub-
program or sub-routine.
Functions are of two types:
1) Built-in functions-------scanf( ),printf( ),sqrt( ),etc.
2) User-defined functions
i) void main( ) , ii) void swap( ) , etc.

{ {

} }

Advantages of functions:-

i) Divide the larger program into smaller programs.


ii) The memory is used in efficient way.
iii) Smalle functions are easier to coding the program.
iv) Duplicate code is removed
v) It can be used any no.of times by any no.of other programs.

Function components:-
Every function has the following components or elements associated with it.
i) Function prototype
ii) Function parameters
iii) Function call(calling function)
iv) Function definition(called function)
v) Return statement.
Example:
#include<stdio.h>
#include<conio.h>
void swap(int a,int b);
void main()
{
int a,b;
clrscr();
a=10;
b=20;
printf("Before swapping a =%d b=%d\n",a,b);
swap(a,b);
getch();
}
void swap(int a,int b)
{
a=a+b;
b=a-b;
a=a-b;
printf("After swapping a =%d b=%d",a,b);
}

Categories of functions:-

Functions are classified in three types, Depending on whether the arguments are present or
not and Whether a value is returned or not.

Type-1:-function with no arguments and no return value.

Type-2:-function with arguments and no return value.

Type-3:-function with arguments and return value.

These are explained in diagrammatical way as follows:

Type-1:

Type-2:
Type-3:

Parameter passing:-

i) Parameter passing is a technique of data communication between calling function


and called function.
ii) Parameters are passed from calling function to called function.
iii) The function with semi-colon( ; ) or without body is called calling function. The
function with with body is called called function.
iv) Calling function parameters(arguments) are called as Actual parameters. Called
function parameters(arguments) are called as Formal parameters.
Parameter passing techniques are:
1) Call-by-value and
2) Call-by-reference(call-by-address).

1) Call-by-value:- It means the values are passed from calling function to called
function.
Example :-

swap(a,b);

void swap(int a,int b)

}
Write a C program to explain the concept of call-by-value(swapping of two
numbers).

#include<stdio.h>
#include<conio.h>
void swap(int a,int b);
void main()
{
int a,b;
clrscr();
a=10;
b=20;
printf("Before swapping a =%d b=%d\n",a,b);
swap(a,b);
getch();
}
void swap(int a,int b)
{
a=a+b;
b=a-b;
a=a-b;
printf("After swapping a =%d b=%d",a,b);
}

Output:-
Before swapping a =10 b=20
After swapping a =20 b=10

2) Call-by-reference(call-by-addresses):- It means the addresses are passed from


calling function to called function.

Example :- swap(&a,&b);

void swap(int *a,int *b)

Write a C program to explain the concept of call-by-referrence(swapping of two


numbers).
#include<stdio.h>
#include<conio.h>
void swap(int *x,int *y);
void main()
{
int a,b;
clrscr();
a=10;
b=20;
printf("Before swapping a =%d b=%d\n",a,b);
swap(&a,&b);
getch();
}
void swap(int *x,int *y)
{
*x=*x+*y;
*y=*x-*y;
*x=*x-*y;
printf("After swapping a =%d b=%d",*x,*y);
}
Output:-
Before swapping a =10 b=20
After swapping a =20 b=10

Storage classes:

Automatic External Static Register


Keyword auto extern static register

Type `local `global `local `local

Default-value garbage Zero zero garbage


Storage Main memory Main memory Main memory register

Where declared With-in function Outside of With-in function With-in function or


or block. functions or block. block.

scope With-in function All files With-in function With-in function or


or block. or block. block.

Life time End of function or Termintation of End of main With-in function or


block program function block.

Syntax auto datatype var; exten datatype var; statc datatype var; register datatype var;

Example auto int a; extern int a; static int a; register int a;

Write a C program to explain storage classes.


#include<stdio.h>
#include<conio.h>
extern int a=10;
void display();
void main()
{
register int d=20;
clrscr();
printf("a =%d d=%d\n",a,d);
display();
display();
getch();
}

void display()
{
int b=5;
static int c=5;
b--;
c--;
printf("b=%d c=%d\n",b,c);
}
Output:- a =10 d=20
b=4 c=4
b=4 c=3
Block structure:-
The block structure indicates the scope of the variable.

Example:-

The variable ‘c’ is available to only block 1 and ‘a’ is available to block2 and block1.
Write a C program to explain block structure.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a=10;
clrscr();

{
int b=20,sum;
sum=a+b;
printf("sum is: %d",sum);
}
getch();
}
Output:- sum is : 30

Array and functions:


i) Passing One-dimensional arrays as arguments to functions.
ii) Passing Two-dimensional arrays as arguments to functions.

i) Passing One-dimensional arrays as arguments to functions.:-

Syntax:- return-type function-name(data-type,array-name[ ],int size)


{

Example:- display(A,n);

void display(int A[],int n)


{

}
In the above example we can say that the called function has two parameters:
a) Array name with data-type and
b) No .of elements of the array being passed.
Write a C program to display the 1 D array elements.
#include<stdio.h>
#include<conio.h>
void display(int A[],int n);
void main()
{
int A[10],i,n;
clrscr();
printf("Enter n value:\n");
scanf("%d",&n);
printf("Enter values into matrix A:\n");

for(i=0;i<n;i++)
{
scanf("%d",&A[i]);
}
display(A,n);
getch();
}
void display(int A[],int n)
{
int i;
printf(“values of matrix A are:\n”);
for(i=0;i<n;i++)
{
printf("%d ",A[i]);
}
}
Output:-
Enter n value:
4
Enter values into matrix A:
1234
values of matrix A are:
1 234

ii) Passing Two-dimensional arrays as arguments to functions.:-

Syntax:- return-type function-name(data-type,array-name[ ][size] ,


Int rowsize , int colsize)
{

Example:- display(A,m,n);

void display(int A[][10],int m, int n)


{

In the above example we can say that the called function has three parameters:
a) Array name with constant value in the second square of brackets.
b) Row size and
c) Column size.
Write a C program to display the 1 D array elements.
#include<stdio.h>
#include<conio.h>
void display(int A[][10],int m,int n);
void main()
{
int A[10][10],m,n,i,j;
clrscr();
printf("Enter m and n values:\n");
scanf("%d%d",&m,&n);
printf("Enter values into matrix A:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{

scanf("%d",&A[i][j]);
}
}
display(A,m,n);
getch();
}
void display(int A[][10],int m,int n)
{
int i,j;
printf(" Values of matrix A are:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{

printf("%d",A[i][j]);
}
printf("\n");
}
}

Standard library functions and Header files:

Library functions in C language are inbuilt functions which are grouped together and
placed in a common place called library. Now a list of the most common libraries and a
brief description of the most useful functions they contain follows:

1. stdio.h: I/O functions:


a. getchar() returns the next character typed on the keyboard.
b. putchar() outputs a single character to the screen.
c. printf() for printing a statement.
d. scanf() for getting a value.
2. string.h: String functions
a. strcat() concatenates a copy of str2 to str1
b. strcmp() compares two strings
c. strcpy() copys contents of str2 to str1
1. ctype.h: Character functions
a. isdigit() returns 1 if arg is digit 0 to 9
b. isalpha() returns non-0 if arg is a letter of the alphabet
c. isalnum() returns non-0 if arg is a letter or digit
d. islower() returns non-0 if arg is lowercase letter
e. isupper() returns non-0 if arg is uppercase letter
1. math.h: Mathematics functions
a. acos() returns arc cosine of arg
b. asin() returns arc sine of arg
c. atan() returns arc tangent of arg
d. cos() returns cosine of arg
e. exp() returns natural logarithim e
f. fabs() returns absolute value of num
g. sqrt() returns square root of num
1. time.h: Time and Date functions
a. time() returns current calender time of system
b. difftime() returns difference in secs between two times
c. clock() returns number of system clock cycles since program execution
1. stdlib.h:Miscellaneous functions
a. malloc() provides dynamic memory allocation, covered in future sections
b. rand() as already described previously
c. srand() used to set the starting point for rand()

Write a C program to implement the library functions and header files concept.
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<ctype.h>
void main()
output:
{
Square root of x is :3.000000
float x=9.0,y=9.43;
Ceil of y is:10.000000
char ch='a';
a is lower case letter
clrscr();
printf("Square root of x is : %f\n",sqrt(x));
printf("Ceil of y is: %f\n",ceil(y));
if(isupper(ch))
{
printf("%c is upper case letter",ch);
}
else
{
printf("%c is lower case letter",ch);
}
getch();
}
C Preprocessor

Pre-processor is the program which expands the source program. That means it attach the
header files code to the given program. Finally the expanded source program is submitted to
the C compiler.

All pre-processor directives should follow the given rules:


i) All pre-processor directives should begin with the symbol #.
ii) Only one directive should be in a line.
iii) The directives do not require the semi-colon(;) at the end.

Pre-processor directives are classified into 3 types:


A) File inclusion directives(#include)
B) Macro substitution directives(#define,#undefine) and
C) Compiler control directives (#ifdef, # endif,#if,#else).

A) File inclusion directives(#include):- It is used for attaching(including) the files.


Syntax:-
#include “ filename” (or)
#include<filename>
Example:-
#include “ stdio.h” (or)
#include<stdio.h>

B)Macro substitution directives(#define,#undefine) :-


It is used to assign a value to the name.
Syntax:-
#define identifier value
Example:-
#define pi 3.14

C) Compiler control directives (#if def, # end if,#if,#else):-


It is also called as conditional compilation directives.
 #ifdef----#endif directives:
#ifdef <identifier>
{

}#endif

 #ifdef----#else----#end if directives:
#ifdef <identifier>
{

}
#else
{

}
#endif
Write a C program to explain the pre-processor directives(finding the area of a circle
and sum of two numbers).
#include<stdio.h>
#include<conio.h>
#define pi 3.14
#define sum
void main()
{
int r=5,x=10,y=20,z;
float area;
clrscr();
area=pi*r*r;
#ifdef sum
z=x+y;
#else
z=x-y;
#endif
printf("Area of circle = %f\n",area);
printf("sum =%d",z);
getch();
}
Output:
Area of circle =78.500000
Sum=30
Recursive functions
 Definition:- “ The function which calls itself is called recursive function”.
 Recursive functions are classified into two types:
i) Direct recursive (function calls directly)
ii) In-direct recursive (function calls indirectly)
 The following are the conditions(criteria ) of recursive function:
a) Base criteria and
b) Recursive criteria.
 The recursive function which satisfies the above two criteria is called well-defined
recursive function.
Rules for recursive function:-
i) Function should be called itself otherwise recursion does not takes place.
ii) Only user-defined functions are involved in the recursion but not pre-defined.
iii) To stop the recursion, the function should met the base criteria.
iv) It needs the stack memory for implementing the recursion.

Advantages of recursion:-

i) It is very flexible in data structures like stacks, ques , linked lists and trees.
ii) Using recursion, the length of the program is reduced.

Disadvantages of recursion:-

i) It requires extra storage space(memory).


ii) Whenever there is no exit condition then program will be executed out of memory
and takes into infinite calls.
iii) It takes more time and less speed for execution.

The following are the applications(example problems ) of recursion:

i) Towers of Hanoi and


ii) Fibonacci sequence(Fibonacci series) .
Towers of Hanoi
1) In Towers of Hanoi game, there are three towers namely tower1 , tower2 and
tower3.
2) The game starts with ‘n’ number of disks on tower1 and ends with the same
‘n’ number of disks on tower3 in same order as in tower1.
3) Consider the initial step of Towers of Hanoi with 3 disks(n=3).

4) Consider the final step of Towers of Hanoi with 3 disks(n=3).

Rules of Towers of Hanoi:-

a) Only one disk can be moved at a time.


b) Only the top disk on any tower can be moved to any other tower.
c) Larger disk cannot be placed on smaller disk.

Example:- consider n=3, where ‘n’ is the number of disks.

The following are the seven minimum number of moves takes place to win the game TOH.

i) Move disk1 from tower1 to tower3


ii) Move disk 2from tower1 to tower2
iii) Move disk1 from tower3 to tower 2
iv) Move disk3 from tower1 to tower 3
v) Move disk1 from tower2 to tower 1
vi) Move disk 2from tower2 to tower 3
vii) Move disk1 from tower1 to tower 3
Write a C program to implement Tower of Hanoi using recursion.
#include<stdio.h>
#include<conio.h>
void toh(int n,char *t1,char *t2, char *t3);
void main()
{
int n;
clrscr();
printf("Enter the number of disks:\n");
scanf("%d",&n);
toh(n,"tower1","tower2","tower3");
getch();
}
void toh(int n,char *t1,char *t2, char *t3)
{
if(n==1)
{
printf("Move disk1 from %s to %s \n",t1,t3);
}
else
{
toh(n-1,t1,t3,t2);
printf("Move disk %d from %s to %s \n",n,t1,t3);
toh(n-1,t2,t1,t3);
}
}

Output:-
Move disk1 from tower1 to tower3
Move disk 2from tower1 to tower2
Move disk1 from tower3 to tower 2
Move disk3 from tower1 to tower 3
Move disk1 from tower2 to tower 1
Move disk 2from tower2 to tower 3
Move disk1 from tower1 to tower 3
Fibonacci sequence
Def:- “The sequence which starts with 0,1 and successive elements are obtained by summing
the preceding two numbers “ is called Fibonacci sequence.

0 1 1 2 3 5 8 13 21 34 etc

The recursive function for Fibonacci sequence is:


fib(n)=n; if n=0 or n=1------base criteria
fib(n)=fib(n-1)+ib(n-2); if n>=2-----recursive criteria
Example:-
fib(0)=0
fib(1)=1
fib(2)=fib(1)+fib(0)=1+0=1
fib(3)=fib(2)+fib(1)=1+1=2
fib(4)=fib(3)+fib(2)=2+1=3
----------------------------------
----------------------------------

0 1 1 2 3 -----------------------

Write a C program to generate the Fibonacci sequence using recursion.

#include<stdio.h>
#include<conio.h>
int fibonacci(int n);
void main()
{
int n,fibno,i;
clrscr();
printf(" Enter number of elements to be generated:\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
fibno=fibonacci(i);
printf("%d ",fibno);
}
getch();
}

int fibonacci(int n)
{
if(n==0)
{
return 0;
}
else
{
if(n==1)
{
return 1;
}
else
{
return fibonacci(n-1)+fibonacci(n-2);
}
}
}
Output:-
Enter number of elements to be generated:
5
0 1 1 2 3

You might also like