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

FOC Unit 4 _ 5 slides

Uploaded by

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

FOC Unit 4 _ 5 slides

Uploaded by

abishekcr5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

M.S.

Ramaiah Institute of Technology


(Autonomous Institute, Affiliated to VTU)
Department of Computer Science and Engineering

Course Name: Fundamentals of Computing


Course Code: CS16
Credits: 2:0:0
UNIT 4

Term: January-March 2021


User Defined Functions:
❖ Introduction,
❖Need for User-Defined Functions,
❖ Elements of User-Defined Functions,
❖ Definition of Functions,
❖Return Values and Their Types, Function Calls,
❖Categories of Functions,
❖ Recursion.

Department of Computer Science and Engineering


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

•A large C program is divided into basic building blocks called C function. C function contains set
of instructions enclosed by “{ }” which performs specific operation in a C program.

•There are many situations where we might need to write same line of code for more than once in a
program. This may lead to unnecessary repetition of code, bugs and even becomes boring for the
programmer. So, C language provides an approach in which you can declare and define a group of
statements once in the form of a function and it can be called and used whenever required.

•C allows you to define functions according to your need, These functions are known as user-
defined functions.

Department of Computer Science and Engineering


C functions can be classified into two categories:
•Library functions
•User-defined functions

•Library functions are those functions which are already defined in C library,
example printf(), scanf(), strcat() etc. You just need to include appropriate header files to use these
functions. These are already declared and defined in C libraries.

•A User-defined functions on the other hand, are those functions which are defined by the user at
the time of writing program. These functions are made for code reusability and for saving time and
space.

Department of Computer Science and Engineering


Benefits/Need of Using Functions:
•It provides modularity to your program's structure.
•A large C program can easily be tracked when it is divided into functions.

•It makes your code reusable. You just have to call the function by its name to use it, wherever
required.

•In case of large programs with thousands of code lines, debugging and editing becomes easier if
you use functions.

•It makes the program more readable and easy to understand.

•It is used to avoid rewriting same logic/code again and again in a program.

Department of Computer Science and Engineering


There are a few steps that need to be follow in order to create a function:

Function Declaration: Like variable declaration, a function declaration specifies the type of the
function.
Function Definition: A function needs to be defined in order to be used. It is the actual function that
we are going to work on.
Function parameters: They contain values or arguments that are sent by the calling function.
Function call: It is how we are going to call the function to get executed.
Department of Computer Science and Engineering
Function Declaration: •It is usually done at the top of the
program and indicates how the function
return_type function_name(parameters); shall be called.
• The actual function definition can be
A function declaration specifies: present anywhere in the program.
•The type of the function or return type,
•The function name and
•Its parameters.
•Function return type: It indicates what type of value the function will return. Eg: int, double, float, char, etc.
A function with void return type does not return any value.
•Function name: A function name can be anything the user decides. Usually, a function name is kept
according to the function it performs.
•Function Parameter: It contains arguments and may or may not take values from the calling function.

Department of Computer Science and Engineering


return_type function_name(parameter)
{

//body of the function


Function Definition
}
Elements of User-Defined Functions:•The first line is known as function header

1. Function name •returntype functionName(type1 parameter1, type2 parameter2)


2. Function Return Type
3. List of parameters •The Second line is function body
4. Local variables
5. C Function statements
It contains the declarations and the statements(algorithm) necessary for performing
6. Return Statement
the required task. The body is enclosed within curly braces { ... } and consists of
three parts.
•local variable declaration(if required).
•function statements to perform the task inside the function.
•a return statement to return the result evaluated by the function(if return type
is void, then no return statement is required).

Department of Computer Science and Engineering


Return Values and Their Types, Function Calls

There are two types of function parameters/Arguments:

•Formal Parameter: The parameter which is written at the function definition is known as a formal
parameter.
•Actual Parameter: The parameter that is written at the function call is known as the actual parameter.

int sum(int,int); Function Declaration/ Function Prototype


void main()
{
int a ,b ;
sum(a ,b );//actual parameter Calling Function (Function Call)
}
int sum(int x, int y)//formal parameter Called Function(Function
Definition )
{
//body of the function
}
Department of Computer Science and Engineering
Return Type:

•When a function is declared to perform some sort of calculation or any operation and is expected to
provide with some result at the end, in such cases, a return statement is added at the end of function body.

•Return type specifies the type of value(int, float, char, double) that function is expected to return to
the program which called the function.

