SlideShare a Scribd company logo
UNIT 7
FUNCTIONS
• A function is a group of statements that together perform a task.
• Every C program has at least one function, which is main(), and all the
most trivial programs can define additional functions.
• You can divide up your code into separate functions.
• How you divide up your code among different functions is up to you,
but logically the division is such that each function performs a specific
task.
2/29/2016 Ashim Lamichhane 2
• Suppose a program where a set of operations has to be repeated
often, though not continuously.
• Loops seems like a better option.
• Instead of inserting the program statements for these operations at so
many places, a separate program segment is written and compiled it
separately.
• As many times as it is needed, the segment program is called.
• The separate program segment is called a function.
2/29/2016 Ashim Lamichhane 3
• Suppose we have to calculate a nCr
nCr = n!/(n-r)!r!
• Without using function:
for(i=1;i<=n;i++){
f1*=1;
}
for(i=1;i<=(n-r);i++){
f2*=1;
}
for(i=1;i<=r;i++){
f3*=1;
}
comb=f1/(f2*f3);
2/29/2016 Ashim Lamichhane 4
Advantages of Function
• Manageability
• Easier to write and keep track of.
• Easier to understand and maintain
• Code Reusability
• Can be used multiple times
• Non-redundant programming
• Same function can be called when needed.
• Logical Clarity
• Reduced number of code in main function.
• Easy to divide the work to many different programmers.
• Large work can be divided by writing different functions.
2/29/2016 Ashim Lamichhane 5
• The C Functions can be classified into two categories:
1. User defined function
2. Library Functions
2/29/2016 Ashim Lamichhane 6
Library functions (Built-in functions)
• These are the functions which are already written, compiled and
placed in C library and they are not required to be written by a
programmer.
• The function’s name, its return type, their argument number and types
have been already defined.
• We can use these functions as required.
• Ex: printf(), scanf(), sqrt(), getch() are example of library functions.
2/29/2016 Ashim Lamichhane 7
User – defined functions
• These are functions which are defined by user at the time of writing a
program.
• The user has choice to choose its name, return type, arguments and
their types.
• The job of each user-defined function is as defined by the user
• A complex C problem can be divided into a number of user-defined
functions.
2/29/2016 Ashim Lamichhane 8
main() function
• The function main() is an user defined function except that the name
of function is defined or fixed by the language.
• The return type, argument and body of the function are defined by the
programmer as required.
• The function is executed first, when the program starts execution.
2/29/2016 Ashim Lamichhane 9
Components associated with function
• Function Definition
• Function declaration or prototype
• Return Statement
• Accessing/Calling a function
2/29/2016 Ashim Lamichhane 10
Function definition
• The collection of program statements that describes the specific task to be
done by the function is called function definition.
• It consists of function header, which defines function’s name, its
return type and its argument list and a function body, which is
a block of code enclosed in parenthesis.
• Syntax:
return_type function_name(data_type variable1, data_type variable2,…..) {
…...
statements;
.....
}
2/29/2016 Ashim Lamichhane 11
All the parts of a function
• Return Type:
• A function may return a value.
• The return_type is the data type of the value the function returns.
• Some functions perform the desired operations without returning a value. In
this case, the return_type is the keyword void.
• Function Name
• This is the actual name of the function.
• The function name and the parameter list together constitute the function
signature.
2/29/2016 Ashim Lamichhane 12
• Parameters (data_type variable1, data_type variable2,….. )
• A parameter is like a placeholder.
• When a function is invoked, you pass a value to the parameter.
• This value is referred to as actual parameter or argument.
• The parameter list refers to the type, order, and number of the parameters of a
function.
• Parameters are optional; that is, a function may contain no parameters.
• Function Body
• The function body contains a collection of statements that define what the
function does.
2/29/2016 Ashim Lamichhane 13
int add(int a,int b){ //function header
int sum; // function body (statements)
sum=a+b; // function body (statements)
return sum; // returns value of sum to whoever called
}
----------------------------------------------------------------------------------------------
float areaOfCircle(float radius){ //function header
return 3.1428*radius*radius; // returns radius to whoever called
}
2/29/2016 Ashim Lamichhane 14
Function Declaration or Prototype
• The function declaration or prototype is model or blueprint of the
function.
• If functions are used before they are defined, then function
declaration or prototype is necessary which provides the following
information to the compiler
• The name of the function
• The type of the value returned by the function
• The number and the type of arguments that must be supplied when calling the
function.
2/29/2016 Ashim Lamichhane 15
Function Declaration or Prototype (cont…)
• A function declaration tells the compiler about a function name and how to call
the function. The actual body of the function can be defined separately.
• A function declaration has the following parts −
return_type function_name( parameter list );
• For the above defined function add(),the function declaration is as follows−
int add(int num1, int num2);
float areaOfCircle(float radius);
int max(int n1,int n2);
2/29/2016 Ashim Lamichhane 16
Return Statement
• It is the statement that is executed just before the function completes
its job and control is transferred back to the calling function.
• The job of return statement is to hand over some value given by
function body to the point where the call was made.
• Two purposes of return statement:
• Immediately transfer the control back to the calling program
• It returns the value to the calling function.
• SYNTAX:
return (expression);
• A function may or may not return a value. If a function doesn't return
a value the return type in the function definition and declaration is
specified as void.
2/29/2016 Ashim Lamichhane 17
Accessing/Calling a function
• A function can be called or accessed by specifying its name, followed by a
list of arguments enclosed in parenthesis and separated by commas.
• Ex:
• a function add() with two arguments is called by add(a,b) to add two numbers.
• If function call doesn’t require any arguments any empty pair of parenthesis must
follow the name of function.
• General Form:
• If function has parameters but it doesn’t return value
• function_name(variable1, variable2…);
• If function has no arguments and it doesn’t return value
• function_name();
• If function has parameters but it returns value
• variable_name=function_name(variable1, variable2…);
• If function has no arguments and it does return value
• variable_name=function_name();
2/29/2016 Ashim Lamichhane 18
/* function definition of add() function which takes two
integers and returns sum of them as integer */
#include <stdio.h>
int add(int a,int b){
int sum;
sum=a+b;
return sum;
}
float areaOfCircle(float radius){
return 3.1428*radius*radius;
}
int main(void){
int a,b,mysum; float myfloat;
printf("Enter two numbersn");
scanf("%d%d",&a,&b);
mysum=add(a,b);
printf("VALUE: %dn", mysum);
myfloat=areaOfCircle(mysum);
printf("So area of circle is: %fn",myfloat );
}
/* function definition of add() function which takes two integers and returns
sum of them as integer */
#include <stdio.h>
int add(int , int ); // Int add(int a, int b);
float areaOfCircle(float ) //float areaOfCircle(float r)
int main(void){
int a,b,mysum; float myfloat;
printf("Enter two numbersn");
scanf("%d%d",&a,&b);
mysum=add(a,b);
printf("VALUE: %dn", mysum);
myfloat=areaOfCircle(mysum);
printf("So area of circle is: %fn",myfloat );
}
int add(int a,int b){
int sum;
sum=a+b;
return sum;
}
float areaOfCircle(float radius){
return 3.1428*radius*radius;
}
2/29/2016 Ashim Lamichhane 19
Question
• Define a function whatIsYourName() which asks for your and returns
your name to main function and you print that name in the main
function.
• Define a function myPercentage() which calculates the percentage of
the marks in two subjects and marksGotInExams() asks for marks in
two subjects and returns your marks and percentage to the main
function.
2/29/2016 Ashim Lamichhane 20
#include <stdio.h>
int total(float a,float b){
return a+b;
}
float percentage(float total){
return total/2;
}
int main(void){
float a,b,mysum;
float myfloat;
printf("Enter marks in two subjects: n");
scanf("%f%f",&a,&b);
mysum=total(a,b);
printf("My total in two subjects: %.2fn", mysum);
myfloat=percentage(mysum);
printf("My percentage is: %.2f n",myfloat );
}
2/29/2016 Ashim Lamichhane 21
Category of functions according to the return value and arguments
• Category 1: Functions with no arguments and no return values
• Category 2: Functions with arguments and no return values
• Category 3: Function with arguments and return values
2/29/2016 Ashim Lamichhane 22
Category 1: Functions with no arguments and no return values
• When function has no arguments, it does not receive any data from
the calling function.
• Similarly when it doesn’t return a value, the calling function does not
receive any data from the called function.
• Thus, in such type of function’s there is no data transfer between the
calling function and the called function.
2/29/2016 Ashim Lamichhane 23
void function_name()
{
/* body of function */
}
• Keyword void means the function doesn’t return any value.
• There is no arguments within parenthesis which implies function has
no argument and it doesn’t receive any data from the called function.
2/29/2016 Ashim Lamichhane 24
Ex:
void addition(){
Int a,b,sum;
Printf(“enter any two numbers: t”);
Scanf(“%d%d”,&a,&b);
sum=a+b;
Printf(“n the sum is : t”,sum);
}
void main(){
clrscr();
addition();
getch();
}
2/29/2016 Ashim Lamichhane 25
Category 2: functions with arguments but no return value
void function_name(argument list)
{
Body of a function
}
• We pass arguments while calling a function but nothing is returned to
the calling function from.
2/29/2016 Ashim Lamichhane 26
Ex:
void addition(int a,int b){
int sum=0;
sum=a+b;
printf(“n the sum is : t”,sum);
}
void main(){
int a ,b;
clrscr();
printf(“enter any two numbers: t”);
Scanf(“%d%d”,&a,&b);
addition(a,b);
getch();
}
2/29/2016 Ashim Lamichhane 27
Category 3: Function with arguments and return values
• We pass arguments
• We expect a return value
return_type function_name(argument_list)
{
/* Body of the function */
return something;
}
2/29/2016 Ashim Lamichhane 28
Ex:
int addition(int a,int b){
int sum=0;
sum=a+b;
return sum;
}
void main(){
int a ,b,sum;
clrscr();
printf(“enter any two numbers: t”);
scanf(“%d%d”,&a,&b);
sum=addition(a,b);
printf(“n the sum is : ”,sum);
getch();
}
2/29/2016 Ashim Lamichhane 29
Passing arrays to function
• It is possible to pass the value of an array element and even an entire
array as an argument to a function.
• To pass an entire array to a function, the array name must appear by
itself, without brackets or subscripts, as an actual argument in
function call statement.
• When declaring a one-dimensional array as a formal argument, the
array name is written with a pair of empty square brackets. The size
of the array is not specified within the formal argument declaration.
Ashim Lamichhane 302/29/2016
• Syntax for function call passing array as argument,
function_name(array_name)
• Syntax for function prototype which accepts array
return_type function_name(data_type array_name[]);
Or
return_type function_name(data_type *pointer_variable);
• When array is passed to a function, the values of the array elements are not
passed to the function rather the array name is interpreted as the address
of the first array element.
• The address assigned to the corresponding formal argument when the
function is called.
• The formal argument therefore becomes a pointer to the first array
element.
Ashim Lamichhane 312/29/2016
#include <stdio.h>
void display(int n){
printf("%dt", n );
}
int main(void){
int nums[5]={100,23,44,3,65},i;
printf("nThe content of array is: n");
for (int i = 0; i < 5; i++){
display(nums[i]);
}
}
Ashim Lamichhane 322/29/2016
WAP to illustrate passing an entire array to a function
#include <stdio.h>
void change(int a[]){
a[0]=10;a[1]=20;a[2]=30;a[3]=40;a[4]=50;
}
int main(void){
int nums[5]={100,23,44,3,65},i;
printf("nBEFORE FUNCTION CALL: n");
for (int i = 0; i < 5; i++) {
printf("t%d",nums[i]);
}
printf("n");
change(nums); /* PASSING ARRAYS NUMS TO FUNCTION */
printf("nAFTER FUNCTION CALLn");
for (int i = 0; i < 5; i++) {
printf("t%d",nums[i]);
} printf("n");
}
Ashim Lamichhane 332/29/2016
Passing Strings to Functions
#include <stdio.h>
void Display(char ch[]);
int main(){
char c[50];
printf("Enter string: ");
gets(c);
Display(c); // Passing string c to function.
return 0;
}
void Display(char ch[]){
printf("String Output: ");
puts(ch);
}
• Here, string c is passed from main() function to user-defined function Display(). In function
declaration, ch[] is the formal argument.
Ashim Lamichhane 342/29/2016
Different types of function call
• The arguments in function can be passed in two ways:
• Pass arguments by value
• Pass arguments by address or reference or points
2/29/2016 Ashim Lamichhane 35
Function call by Value (Pass arguments by value)
• When values of actual arguments are passed to the function as
arguments, its known as function call by value.
• In this call, the value of each actual argument is copied into
corresponding formal argument of the function definition.
2/29/2016 Ashim Lamichhane 36
/* A program to illustrate function call by value */
#include <stdio.h>
void swap(int, int);
/* function prototype */
int main(void){
int a=99,b=98;
printf("BEFORE function calling a and b are: %d t %dn",a,b);
swap(a,b); /* function call by value */
printf("After calling function, a and b are: %dt %dn",a,b );
}
void swap(int x, int y){
int temp;
temp=x;
x=y;
y=temp;
printf("The values within functions are %dt%dn",x,y);
}
2/29/2016 Ashim Lamichhane 37
#include <stdio.h>
void swap(int x, int y); /* function declaration */
int main () {
int a = 100; int b = 200; /* local variable definition */
printf("Before swap, value of a : %dn", a );
printf("Before swap, value of b : %dn", b );
swap(a, b); /* calling a function to swap the values */
printf("After swap, value of a : %dn", a );
printf("After swap, value of b : %dn", b );
return 0;
}
/* function definition to swap the values */
void swap(int x, int y) {
int temp; temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
2/29/2016 Ashim Lamichhane 38
Function Call by Reference (Pass argument by address)
• In this type of function call, the address of variable is passed as an argument instead of
actual value of variable.
• Using this method, the original values are changed if they are changed within the function
• We need pointer for this. Detail study of pointer will be on next unit.
• Pointer: a pointer is a variable that stores a memory address of a variable.
• Pointer is declared in the same fashion like other variables but is always preceded by ‘*’
(asterisk) operator.
Ex. int *a; float *b; char *c;
• Here a,b and c are pointer variables which stores address of integer, float and char
variables
2/29/2016 Ashim Lamichhane 39
int *a; float *b ; char *c;
int x; float y; char z;
/* now we can do */
a=&x; /* the address of x is assigned to pointer variable a */
b=&y; /* the address of float variable y is stored in pointer variable b */
c=&z; /* the address of char variable z is stored in pointer variable c */
2/29/2016 Ashim Lamichhane 40
WAP to swap the values of two variables using call by reference
void swap(int *,int *);
void main(){
int a=99,b=98;
printf("BEFORE function calling a and b are: %d t %dn",a,b);
swap(&a,&b); /* function call by reference*/
printf("After calling function, a and b are: %dt %dn",a,b );
}
void swap(int *x, int *y){
int temp;
temp=*x;
*x=*y;
*y=temp;
}
2/29/2016 Ashim Lamichhane 41
#include <stdio.h>
void swap(int *x, int *y); /* function declaration */
int main () {
int a = 100; int b = 200; /* local variable definition */
printf("Before swap, value of a : %dn", a );
printf("Before swap, value of b : %dn", b );
/* calling a function to swap the values.
&a indicates pointer to a ie. address of variable a and
&b indicates pointer to b ie. address of variable b. */
swap(&a, &b);
printf("After swap, value of a : %dn", a );
printf("After swap, value of b : %dn", b );
return 0;
}
void swap(int *x, int *y) { /* function definition to swap the values */
int temp; temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
2/29/2016 Ashim Lamichhane 42
Recursive function
• A recursive function is one which calls itself.
• Recursive functions are useful in evaluating certain types of
mathematical function.
• The function is called recursive function if it calls to itself and
recursion is a process by which a function calls itself repeatedly until
some specified condition is satisfied.
2/29/2016 Ashim Lamichhane 43
Recursive function
• To solve a problem using recursive method, two conditions must be
satisfied. They are:
• Problem could be written or defined in term of its previous
result.
• Problem statement must include a stopping condition i.e. we
must have an if statement somewhere to force the
function to return without the recursive call being executed,
otherwise the function will never return.
2/29/2016 Ashim Lamichhane 44
Ex: Suppose you have numbers from 0 to 9 and you need to calculate the sum of
these numbers in the following way :
• you can see that we start with 0 and 1
• sum them up and add the result into next
number ie 2
• then again we add this result to 3 and continue
like this.
• Now lets see the code….
0 + 1 = 1
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
10 + 5 = 15
15 + 6 = 21
21 + 7 =28
28 + 8 = 36
36 + 9 = 45
2/29/2016 Ashim Lamichhane 45
#include <stdio.h>
int count = 1;
void func(int sum) {
sum = sum + count;
count ++;
if(count <=9){
func(sum);
} else {
printf("nSum is [%d] n", sum);
} return;
}
int main(void) {
int sum = 0;
func(sum);
return 0;
}
Explanation
• When func() was called through main(), ‘sum’
was zero.
• For every call to func(), the value of ‘sum’ is
incremented with ‘count’ (which is 1 initially),
which itself gets incremented with every call.
• The condition of termination of this recursion
is when value of ‘count’ exceeds 9. This is
exactly what we expect.
• When ‘count’ exceeds 9, at this very moment,
the value of ‘sum’ is the final figure that we
want and hence the solution.
2/29/2016 Ashim Lamichhane 46
#include <stdio.h>
int func(int num) {
int res = 0;
if(num <= 0){
printf("n Error n");
}else if(num ==1){
return num;
}else {
res = num * func(num -1);
return res;
}
return 0;
}
int main(void) {
int num = 5 ;
int fact = func(num);
if (fact > 0)
printf("n The factorial of [%d] is [%d]n", num, fact);
return 0;
}
• res = 5 * func(5 -1); // This is func() stack 1
• res = 4 *func(4-1); // This is func() stack 2
• res = 3 *func(4-1); // This is func() stack 3
• res = 2 *func(2-1); // This is func() stack 4
• return 1; // This is func() stack 5
Take an example of sum
sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15
2/29/2016 Ashim Lamichhane 47
WAP a program to find the factorial of a number using recursive
method
#include <stdio.h>
long int factorial(int i) {
if(i <= 1)
return 1;
else
return i * factorial(i - 1);
}
int main() {
int i = 5;
printf("Factorial of %d is %dn", i, factorial(i));
return 0;
}
5!
5*4!
5*4*3!
5*4*3*2!
5*4*3*2*1!
5*4*3*2*1
2/29/2016 Ashim Lamichhane 48
Recursion Iteration
A function is called from the definition of the same
function to do repeated task.
Loop is used to do repeated task
Recursion is a top-down approach to problem solving;
it divides the problem into pieces
Iterations is like a bottom-up approach; it begins with
what is known and from this it constructs the solution
step by step
In recursion, a function calls to itself until some
condition will be satisfied
In iteration, a function does not call to itself.
Problem could be written or defined in term of its
previous result to solve a problem using recursion
It is not necessary to define a problem in term of its
previous result to solve using iteration
All problems can not be solved using recursion All problems can be solved using iteration
2/29/2016 Ashim Lamichhane 49
Types of variables
• Local variable (automatic or internal variable)
• Global variables(External)
• Static variables
• Register variables
2/29/2016 Ashim Lamichhane 50
Local variables (automatic or internal)
• Are always declared within a function or block.
• Are local to the particular function or block in which they are declared.
• Other functions cannot access these variables.
• Compiler shows errors in case other functions try to access the variables.
• Are created when the function is called and destroyed automatically when the
function is exited.
• Scopeof a variable can be defined as the region over which the variable is
visible or valid
2/29/2016 Ashim Lamichhane 51
long int fact(int n){
int i;
long int f=1;
for(i=1; i<=n;i++){
f*=1;
return f;
}
void main(){
Int num=5;
printf(“factorial of %d is %ld”,num,f);
getch()
}
• here the variables n, i and f are local to function
fact() and are unknown to main()
function.
• Similarly num is local variable to the function
main() and unknown to the function fact()
2/29/2016 Ashim Lamichhane 52
Global variables (External)
• Variables that are both alive and active throughout the entire program.
• These are declared outside any block or function
• Can be accessed by any function in the program
• The scope is global. i.e within the program
• The life time is as long as the program execution doesn’t come to an
end.
2/29/2016 Ashim Lamichhane 53
int roll;
float marks;
main(){
…..;
…..;
…..;
}
func1(){
…..;
…..;
…..;
}
int a=10;
Void fun(){
a=20;
printf(“%d”,a++);
}
Void main(){
printf(“%d”,a);
fun();
printf(“%d”,a)
}
OUTPUT:
10
20
21
• Here, a is global variable and
is recognized within main() as
well as user-defined function
fun() and can be used
anywhere in the program.
2/29/2016 Ashim Lamichhane 54
Static variable
• Static variable can only be accessed from the function in which it is declared, just
like local variable.
• The static variable is not destroyed on exit from the function; instead its value is
preserved and becomes available again when the function is next called.
• Eg. static int counter;
• Can be initialized as normal variable.
• Its scope is local to the block in which the variable is defined.
• Its lifetime is global i.e. its value persists between different function calls.
2/29/2016 Ashim Lamichhane 55
/* With auto variables */
increment(){
Int i=1;
printf(“%dt”,i);
i++;
}
Void main(){
increment();
increment()
increment()
increment()
}
OUTPUT
1 1 1 1
2/29/2016 Ashim Lamichhane 56
/* With static variables */
increment(){
static int i=1;
printf(“%dt”,i);
i++;
}
Void main(){
increment();
increment()
increment()
increment()
}
OUTPUT
1 2 3 4
Register Variable
• Register variables are special case of automatic variables.
• Accessing data in memory is considerably slower than processing in the CPU.
• Computes often have small amounts of storage within the CPU itself where data can be
stored and accessed quickly.
• These storage cells are called registers.
• C provides storage class register for some variables to be allocated to CPU registers , if
possible.
• Thus register variables provide a certain control over efficiency of program execution.
2/29/2016 Ashim Lamichhane 57
Register Variable
• Variables which are used repeatedly or whose access times are critical
may be declared to be of storage register.
• It behaves just like automatic variables.
• They are allocated storage upon entry to a block and the storage is
freed when the block is exited.
• Scope of register variable is local to the block in which they are
declared.
2/29/2016 Ashim Lamichhane 58
#include<stdio.h>
int main() {
int num1,num2;
register int sum;
printf("nEnter the Number 1 : ");
scanf("%d",&num1);
printf("nEnter the Number 2 : ");
scanf("%d",&num2);
sum = num1 + num2;
printf("nSum of Numbers : %d",sum);
return(0);
}
2/29/2016 Ashim Lamichhane 59
Difference between local, global and static variables
Local Variables Global Variables Static Variables
The variables are declared within
function or blocks. The scope is
only within the function or block in
which they are defined
Global variables are defined
outside the functions so that their
scope is throughout the program
Static variables are special case of
local variables. Thus, static
variables are also defined inside
the functions or blocks
The initial value is unpredictable or
garbage value.
The initial value is zero The initial value is zero
The life time is till the control
remains within the block or
function in which the variable is
defined. The variable is destroyed
when function returns to the
calling function or block ends
The life time is till programs
execution doesn't come to an i.e.
variables are created when
program starts and destroyed when
program ends.
Its value persists between different
function calls. Thus life time is
same as global variables.
The keyword auto is used The keyword extern is used The keyword static is used.
2/29/2016 Ashim Lamichhane 60
Tower of Hanoi (TOH) problem
• Well known game
• Played with three poles and number of different sized disks.
• Each disk has hole in the center, allowing it to be stacked around any
of the poles.
• Initially disks are stacked on the leftmost pole in an order. i.e. Largest
on the bottom and the smallest on the top
2/29/2016 Ashim Lamichhane 61
Tower of Hanoi (TOH) problem
2/29/2016 Ashim Lamichhane 62
Objective on TOH problem
• Transfer the disks from the left most pole to the rightmost pole
without ever placing a larger disk on top of a smaller disk.
• Only one may be moved at a time and each disk must always be placed
around one of the poles.
• The problem can be solved in recursive method in three steps.
1. Move the top n-1 disks from the left pole to the center pole
2. Move nth disk(largest) to the right
3. Move the n-1 disk on the center pole to the right pole
2/29/2016 Ashim Lamichhane 63
TOH problem
/*C program for Tower of Hanoi using Recursion */
#include <stdio.h>
void towers(int, char, char, char);
int main()
{
int num;
printf("Enter the number of disks : ");
scanf("%d", &num);
printf("The sequence of moves involved in the
Tower of Hanoi are :n");
towers(num, 'A', 'C', 'B');
return 0;
}
2/29/2016 Ashim Lamichhane 64
void towers(int num, char frompeg, char topeg, char auxpeg)
{
if (num == 1)
{
printf("Move disk 1 from peg %c to peg %cn",
frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("Move disk %d from peg %c to peg %cn",
num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}
Questions
• Write a function CalculateRoots() which receives three coefficients a,b,c of
quadratic equation ax2+bx+c=0 as its arguments and then calculates and
displays its roots.
• Write a recursive function like int findsum(int n) which receives an integer n
and returns sum of first n natural numbers.
• Write three functions: convertFromFeetToInches() which converts feet value
to inches, convertFromInchesToCentimeters() which converts inches to
centimeters and convertFromCentimetersToMeter() which converts
centimeters to meters. Write a program that prompts a user for a
measurement in feet and then converts and displays this value in meters.
[Hint: 1 feet = 12 inches, 1 inch=2.54cm and 100cm = 1m]
2/29/2016 Ashim Lamichhane 65
Reference
• http://www.tutorialspoint.com/cprogramming/c_functions.htm
• http://www.cprogramming.com/tutorial/c/lesson4.html
• http://www.cs.utah.edu/~germain/PPS/Topics/C_Language/c_functio
ns.html
• http://www.programiz.com/c-programming/c-functions
• http://fresh2refresh.com/c-programming/c-function/
• http://www2.its.strath.ac.uk/courses/c/section3_9.html
2/29/2016 Ashim Lamichhane 66

More Related Content

What's hot

Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
Qazi Shahzad Ali
 
Strings in c
Strings in cStrings in c
Strings in c
vampugani
 
SPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in CSPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in C
Mohammad Imam Hossain
 
Unit 5. Control Statement
Unit 5. Control StatementUnit 5. Control Statement
Unit 5. Control Statement
Ashim Lamichhane
 
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
tanmaymodi4
 
C functions
C functionsC functions
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
Harendra Singh
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
Neeru Mittal
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
Nilesh Dalvi
 
C Pointers
C PointersC Pointers
C Pointers
omukhtar
 
Function in Python
Function in PythonFunction in Python
Function in Python
Yashdev Hada
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
Neeru Mittal
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variables
sangrampatil81
 
Managing input and output operation in c
Managing input and output operation in cManaging input and output operation in c
Managing input and output operation in c
yazad dumasia
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Pranali Chaudhari
 

What's hot (20)

Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
 
Strings in c
Strings in cStrings in c
Strings in c
 
SPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in CSPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in C
 
Unit 5. Control Statement
Unit 5. Control StatementUnit 5. Control Statement
Unit 5. Control Statement
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
C functions
C functionsC functions
C functions
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Constructor
ConstructorConstructor
Constructor
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
C Pointers
C PointersC Pointers
C Pointers
 
Function in Python
Function in PythonFunction in Python
Function in Python
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variables
 
Managing input and output operation in c
Managing input and output operation in cManaging input and output operation in c
Managing input and output operation in c
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 

Viewers also liked

File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
Sonya Akter Rupa
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
Gaurav Garg
 
Unit 3. Input and Output
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
Ashim Lamichhane
 
File in c
File in cFile in c
File in c
Prabhu Govind
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
Ashim Lamichhane
 
Unit 8. Pointers
Unit 8. PointersUnit 8. Pointers
Unit 8. Pointers
Ashim Lamichhane
 
File handling in c
File handling in c File handling in c
File handling in c
Vikash Dhal
 
Unit 11. Graphics
Unit 11. GraphicsUnit 11. Graphics
Unit 11. Graphics
Ashim Lamichhane
 
Unit 2. Elements of C
Unit 2. Elements of CUnit 2. Elements of C
Unit 2. Elements of C
Ashim Lamichhane
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
Ashim Lamichhane
 
File handling in C
File handling in CFile handling in C
File handling in C
Kamal Acharya
 

Viewers also liked (12)

File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
Unit 3. Input and Output
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
 
File in c
File in cFile in c
File in c
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
 
Unit 8. Pointers
Unit 8. PointersUnit 8. Pointers
Unit 8. Pointers
 
File handling in c
File handling in c File handling in c
File handling in c
 
Unit 11. Graphics
Unit 11. GraphicsUnit 11. Graphics
Unit 11. Graphics
 
Unit 2. Elements of C
Unit 2. Elements of CUnit 2. Elements of C
Unit 2. Elements of C
 
File handling in c
File handling in cFile handling in c
File handling in c
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 
File handling in C
File handling in CFile handling in C
File handling in C
 

Similar to Unit 7. Functions

PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
ArshiniGubbala3
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
Functions
FunctionsFunctions
Functions
FunctionsFunctions
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
Bharath904863
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 
Functions
Functions Functions
Functions
Dr.Subha Krishna
 
Function C programming
Function C programmingFunction C programming
Function C programming
Appili Vamsi Krishna
 
Functions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothiFunctions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothi
Sowmya Jyothi
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
NirmalaShinde3
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
Rhishav Poudyal
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
SKUP1
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
LECO9
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
KhurramKhan173
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
miki304759
 
Functions assignment
Functions assignmentFunctions assignment
Functions assignment
Ahmad Kamal
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
Appili Vamsi Krishna
 

Similar to Unit 7. Functions (20)

PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
Functions
FunctionsFunctions
Functions
 
Functions
FunctionsFunctions
Functions
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
Functions
Functions Functions
Functions
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Functions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothiFunctions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothi
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
Functions assignment
Functions assignmentFunctions assignment
Functions assignment
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 

More from Ashim Lamichhane

Searching
SearchingSearching
Searching
Ashim Lamichhane
 
Sorting
SortingSorting
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
Ashim Lamichhane
 
Linked List
Linked ListLinked List
Linked List
Ashim Lamichhane
 
Queues
QueuesQueues
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
Ashim Lamichhane
 
Algorithm big o
Algorithm big oAlgorithm big o
Algorithm big o
Ashim Lamichhane
 
Algorithm Introduction
Algorithm IntroductionAlgorithm Introduction
Algorithm Introduction
Ashim Lamichhane
 
Introduction to data_structure
Introduction to data_structureIntroduction to data_structure
Introduction to data_structure
Ashim Lamichhane
 
Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer   Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer
Ashim Lamichhane
 

More from Ashim Lamichhane (10)

Searching
SearchingSearching
Searching
 
Sorting
SortingSorting
Sorting
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
Linked List
Linked ListLinked List
Linked List
 
Queues
QueuesQueues
Queues
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
 
Algorithm big o
Algorithm big oAlgorithm big o
Algorithm big o
 
Algorithm Introduction
Algorithm IntroductionAlgorithm Introduction
Algorithm Introduction
 
Introduction to data_structure
Introduction to data_structureIntroduction to data_structure
Introduction to data_structure
 
Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer   Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer
 

Recently uploaded

special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 

Recently uploaded (20)

special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 

Unit 7. Functions

  • 2. • A function is a group of statements that together perform a task. • Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. • You can divide up your code into separate functions. • How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task. 2/29/2016 Ashim Lamichhane 2
  • 3. • Suppose a program where a set of operations has to be repeated often, though not continuously. • Loops seems like a better option. • Instead of inserting the program statements for these operations at so many places, a separate program segment is written and compiled it separately. • As many times as it is needed, the segment program is called. • The separate program segment is called a function. 2/29/2016 Ashim Lamichhane 3
  • 4. • Suppose we have to calculate a nCr nCr = n!/(n-r)!r! • Without using function: for(i=1;i<=n;i++){ f1*=1; } for(i=1;i<=(n-r);i++){ f2*=1; } for(i=1;i<=r;i++){ f3*=1; } comb=f1/(f2*f3); 2/29/2016 Ashim Lamichhane 4
  • 5. Advantages of Function • Manageability • Easier to write and keep track of. • Easier to understand and maintain • Code Reusability • Can be used multiple times • Non-redundant programming • Same function can be called when needed. • Logical Clarity • Reduced number of code in main function. • Easy to divide the work to many different programmers. • Large work can be divided by writing different functions. 2/29/2016 Ashim Lamichhane 5
  • 6. • The C Functions can be classified into two categories: 1. User defined function 2. Library Functions 2/29/2016 Ashim Lamichhane 6
  • 7. Library functions (Built-in functions) • These are the functions which are already written, compiled and placed in C library and they are not required to be written by a programmer. • The function’s name, its return type, their argument number and types have been already defined. • We can use these functions as required. • Ex: printf(), scanf(), sqrt(), getch() are example of library functions. 2/29/2016 Ashim Lamichhane 7
  • 8. User – defined functions • These are functions which are defined by user at the time of writing a program. • The user has choice to choose its name, return type, arguments and their types. • The job of each user-defined function is as defined by the user • A complex C problem can be divided into a number of user-defined functions. 2/29/2016 Ashim Lamichhane 8
  • 9. main() function • The function main() is an user defined function except that the name of function is defined or fixed by the language. • The return type, argument and body of the function are defined by the programmer as required. • The function is executed first, when the program starts execution. 2/29/2016 Ashim Lamichhane 9
  • 10. Components associated with function • Function Definition • Function declaration or prototype • Return Statement • Accessing/Calling a function 2/29/2016 Ashim Lamichhane 10
  • 11. Function definition • The collection of program statements that describes the specific task to be done by the function is called function definition. • It consists of function header, which defines function’s name, its return type and its argument list and a function body, which is a block of code enclosed in parenthesis. • Syntax: return_type function_name(data_type variable1, data_type variable2,…..) { …... statements; ..... } 2/29/2016 Ashim Lamichhane 11
  • 12. All the parts of a function • Return Type: • A function may return a value. • The return_type is the data type of the value the function returns. • Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. • Function Name • This is the actual name of the function. • The function name and the parameter list together constitute the function signature. 2/29/2016 Ashim Lamichhane 12
  • 13. • Parameters (data_type variable1, data_type variable2,….. ) • A parameter is like a placeholder. • When a function is invoked, you pass a value to the parameter. • This value is referred to as actual parameter or argument. • The parameter list refers to the type, order, and number of the parameters of a function. • Parameters are optional; that is, a function may contain no parameters. • Function Body • The function body contains a collection of statements that define what the function does. 2/29/2016 Ashim Lamichhane 13
  • 14. int add(int a,int b){ //function header int sum; // function body (statements) sum=a+b; // function body (statements) return sum; // returns value of sum to whoever called } ---------------------------------------------------------------------------------------------- float areaOfCircle(float radius){ //function header return 3.1428*radius*radius; // returns radius to whoever called } 2/29/2016 Ashim Lamichhane 14
  • 15. Function Declaration or Prototype • The function declaration or prototype is model or blueprint of the function. • If functions are used before they are defined, then function declaration or prototype is necessary which provides the following information to the compiler • The name of the function • The type of the value returned by the function • The number and the type of arguments that must be supplied when calling the function. 2/29/2016 Ashim Lamichhane 15
  • 16. Function Declaration or Prototype (cont…) • A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. • A function declaration has the following parts − return_type function_name( parameter list ); • For the above defined function add(),the function declaration is as follows− int add(int num1, int num2); float areaOfCircle(float radius); int max(int n1,int n2); 2/29/2016 Ashim Lamichhane 16
  • 17. Return Statement • It is the statement that is executed just before the function completes its job and control is transferred back to the calling function. • The job of return statement is to hand over some value given by function body to the point where the call was made. • Two purposes of return statement: • Immediately transfer the control back to the calling program • It returns the value to the calling function. • SYNTAX: return (expression); • A function may or may not return a value. If a function doesn't return a value the return type in the function definition and declaration is specified as void. 2/29/2016 Ashim Lamichhane 17
  • 18. Accessing/Calling a function • A function can be called or accessed by specifying its name, followed by a list of arguments enclosed in parenthesis and separated by commas. • Ex: • a function add() with two arguments is called by add(a,b) to add two numbers. • If function call doesn’t require any arguments any empty pair of parenthesis must follow the name of function. • General Form: • If function has parameters but it doesn’t return value • function_name(variable1, variable2…); • If function has no arguments and it doesn’t return value • function_name(); • If function has parameters but it returns value • variable_name=function_name(variable1, variable2…); • If function has no arguments and it does return value • variable_name=function_name(); 2/29/2016 Ashim Lamichhane 18
  • 19. /* function definition of add() function which takes two integers and returns sum of them as integer */ #include <stdio.h> int add(int a,int b){ int sum; sum=a+b; return sum; } float areaOfCircle(float radius){ return 3.1428*radius*radius; } int main(void){ int a,b,mysum; float myfloat; printf("Enter two numbersn"); scanf("%d%d",&a,&b); mysum=add(a,b); printf("VALUE: %dn", mysum); myfloat=areaOfCircle(mysum); printf("So area of circle is: %fn",myfloat ); } /* function definition of add() function which takes two integers and returns sum of them as integer */ #include <stdio.h> int add(int , int ); // Int add(int a, int b); float areaOfCircle(float ) //float areaOfCircle(float r) int main(void){ int a,b,mysum; float myfloat; printf("Enter two numbersn"); scanf("%d%d",&a,&b); mysum=add(a,b); printf("VALUE: %dn", mysum); myfloat=areaOfCircle(mysum); printf("So area of circle is: %fn",myfloat ); } int add(int a,int b){ int sum; sum=a+b; return sum; } float areaOfCircle(float radius){ return 3.1428*radius*radius; } 2/29/2016 Ashim Lamichhane 19
  • 20. Question • Define a function whatIsYourName() which asks for your and returns your name to main function and you print that name in the main function. • Define a function myPercentage() which calculates the percentage of the marks in two subjects and marksGotInExams() asks for marks in two subjects and returns your marks and percentage to the main function. 2/29/2016 Ashim Lamichhane 20
  • 21. #include <stdio.h> int total(float a,float b){ return a+b; } float percentage(float total){ return total/2; } int main(void){ float a,b,mysum; float myfloat; printf("Enter marks in two subjects: n"); scanf("%f%f",&a,&b); mysum=total(a,b); printf("My total in two subjects: %.2fn", mysum); myfloat=percentage(mysum); printf("My percentage is: %.2f n",myfloat ); } 2/29/2016 Ashim Lamichhane 21
  • 22. Category of functions according to the return value and arguments • Category 1: Functions with no arguments and no return values • Category 2: Functions with arguments and no return values • Category 3: Function with arguments and return values 2/29/2016 Ashim Lamichhane 22
  • 23. Category 1: Functions with no arguments and no return values • When function has no arguments, it does not receive any data from the calling function. • Similarly when it doesn’t return a value, the calling function does not receive any data from the called function. • Thus, in such type of function’s there is no data transfer between the calling function and the called function. 2/29/2016 Ashim Lamichhane 23
  • 24. void function_name() { /* body of function */ } • Keyword void means the function doesn’t return any value. • There is no arguments within parenthesis which implies function has no argument and it doesn’t receive any data from the called function. 2/29/2016 Ashim Lamichhane 24
  • 25. Ex: void addition(){ Int a,b,sum; Printf(“enter any two numbers: t”); Scanf(“%d%d”,&a,&b); sum=a+b; Printf(“n the sum is : t”,sum); } void main(){ clrscr(); addition(); getch(); } 2/29/2016 Ashim Lamichhane 25
  • 26. Category 2: functions with arguments but no return value void function_name(argument list) { Body of a function } • We pass arguments while calling a function but nothing is returned to the calling function from. 2/29/2016 Ashim Lamichhane 26
  • 27. Ex: void addition(int a,int b){ int sum=0; sum=a+b; printf(“n the sum is : t”,sum); } void main(){ int a ,b; clrscr(); printf(“enter any two numbers: t”); Scanf(“%d%d”,&a,&b); addition(a,b); getch(); } 2/29/2016 Ashim Lamichhane 27
  • 28. Category 3: Function with arguments and return values • We pass arguments • We expect a return value return_type function_name(argument_list) { /* Body of the function */ return something; } 2/29/2016 Ashim Lamichhane 28
  • 29. Ex: int addition(int a,int b){ int sum=0; sum=a+b; return sum; } void main(){ int a ,b,sum; clrscr(); printf(“enter any two numbers: t”); scanf(“%d%d”,&a,&b); sum=addition(a,b); printf(“n the sum is : ”,sum); getch(); } 2/29/2016 Ashim Lamichhane 29
  • 30. Passing arrays to function • It is possible to pass the value of an array element and even an entire array as an argument to a function. • To pass an entire array to a function, the array name must appear by itself, without brackets or subscripts, as an actual argument in function call statement. • When declaring a one-dimensional array as a formal argument, the array name is written with a pair of empty square brackets. The size of the array is not specified within the formal argument declaration. Ashim Lamichhane 302/29/2016
  • 31. • Syntax for function call passing array as argument, function_name(array_name) • Syntax for function prototype which accepts array return_type function_name(data_type array_name[]); Or return_type function_name(data_type *pointer_variable); • When array is passed to a function, the values of the array elements are not passed to the function rather the array name is interpreted as the address of the first array element. • The address assigned to the corresponding formal argument when the function is called. • The formal argument therefore becomes a pointer to the first array element. Ashim Lamichhane 312/29/2016
  • 32. #include <stdio.h> void display(int n){ printf("%dt", n ); } int main(void){ int nums[5]={100,23,44,3,65},i; printf("nThe content of array is: n"); for (int i = 0; i < 5; i++){ display(nums[i]); } } Ashim Lamichhane 322/29/2016
  • 33. WAP to illustrate passing an entire array to a function #include <stdio.h> void change(int a[]){ a[0]=10;a[1]=20;a[2]=30;a[3]=40;a[4]=50; } int main(void){ int nums[5]={100,23,44,3,65},i; printf("nBEFORE FUNCTION CALL: n"); for (int i = 0; i < 5; i++) { printf("t%d",nums[i]); } printf("n"); change(nums); /* PASSING ARRAYS NUMS TO FUNCTION */ printf("nAFTER FUNCTION CALLn"); for (int i = 0; i < 5; i++) { printf("t%d",nums[i]); } printf("n"); } Ashim Lamichhane 332/29/2016
  • 34. Passing Strings to Functions #include <stdio.h> void Display(char ch[]); int main(){ char c[50]; printf("Enter string: "); gets(c); Display(c); // Passing string c to function. return 0; } void Display(char ch[]){ printf("String Output: "); puts(ch); } • Here, string c is passed from main() function to user-defined function Display(). In function declaration, ch[] is the formal argument. Ashim Lamichhane 342/29/2016
  • 35. Different types of function call • The arguments in function can be passed in two ways: • Pass arguments by value • Pass arguments by address or reference or points 2/29/2016 Ashim Lamichhane 35
  • 36. Function call by Value (Pass arguments by value) • When values of actual arguments are passed to the function as arguments, its known as function call by value. • In this call, the value of each actual argument is copied into corresponding formal argument of the function definition. 2/29/2016 Ashim Lamichhane 36
  • 37. /* A program to illustrate function call by value */ #include <stdio.h> void swap(int, int); /* function prototype */ int main(void){ int a=99,b=98; printf("BEFORE function calling a and b are: %d t %dn",a,b); swap(a,b); /* function call by value */ printf("After calling function, a and b are: %dt %dn",a,b ); } void swap(int x, int y){ int temp; temp=x; x=y; y=temp; printf("The values within functions are %dt%dn",x,y); } 2/29/2016 Ashim Lamichhane 37
  • 38. #include <stdio.h> void swap(int x, int y); /* function declaration */ int main () { int a = 100; int b = 200; /* local variable definition */ printf("Before swap, value of a : %dn", a ); printf("Before swap, value of b : %dn", b ); swap(a, b); /* calling a function to swap the values */ printf("After swap, value of a : %dn", a ); printf("After swap, value of b : %dn", b ); return 0; } /* function definition to swap the values */ void swap(int x, int y) { int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ y = temp; /* put temp into y */ return; } 2/29/2016 Ashim Lamichhane 38
  • 39. Function Call by Reference (Pass argument by address) • In this type of function call, the address of variable is passed as an argument instead of actual value of variable. • Using this method, the original values are changed if they are changed within the function • We need pointer for this. Detail study of pointer will be on next unit. • Pointer: a pointer is a variable that stores a memory address of a variable. • Pointer is declared in the same fashion like other variables but is always preceded by ‘*’ (asterisk) operator. Ex. int *a; float *b; char *c; • Here a,b and c are pointer variables which stores address of integer, float and char variables 2/29/2016 Ashim Lamichhane 39
  • 40. int *a; float *b ; char *c; int x; float y; char z; /* now we can do */ a=&x; /* the address of x is assigned to pointer variable a */ b=&y; /* the address of float variable y is stored in pointer variable b */ c=&z; /* the address of char variable z is stored in pointer variable c */ 2/29/2016 Ashim Lamichhane 40
  • 41. WAP to swap the values of two variables using call by reference void swap(int *,int *); void main(){ int a=99,b=98; printf("BEFORE function calling a and b are: %d t %dn",a,b); swap(&a,&b); /* function call by reference*/ printf("After calling function, a and b are: %dt %dn",a,b ); } void swap(int *x, int *y){ int temp; temp=*x; *x=*y; *y=temp; } 2/29/2016 Ashim Lamichhane 41
  • 42. #include <stdio.h> void swap(int *x, int *y); /* function declaration */ int main () { int a = 100; int b = 200; /* local variable definition */ printf("Before swap, value of a : %dn", a ); printf("Before swap, value of b : %dn", b ); /* calling a function to swap the values. &a indicates pointer to a ie. address of variable a and &b indicates pointer to b ie. address of variable b. */ swap(&a, &b); printf("After swap, value of a : %dn", a ); printf("After swap, value of b : %dn", b ); return 0; } void swap(int *x, int *y) { /* function definition to swap the values */ int temp; temp = *x; /* save the value at address x */ *x = *y; /* put y into x */ *y = temp; /* put temp into y */ return; } 2/29/2016 Ashim Lamichhane 42
  • 43. Recursive function • A recursive function is one which calls itself. • Recursive functions are useful in evaluating certain types of mathematical function. • The function is called recursive function if it calls to itself and recursion is a process by which a function calls itself repeatedly until some specified condition is satisfied. 2/29/2016 Ashim Lamichhane 43
  • 44. Recursive function • To solve a problem using recursive method, two conditions must be satisfied. They are: • Problem could be written or defined in term of its previous result. • Problem statement must include a stopping condition i.e. we must have an if statement somewhere to force the function to return without the recursive call being executed, otherwise the function will never return. 2/29/2016 Ashim Lamichhane 44
  • 45. Ex: Suppose you have numbers from 0 to 9 and you need to calculate the sum of these numbers in the following way : • you can see that we start with 0 and 1 • sum them up and add the result into next number ie 2 • then again we add this result to 3 and continue like this. • Now lets see the code…. 0 + 1 = 1 1 + 2 = 3 3 + 3 = 6 6 + 4 = 10 10 + 5 = 15 15 + 6 = 21 21 + 7 =28 28 + 8 = 36 36 + 9 = 45 2/29/2016 Ashim Lamichhane 45
  • 46. #include <stdio.h> int count = 1; void func(int sum) { sum = sum + count; count ++; if(count <=9){ func(sum); } else { printf("nSum is [%d] n", sum); } return; } int main(void) { int sum = 0; func(sum); return 0; } Explanation • When func() was called through main(), ‘sum’ was zero. • For every call to func(), the value of ‘sum’ is incremented with ‘count’ (which is 1 initially), which itself gets incremented with every call. • The condition of termination of this recursion is when value of ‘count’ exceeds 9. This is exactly what we expect. • When ‘count’ exceeds 9, at this very moment, the value of ‘sum’ is the final figure that we want and hence the solution. 2/29/2016 Ashim Lamichhane 46
  • 47. #include <stdio.h> int func(int num) { int res = 0; if(num <= 0){ printf("n Error n"); }else if(num ==1){ return num; }else { res = num * func(num -1); return res; } return 0; } int main(void) { int num = 5 ; int fact = func(num); if (fact > 0) printf("n The factorial of [%d] is [%d]n", num, fact); return 0; } • res = 5 * func(5 -1); // This is func() stack 1 • res = 4 *func(4-1); // This is func() stack 2 • res = 3 *func(4-1); // This is func() stack 3 • res = 2 *func(2-1); // This is func() stack 4 • return 1; // This is func() stack 5 Take an example of sum sum(5) =5+sum(4) =5+4+sum(3) =5+4+3+sum(2) =5+4+3+2+sum(1) =5+4+3+2+1+sum(0) =5+4+3+2+1+0 =5+4+3+2+1 =5+4+3+3 =5+4+6 =5+10 =15 2/29/2016 Ashim Lamichhane 47
  • 48. WAP a program to find the factorial of a number using recursive method #include <stdio.h> long int factorial(int i) { if(i <= 1) return 1; else return i * factorial(i - 1); } int main() { int i = 5; printf("Factorial of %d is %dn", i, factorial(i)); return 0; } 5! 5*4! 5*4*3! 5*4*3*2! 5*4*3*2*1! 5*4*3*2*1 2/29/2016 Ashim Lamichhane 48
  • 49. Recursion Iteration A function is called from the definition of the same function to do repeated task. Loop is used to do repeated task Recursion is a top-down approach to problem solving; it divides the problem into pieces Iterations is like a bottom-up approach; it begins with what is known and from this it constructs the solution step by step In recursion, a function calls to itself until some condition will be satisfied In iteration, a function does not call to itself. Problem could be written or defined in term of its previous result to solve a problem using recursion It is not necessary to define a problem in term of its previous result to solve using iteration All problems can not be solved using recursion All problems can be solved using iteration 2/29/2016 Ashim Lamichhane 49
  • 50. Types of variables • Local variable (automatic or internal variable) • Global variables(External) • Static variables • Register variables 2/29/2016 Ashim Lamichhane 50
  • 51. Local variables (automatic or internal) • Are always declared within a function or block. • Are local to the particular function or block in which they are declared. • Other functions cannot access these variables. • Compiler shows errors in case other functions try to access the variables. • Are created when the function is called and destroyed automatically when the function is exited. • Scopeof a variable can be defined as the region over which the variable is visible or valid 2/29/2016 Ashim Lamichhane 51
  • 52. long int fact(int n){ int i; long int f=1; for(i=1; i<=n;i++){ f*=1; return f; } void main(){ Int num=5; printf(“factorial of %d is %ld”,num,f); getch() } • here the variables n, i and f are local to function fact() and are unknown to main() function. • Similarly num is local variable to the function main() and unknown to the function fact() 2/29/2016 Ashim Lamichhane 52
  • 53. Global variables (External) • Variables that are both alive and active throughout the entire program. • These are declared outside any block or function • Can be accessed by any function in the program • The scope is global. i.e within the program • The life time is as long as the program execution doesn’t come to an end. 2/29/2016 Ashim Lamichhane 53
  • 54. int roll; float marks; main(){ …..; …..; …..; } func1(){ …..; …..; …..; } int a=10; Void fun(){ a=20; printf(“%d”,a++); } Void main(){ printf(“%d”,a); fun(); printf(“%d”,a) } OUTPUT: 10 20 21 • Here, a is global variable and is recognized within main() as well as user-defined function fun() and can be used anywhere in the program. 2/29/2016 Ashim Lamichhane 54
  • 55. Static variable • Static variable can only be accessed from the function in which it is declared, just like local variable. • The static variable is not destroyed on exit from the function; instead its value is preserved and becomes available again when the function is next called. • Eg. static int counter; • Can be initialized as normal variable. • Its scope is local to the block in which the variable is defined. • Its lifetime is global i.e. its value persists between different function calls. 2/29/2016 Ashim Lamichhane 55
  • 56. /* With auto variables */ increment(){ Int i=1; printf(“%dt”,i); i++; } Void main(){ increment(); increment() increment() increment() } OUTPUT 1 1 1 1 2/29/2016 Ashim Lamichhane 56 /* With static variables */ increment(){ static int i=1; printf(“%dt”,i); i++; } Void main(){ increment(); increment() increment() increment() } OUTPUT 1 2 3 4
  • 57. Register Variable • Register variables are special case of automatic variables. • Accessing data in memory is considerably slower than processing in the CPU. • Computes often have small amounts of storage within the CPU itself where data can be stored and accessed quickly. • These storage cells are called registers. • C provides storage class register for some variables to be allocated to CPU registers , if possible. • Thus register variables provide a certain control over efficiency of program execution. 2/29/2016 Ashim Lamichhane 57
  • 58. Register Variable • Variables which are used repeatedly or whose access times are critical may be declared to be of storage register. • It behaves just like automatic variables. • They are allocated storage upon entry to a block and the storage is freed when the block is exited. • Scope of register variable is local to the block in which they are declared. 2/29/2016 Ashim Lamichhane 58
  • 59. #include<stdio.h> int main() { int num1,num2; register int sum; printf("nEnter the Number 1 : "); scanf("%d",&num1); printf("nEnter the Number 2 : "); scanf("%d",&num2); sum = num1 + num2; printf("nSum of Numbers : %d",sum); return(0); } 2/29/2016 Ashim Lamichhane 59
  • 60. Difference between local, global and static variables Local Variables Global Variables Static Variables The variables are declared within function or blocks. The scope is only within the function or block in which they are defined Global variables are defined outside the functions so that their scope is throughout the program Static variables are special case of local variables. Thus, static variables are also defined inside the functions or blocks The initial value is unpredictable or garbage value. The initial value is zero The initial value is zero The life time is till the control remains within the block or function in which the variable is defined. The variable is destroyed when function returns to the calling function or block ends The life time is till programs execution doesn't come to an i.e. variables are created when program starts and destroyed when program ends. Its value persists between different function calls. Thus life time is same as global variables. The keyword auto is used The keyword extern is used The keyword static is used. 2/29/2016 Ashim Lamichhane 60
  • 61. Tower of Hanoi (TOH) problem • Well known game • Played with three poles and number of different sized disks. • Each disk has hole in the center, allowing it to be stacked around any of the poles. • Initially disks are stacked on the leftmost pole in an order. i.e. Largest on the bottom and the smallest on the top 2/29/2016 Ashim Lamichhane 61
  • 62. Tower of Hanoi (TOH) problem 2/29/2016 Ashim Lamichhane 62
  • 63. Objective on TOH problem • Transfer the disks from the left most pole to the rightmost pole without ever placing a larger disk on top of a smaller disk. • Only one may be moved at a time and each disk must always be placed around one of the poles. • The problem can be solved in recursive method in three steps. 1. Move the top n-1 disks from the left pole to the center pole 2. Move nth disk(largest) to the right 3. Move the n-1 disk on the center pole to the right pole 2/29/2016 Ashim Lamichhane 63
  • 64. TOH problem /*C program for Tower of Hanoi using Recursion */ #include <stdio.h> void towers(int, char, char, char); int main() { int num; printf("Enter the number of disks : "); scanf("%d", &num); printf("The sequence of moves involved in the Tower of Hanoi are :n"); towers(num, 'A', 'C', 'B'); return 0; } 2/29/2016 Ashim Lamichhane 64 void towers(int num, char frompeg, char topeg, char auxpeg) { if (num == 1) { printf("Move disk 1 from peg %c to peg %cn", frompeg, topeg); return; } towers(num - 1, frompeg, auxpeg, topeg); printf("Move disk %d from peg %c to peg %cn", num, frompeg, topeg); towers(num - 1, auxpeg, topeg, frompeg); }
  • 65. Questions • Write a function CalculateRoots() which receives three coefficients a,b,c of quadratic equation ax2+bx+c=0 as its arguments and then calculates and displays its roots. • Write a recursive function like int findsum(int n) which receives an integer n and returns sum of first n natural numbers. • Write three functions: convertFromFeetToInches() which converts feet value to inches, convertFromInchesToCentimeters() which converts inches to centimeters and convertFromCentimetersToMeter() which converts centimeters to meters. Write a program that prompts a user for a measurement in feet and then converts and displays this value in meters. [Hint: 1 feet = 12 inches, 1 inch=2.54cm and 100cm = 1m] 2/29/2016 Ashim Lamichhane 65
  • 66. Reference • http://www.tutorialspoint.com/cprogramming/c_functions.htm • http://www.cprogramming.com/tutorial/c/lesson4.html • http://www.cs.utah.edu/~germain/PPS/Topics/C_Language/c_functio ns.html • http://www.programiz.com/c-programming/c-functions • http://fresh2refresh.com/c-programming/c-function/ • http://www2.its.strath.ac.uk/courses/c/section3_9.html 2/29/2016 Ashim Lamichhane 66