0% found this document useful (0 votes)
14 views

3 Functions

The document discusses different types of functions in C programming, including user-defined functions which must be defined by the programmer, and predefined library functions which are already defined in system libraries. It also covers the basics of function declarations, definitions, prototypes, arguments, return types, and how functions are called and used to break programs into smaller, reusable parts of code.

Uploaded by

Dhanush Kamaraj
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

3 Functions

The document discusses different types of functions in C programming, including user-defined functions which must be defined by the programmer, and predefined library functions which are already defined in system libraries. It also covers the basics of function declarations, definitions, prototypes, arguments, return types, and how functions are called and used to break programs into smaller, reusable parts of code.

Uploaded by

Dhanush Kamaraj
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 134

Functions

• A function is a block of code that performs a specific task.


• Functions are often used to perform similar tasks on different
data sets.
• A large C program is divided into basic building blocks called C
functions. C function contains a set of instructions enclosed by “{
}” which performs specific operations in a C program Actually,
the collection of these functions creates a C program.
Types of C functions

-main() -printf
-scanf

-sqrt()
1. User-defined functions
• These functions must be defined by the programmer or user.
• Programmer has to write the coding for such functions and test
them properly before using them.
• The syntax of the function is given by the user so there is no
need to include any header files.
• For example: main(), swap(), sum(), etc., are some of the user-
defined functions.
#include <math.h>
#include <stdio.h>
int main()
{
Output:
double number, squareRoot; Enter a positive number
printf("Enter a number: "); 25
Squareroot = 5
scanf("%lf", &number);
// computing the square root
squareRoot = sqrt(number);
printf("Square root of %.2lf = %.2lf", number, squareRoot);
return 0;
}
2. Predefined (or) library functions
• These functions are already defined in the system libraries.
• Programmer can reuse the existing code in the system libraries
which is helpful to write error-free code.
• User must be aware of the syntax of the function.