•Note: In case your function doesn't return any value, the return type would be void.

Returning a value from function:

•A function may or may not return a result. But if it does, we must use the return statement to output the
result. return statement also ends the function execution, hence it must be the last statement of any
function. If you write any statement after the return statement, it won't be executed.

Department of Computer Science and Engineering


Function Call

A function needs to be called by the calling function in order to get executed. There are two ways in which a
function can be called:

Call by reference: In this method, the address of the parameter or argument is put in the formal
parameter and then the values are accessed using the address in the actual parameter. Call by reference is
done as follows:
int sum(int *x,*y)// *x is the address which points to the value of the variable x stored in the address.

Call by value: In this method, the actual values are passed as an argument in the formal parameter and are
accessed in the actual parameter.
int sum(int x,int y) // x is the variable which contains the value so the value is directly passed to the
function

Note:- The difference between the above two is that, when we pass by reference then no new copy of the value is created i.e. the passed
variable is used and even if we do not return anything from the called function then also the changes will reflect inside the calling
function.

Department of Computer Science and Engineering


Passing Arguments toDepartment
a function of Computer Science
Returning a value from function
and Engineering

Department of Computer Science and Engineering


Categories of Functions
There can be 4 different types of user-defined functions, they are:

•Function with no arguments and no return value


•Function with no arguments and a return value
•Function with arguments and no return value
•Function with arguments and a return value

Department of Computer Science and Engineering


Categories of Functions
function declaration:
int function ( int );

function call:
function ( a ); Function with argument
1. With arguments
and with return values function definition:
int function( int a )
{
statements;
return a; Function with return value
}

Department of Computer Science and Engineering


Categories of Functions
function declaration:
void function ( int );

function call:
function( a ); Function with argument
2. With arguments and
Without return values
function definition:
void function( int a )
{
statements; Function without return value
}

Department of Computer Science and Engineering


Categories of Functions

function declaration:
void function();

function call:
function(); Function without argument
3. Without arguments and
without return values
function definition:
void function()
{
statements; Function without return value
}

Department of Computer Science and Engineering


Categories of Functions

function declaration:
int function ( );

function call:
function ( ); Function without argument
4. Without arguments and
With return values function definition:
int function( )
{
statements;
return a; Function with return value
}

Department of Computer Science and Engineering


#include<stdio.h>

int factorial(int x); //declaring the function


What is Recursion?
void main()
Recursion is a special way of {
int a, b;
nesting functions, where a
printf("Enter a number...");
function calls itself inside scanf("%d", &a);
it. b = factorial(a); //calling the function named factorial
printf("%d", b);
We must have certain }
conditions in the function to
break out of the recursion, int factorial(int x) //defining the function
otherwise recursion will {
occur infinite times. int r = 1;
if(x == 1)
return 1;
else
r = x*factorial(x-1); //recursion, since the function calls itself
return r;
}
Department of Computer Science and Engineering
The scope, visibility and lifetime of variables:
• Automatic variables,
•Static Variables,
•Register Variables, and
•External Variables.

Department of Computer Science and Engineering


•Scope is defined as the area in which the declared variable is ‘available’.

•The lifetime of a variable is the period of time in which the variable is allocated a space (i.e., the
period of time for which it “lives”).

•Visibility is the “accessibility” of the variable declared.

The scope of a variable is the part of the program within which the variable can be used. So, the
scope describes the visibility of an identifier within the program.
The lifetime of a variable or function is the time duration for which memory is allocated to store it, and
when that memory is released. It also refered as extent of a variable.

Department of Computer Science and Engineering


There are two basic types of scope: local scope and global scope.

•A variable declared outside all functions is located into the global scope.

•Access to such variables can be done from anywhere in the program.


•These variables are located in the global pool of memory, so their lifetime coincides with the lifetime
of the program.

•A variable declared inside a block (part of code enclosed in curly brackets) belongs to the local
scope.

•Such a variable is not visible (and therefore not available) outside the block, in which it is declared.
•The most common case of local declaration is a variable declared within a function. A variable
declared locally, is located on the stack, and the lifetime of such a variable is equal to the lifetime of
the function.

Department of Computer Science and Engineering


Static variables: Memory is allocated at the beginning of the program execution and it is reallocated
only after the program terminates. The scope of the static variables is local to the block in which the
variables are defined.

Register variables: belong to the register storage class and are stored in the CPU registers.

The scope of the register variables is local to the block in which the variables are defined.

The variables which are used for more number of times in a program are declared as register
variables for faster access.

Example: loop counter variables.

register int y=6;

Department of Computer Science and Engineering


#include<stdio.h>

int number; // global variable

void main()
{
number = 10;
printf("I am in main function. My value is %d\n", number);
fun1();
fun2(); /* This is function 1 */
fun2()
}
{
/* This is function 1 */ printf("\nI am in function fun2.
fun1() My value is %d", number);
{
number = 20; // local variable }
printf("I am in function fun1.
My value is %d", number); I am in function main. My value is 10
I am in function fun1. My value is 20
} I am in function fun2. My value is 20

Department of Computer Science and Engineering


Example for Static variable

#include <stdio.h> #include <stdio.h>

void decrement() Function Definition void decrement()


{ {
static int a=5; With Static variable int a=5; Without Static storage class
a--; a--;
printf("Value of a:%d\n", a); printf("Value of a:%d\n", a);
} }
int main() int main()
{ {
int i , n=4; int i , n=4;
for(i=0; i<n; i++) for(i=0; i<n; i++)
decrement(); Function Call decrement();
return 0; return 0;
} }
Value of a:4 Value of a:4
Value of a:3 Value of a:4
Value of a:2 Value of a:4
Value of a:1 Value of a:4
Department of Computer Science and Engineering
With Static variable Without Static storage class

#include<stdio.h> #include<stdio.h>

void test(); //Function declaration void test(); //Function declaration

int main() int main()


{ {
test(); test();
test(); test();
test(); test();
} }

void test() void test()


{ {
static int a = 0; int a = 0;
a = a + 1; a = a + 1;
printf("%d\t",a); printf("%d\t",a);

} }
OUTPUT: 1 2 3

Department of Computer Science and Engineering


What is a Storage Class?

•A storage class represents the visibility and a location of a variable. It tells from what part of code we can
access a variable.

•There are total four types of standard storage classes. The table below represents the storage classes in 'C'.

Department of Computer Science and Engineering


The variables defined using auto storage class are called as local variables.
• Auto stands for automatic storage class. A variable is in auto storage class by default if it is not
explicitly specified.
•The scope of an auto variable is limited with the particular block only.
#include <stdio.h> #include <stdio.h>
int main( ) int main( )
{ {
auto int j = 1; int j = 1;
{ {
auto int j= 2; int j= 2;
{ {
auto int j = 3; int j = 3;
printf ( " %d ", j); printf ( " %d ", j);
} }
printf ( "\t %d ",j); printf ( "\t %d ",j);
} }
printf( "%d\n", j); printf( "%d\n", j);
} }
OUTPUT: 3 2 1 OUTPUT: 3 2 1
Extern storage class is used when we have global functions or variables which are shared between two or
more files.
Keyword extern is used to declaring a global variable or function in another file to provide the reference
of variable or function which have been already defined in the original file.
C storage class is used to define the scope variables and function. There
are four various types of storage classes that are given below.
Table summarizes the principal features of each storage class which are commonly used in C programming
Structures:
• Defining a Structure,
•Declaring Structure Variables,
• Accessing Structure Members,
•Structure Initialization,
•Copying and Comparing Structure variables,
•Arrays of Structures,
•Arrays within Structures.
Defining a Structure
Structure is a user-defined data type in C programming language ,that combines logically related data
items of different data types together.

•Arrays allow to define type of variables that can hold several data items of the same kind.
Similarly structure is another user defined data type available in C that allows to combine data items
of different kinds.
•struct keyword is used to declare the structure in C.
•Variables inside the structure are called members of the structure.
Syntax: Examples:
struct struct_name struct employee struct student
{ { {
DataType member1_name; char name[50]; char name[60];
DataType member2_name; DataType int age; int roll_no;
member3_name; float salary; float marks;
… }; }
};
Declaring Structure Variables
Example1 :
struct student Name of the structure
{
char name[60];
int roll_no; members of the structure
float marks;
Declaring Structure variables
} s1,s2,s3….sn; s1,s2,s3….sn
at the time of definition
Example 2:
#include <stdio.h>
void main()
{
struct student
struct student s1,s2,s3........sn; // Declaring Structure variables
{ within a main function.
char name[60];
int roll_no;
float marks;
}; }
Defining a structure called “ student ” before the main function
Accessing Structure Members
How to access data members of a structure using a struct variable?

Using Dot(.) operator Example 2:


#include<stdio.h>
Example1 :
#include <stdio.h> struct Point
{
struct student int x, y;
{ };
char name[60];
int roll_no; int main()
float marks; {
} s1; struct Point p1 = {0, 1};

/*Assigning the values of each struct member here*/ // Accessing members of point p1
p1.x = 20;
s1. name = “ramesh”; P2.y=10;
s1. roll_no = 101; printf ("x = %d, y = %d", p1.x, p1.y);
s1. marks = 25.0
return 0;
int main()
#include <stdio.h> {
printf("Enter the following information:\n");
struct student
{ printf("Enter student name: ");
char name[60]; scanf( “%s”, s1.name)
int roll_no;
float marks; printf("Enter student roll number: ");
} s1; scanf("%d", & s1. roll_no);

printf("Enter students marks: ");


scanf("%f", & s1.marks);

printf("The information you have entered is: \n");

printf("Student name: %s \n” , s1.name);


printf("Student roll number: %d \n", s1. roll_no);
printf("Student marks: %f \n", s1.marks);
return 0;
}
Structure Initialization
#include<stdio.h> Example1 :

struct Point
{
int x, y, z;
};

int main()
{
// Examples of initialization

struct Point p1 = {10,20,30}; Structure member initialization


struct Point p2 = {20,40,60,60};

printf ("x = %d, y = %d, z = %d\n", p1.x, p1.y, p1.z);


printf ("x = %d, y = %d, z = %d\n", p2.x, p2.y, p2.z);
return 0;
}
#include <stdio.h> Example 2:
struct student
{
char name[60];
int roll_no;
float marks;
} s3={ “pavan”, 103, 25}; Structure member (S3) initialization

int main()
{
struct student s1 = { “ramesh”, 101, 23 }; Structure member (S1 and S2)
struct student s2 = { “suresh”, 102, 27 }; initialization
printf ("x = %s, y = %d, z = %f\n", s1.name, s1.roll_no, s1.marks);
printf ("x = %s, y = %d, z = %f\n", s2.name, s2.roll_no, s2.marks);

}
Copying and Comparing Structure variables

struct class Structure Definition


main()
Structure Declaration and Initialization {
{
int number;
int x;
char name[20];
struct class student1 = {111,"Ramesh",72.50};
float marks;
struct class student2 = {222,"Reddy", 67.00};
struct class student3;
};
student3 = student2; Copying Structure variables

x =((student3.number == student2.number) && (student3.marks == student2.marks)) ? 1 : 0;

if(x == 1) Comparing Structure variables


{
printf(“student2 and student3 are same\n", student3.number, student3.name, student3.marks);
}
else
{
printf(\"\\nstudent2 and student3 are different\\n\\n\");
}
}
Arrays of Structures

/* Array of Structures in C Initialization */ Example 1:

struct Employee
{
int age;
char name[10];
int salary;
} Employees[4] = { {25, "Suresh", 25000}, {24, "Tutorial", 28000}, {22, "Gateway", 35000}, {27, "Mike", 20000} };

Employees[0] ={25, "Suresh", 25000}; Employees[1] =


{24, "Tutorial", 28000}; Employees[2] = {22, "Gateway",
35000}; Employees[3] = {27, "Mike", 20000};
Example 2: void main()
{
Structure Definition
struct student S[4]; Arrays of Structures
struct student
{ S[4] = { {25, "Suresh", 25},
int age; {24, “Ramesh", 28}, Initialization members
char name[10]; {22, “Anoop", 35},
int marks; {27, “Arun", 20}
}; };

}
struct student
{ Structure Definition
int id;
char name[30];
float percentage;
int main() };
{
int i;
struct student record[2]; Array of Structure, Declaration

// 1st student's record


record[0].id=1;
strcpy(record[0].name, "Raju"); Initialization of members
record[0].percentage = 86.5;
Printing of Members
// 2nd student's record
record[1].id=2; for(i=0; i<3; i++)
strcpy(record[1].name, "Surendren"); {
record[1].percentage = 90.5; printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
// 3rd student's record printf(" Name is: %s \n", record[i].name);
record[2].id=3; printf(" Percentage is: %f\n\n",record[i].percentage);
strcpy(record[2].name, "Thiyagu"); }
record[2].percentage = 81.5; return 0;

} }
Thank you

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 42

You might also like