Example:
For instance, sqrt() function is available in math.h library and its usage is
y= sqrt (x), where x= number must be positive.
If x value is 25, i.e., y = sqrt (25) then ‘y’ = 5.
#include<stdio.h>
int sum(int, int);
void main() { Sum = 30
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{ return a+b;
}
User-defined vs library functions
User-defined Library
A programmer creates a function according A function whose prototypes are already
to the requirement of a program defined in the C library

A user-defined function is required to write We don't require writing a complete code to


the complete code before using the function use the library function in a program.
in a program
The name of any user-defined function can We can't change or modify the name of the
change easily. library function because the functionality of
these functions is already defined in the
compiler.
A user defined function is not compulsory to We need to use the library function in every
use in any C program. C program.
Contd.
User-defined Library
A user-defined function does not require All the library functions are predefined inside
writing any code inside the header files. the header files.
For example: swap() function does not For example: printf(), and scanf() function
require any header file. are defined in the stdio.h header file.
A user-defined function is part of a program. Library functions are part of the C header
file.
The programmer or user define the function The developer in the C compiler predefines
at the time of writing the code. the library function.

Example: multiply(), sum() divide(), etc. are Example: printf(), sqrt(), strcpy(), etc.
the user defined or user created function in a
program.
Advantages of Functions
• It is much easier to write a structured program where a
large program can be divided into a smaller, simpler
task.
• Allowing the code to be called many times.
• Easier to read and update.
• It is easier to debug a structured program where there
error is easy to find and fix.
C function declaration, function call and function
definition
There are 3 aspects in each C function. They are,
• Function declaration or prototype – this informs compiler about
the function name, function parameters and return value’s data
type.
• Function call – this calls the actual function.
• Function definition – this contains all the statements to be
executed.
C function aspects Syntax
function declaration return_type function_name
(arguments list)

function call function_name (arguments list);


function definition return_type function_name
(argument list);
{Body of functions; }
• Function names is cube.
• Variable that requires is
long.
• The variable to be passed
on is X (has single
arguments)= value can be
passed to function so it can
perform the specific task, it
is called argumensts.
• Functions should be declared and defined before
calling in a C program.
• Here “square” is called from main function.
• The value of “m” is passed as argument to the
function “square”. This value is multiplied by itself in
this function and multiplied value “p” returned to main
function from function “square”.
How the function works
• C program doesn’t execute the statement in function
until the function is called.
• When function is called the program can send the
function information in the form of one or more
argument.
• When the function is used is referred to as the called
function.
• Functions often use data that is passes to them from
the calling function.
• Data is passed from the calling function to a called
function by specifying the variable in a argument list.
• Argument list cannot be used to send data, its only
copy data/value/variable that pass from the calling
function.
• The called function then performs its operation using
the copies.
Function prototypes
• Provides the compiler with the description of functions that will be
used later in the program.
• Its define the function before it been used/called.
• Function prototype need to be written at the beginning of the
program.
• The function prototype must have:
A return type indicating the variable that the function will be return.
Syntax for function prototype
return-type function_name(arg-type name-1,…,arg-type name-n);
Function prototype examples
• double squared(double number);
• void print_report(int report_number);
• Int get_menu-choice(void);
Function Definition
• It is the actual function that contains the code that will be
execute.
• Should be identical to the function prototype.
Syntax of function definition
return-type function_name(arg-type name-1,…,arg-type name-n)
{
declarations; function header
statements;
return(expression); function body
}
Function definition example
float conversion(float celsius)
{
float fahrenheit;
fahrenheit = celsius*33.8;
return fahrenheit;
}
• The function name is conversion.
• This function accepts arguments celsius of the type float. The function
return a float value.
• So, when the function is called in the program, it will perform its task
which is to convert fahrenheit by multiply celsius with 33.8 and return
the result of the summation
• Note that if the function is returning a value, it needs to use the
keyword return.
Function return types
Can be any of C’data type
char
int
float
long ….

Examples:
int funct(…) /*return a type int*/
float funct2(…) /*returns a type float*/
void funct3(…) /*returns nothing*/
Types of functions

Functions can be divided into 4 categories:


1. A function with no arguments and no return value.
2. A function with no arguments and a return value.
3. A function with an argument or arguments and returns no value.
4. A function with arguments and return values.
A function with no arguments and no return value

• Called function does not have any arguments.


• Not able to get value from the calling functions.
• Not returning any value.
• There is no data transfer between the calling function and called
function.
#include<stdio.h>
int main()
{
void sum();
sum();
}
void sum() //function with no arguments and return data type
{
int x=15,y=35,z=5;
printf("x = %d ; y = %d ; z = %d \n",x,y,z);
int sum = x+y+z;
printf("Sum = %d",sum);
}
Output:
x = 15 ; y = 35 ; z = 5
Sum = 55
A function with no arguments and a return value

• Does not get any values from the calling function.


• Can give a return value to calling program.
#include<stdio.h>
int main()
{
Output:
int sum(); x = 10 ; y = 20 ; z = 5
int c = sum(); Sum = 35

printf("Sum = %d",c);
}
int sum() //function with no arguments and return data type
{
int x=10,y=20,z=5;
printf("x = %d ; y = %d ; z = %d \n",x,y,z);
int sum = x+y+z;
return(sum);
}
A function with an argument or arguments and a return no
value
• A function has arguments.
• A calling function can pass values to function called, but calling
function not receive any value.
• Data is transferred from calling function but no data is
transferred from the called function to the calling function.
• Generally Output is printed in the Called function.
• A function that does not return any value cannot be used in an
expression it can be used only as independent statement.
#include <stdio.h>
int main()
{
void sum(float,float); //function with arguments and no return value
float x=10.56,y=7.22;
sum(x,y);
}
void sum(float a,float b) //function with arguments and no return value
{
float z = a+b;
printf("x + y = %f",z);
}
Output:
x + y = 17.780001
A function with arguments and returning a values

• Argument are passed by calling function to the called function.


• Called function return value to the calling function.
• Mostly used in programming because it can two way
communication.
• Data returned by the function can be used later in program for
further calculation.
Send 2 integer value x and y to add()

Function add the two values and send


back the result to the calling function.

int is the return type of function.

Return statement is a keyword and in


bracket we can give values which we
want to return.
#include <stdio.h>
void main()
{
int sub(int,int); //function with return value and arguments
int x=10,y=7;
int res = sub(x,y);
printf("x-y = %d",res);
}
int sub(int a,int b) //function with return value and arguments
{
return(a-b); // return value
}
Output:
x-y = 3
Actual arguments vs Formal arguments
Contd.
Calling function vs called function
The Function which calls another Function is called a Calling
Function and the function which is called another Function is Called
Function.
Example: main() is calling function and sub() is calling function.
A caller is a function that calls another function; a callee is a function
that was called. The currently-executing function is a callee, but not a
caller.
Call by value vs Call by Reference

These are differentiated by the type of values passed to them as


parameters.

The parameters passed to the function are called actual


parameters whereas the parameters received by the function
are called formal parameters.
Contd.
Call by value: Parameter passing method, values of actual
parameters are copied to the function’s formal parameters and the
two types of parameters are stored in different memory
locations. So any changes made inside functions are not reflected
in the actual parameters of the caller.

Call by reference: Both the actual and formal parameters refer to


the same locations, so any changes made inside the function are
actually reflected in the actual parameters of the caller.
https://www.youtube.com/watch?v=kCiNYzHuIX8
C Call by Value Call by reference
While calling a function, we pass While calling a function, instead of
values of variables to it. Such passing the values of variables, we
functions are known as “Call By pass address of variables(location of
Values”. variables) to the function known as
“Call By References.
The value of each variable in the The address of actual variables in
calling function is copied into the calling function is copied into the
corresponding dummy variables of dummy variables of the called
the called function. function.
C Call by Value Call by reference
The changes made to the dummy Using addresses we would have an
variables in the called function access to the actual variables and
have no effect on the values of hence we would be able to
actual variables in the calling manipulate them.
function.
We cannot alter the values of We can alter the values of variables
actual variables through function through function calls.
calls
Values of variables are passed by Pointer variables are necessary to
the Simple technique. define to store the address values of
variables.
https://log2base2.com/courses/recursion/introduction-recursi
on-basic-rules-trial?preview
Output:
8
0, 1, 1, 2, 3, 5, 8, 13,
• Write a function that will take an integer as an input (the position in the
Fibonacci series whose element we want to display) and will return the
element at that position.
• In this function, we will have an if-else-if ladder.
• If the input will be 0 i.e., the element at the 0th position, we will return 0
• If the input will be 1 i.e., the element at 1st position, we will return 1
• else we will recursively call the fibonacci() function again twice and will
pass arguments by decreasing the num variable we initially received in
that specific call by 1 and 2 respectively and will be adding the function
calls
• This process will keep repeating till we get to our base condition of F(0) = 0
and F(1) = 1 and the function will finally return by adding each of the
returned values by each call, and finally we will get our required number
Towers of Hanoi

• Tower of Hanoi is a mathematical game or a puzzle which


consists of 3 rods or pegs and n disks of various diameters.
• The Tower of Hanoi puzzle begins with all disks stacked on one
rod in decreasing order and the task is to move all these disks
onto some other rod.
• The tower of Hanoi is a mathematical puzzle. It consists of three
rods and a number of disks of different sizes which can slide onto
any rod. The puzzle begins with all disks stacked on one rod in
decreasing order and the task is to move all these disks onto
some other rod obeying the following rules.
Rules of Tower of Hanoi Puzzle:

• Only one disk may be moved at a time.


• Each move consists of taking the upper disk from one of the
stacks and placing it on top of another stack or on an empty rod.
• No disk may be placed on top of a disk that is smaller than it.
Recursive statement of the general problem of n disks

Step 1:
Move the top (n-1) disks from frompeg (left) to auxpeg (center)
Step 2:
Move the largest disk from frompeg (left) to topeg (right)
Step 3:
Move the (n-1) disks from auxpeg (center) to topeg (right)
Example:
• Suppose no of disks are 4 and the starting rod is ‘A’, the auxiliary
rod is ‘B’ and the ending rod is ‘C’.
• In each step first, we move the topmost node of peg ‘A’ to
auxiliary peg ‘B’ and then finally move to ‘C’ which is the desired
peg.
• Initially: All disks are stacked on peg ‘A’ with the order of their size
being Disk3 < Disk2 < Disk1
1. Peg A Peg B Peg C
Disc 3
Disc 2
Disc 1
2. Moving Disc 3 To Peg C:
Peg A Peg B Peg C

Disc 2
Disc 1 Disc 3
3. Moving Disc 2 To Peg B:
Peg A Peg B Peg C

Disc 1 Disc 2 Disc 3


4. Moving Disc 3 To Peg B:
Peg A Peg B Peg C

Disc 3
Disc 1 Disc 2
5. Moving Disc 1 To Peg C:
Peg A Peg B Peg C

Disc 3
Disc 2 Disc 1
6. Moving Disc 3 To Peg B:
Peg A Peg B Peg C

Disc 3 Disc 2 Disc 1


7. Moving Disc 2 To Peg C:
Peg A Peg B Peg C

Disc 3 Disc 2
Disc 1
8. Moving Disc 3 To Peg C:
Peg A Peg B Peg C

Disc 3
Disc 2
Disc 1
Tower of Hanoi Algorithm:

Step 1: Start the program.


Step 2: Input the number of disks.
Step 3: Declare a function that takes the number of disks, starting
disk, auxiliary disk, and final disk as argument and recursively calls
itself twice.
Step 4: Call the function.
Step 5: End the Program.
#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;
}
void towers(int num, char frompeg, char topeg, char auxpeg)
{
if (num == 1)
{
printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("\n Move disk %d from peg %c to peg %c", num, frompeg,
topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}
Output:
Enter the number of disks : 3
The sequence of moves involved in the Tower of Hanoi are :

Move disk 1 from peg A to peg C


Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C
Program Explanation
1. First input the number of disks placed on three rods.
2. Declare a function that takes 4 parameters which are: no of disks and
name of the initial disk, auxiliary disk, and final disk.
3. The function recursively calls itself twice to solve the problem with a
base case to stop when n is 1.
4. Call this function from the main function.
Pass arrays to a function
Pass Individual Array Elements: Passing array elements to a
function is similar to passing variables to a function.
#include <stdio.h> int main() {
void display(int age1, int age2) int ageArray[] = {2, 8, 4, 12};
{ display(ageArray[1], ageArray[2]);
return 0;
printf("%d\n", age1); }
printf("%d\n", age2); Output:
8
}
4
#include<stdio.h>
void giveMeArray(int a);
int main()
{
int myArray[] = { 2, 3, 4 }; Output:
giveMeArray(myArray[2]); 4
return 0;
}
void giveMeArray(int a)
{
printf("%d", a);
}
Pass Arrays to Functions: Program to calculate the sum of array elements
by passing to a function
#include <stdio.h>
float calculateSum(float num[]);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
result = calculateSum(num); float calculateSum(float num[]) {
printf("Result = %.2f", result); float sum = 0.0;
for (int i = 0; i < 6; ++i) {
return 0; sum += num[i];
} }
return sum;
}
Output:
Result = 162.50
Pass Multidimensional Arrays to a Function: To pass multidimensional
arrays to a function, only the name of the array is passed to the function
(similar to one-dimensional arrays).
Pass two-dimensional arrays: void displayNumbers(int num[2][2])
#include <stdio.h> {
void displayNumbers(int num[2][2]); printf("Displaying:\n");
int main() { for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
int num[2][2];
printf("%d\n", num[i][j]);
printf("Enter 4 numbers:\n");
}
for (int i = 0; i < 2; ++i) {
}
for (int j = 0; j < 2; ++j) { }
scanf("%d", &num[i][j]);
} } displayNumbers(num);
return 0; }
Output:
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
#include<stdio.h>
void displayArray(int arr[3][3]);
int main()
{
int arr[3][3], i, j;
printf("Please enter 9 numbers for the array: \n");
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 3; ++j)
{ scanf("%d", &arr[i][j]); }
}
displayArray(arr);
return 0; }
}
void displayArray(int arr[3][3])
{
Please enter 9 numbers for the
int i, j;
array:
printf("The complete array is: \n"); 1
2
for (i = 0; i < 3; ++i)
3
{ 4
5
printf("\n");
6
for (j = 0; j < 3; ++j) 7
8
{
9
// \t is used to provide tab space The complete array is:
1 2 3
printf("%d\t", arr[i][j]); }
4 5 6
} 7 8 9
}
C Preprocessor and header files
Strings

You might also like