SlideShare uma empresa Scribd logo
1 de 39
FUNCTIONS
UNIT- IV
Fundamental of Computer
programming -206
By- Er. Indrajeet Sinha , +919509010997
CONTENTS: UNIT-IV
 Functions in C
 Passing Parameters, using returned data
 Passing arrays, passing characters and strings
 Passing structures, array of structures, pointer to structure
 The void pointer,
2
FUNCTIONS IN C
Lecture no.- 34,
UNIT- IV
By- Er. Indrajeet Sinha , +919509010997
4.1.1- INTRODUCTION TO MODULAR
PROGRAMMING
 Definition
A modular programming is the process of subdividing a
computer program into separate sub-programs.
 The benefits of using modular programming include:
 Less code has to be written.
 A single procedure can be developed for reuse,
eliminating the need to retype the code many times.
 Programs can be designed more easily because a small
team deals with only a small part of the entire code.
 Modular programming allows many programmers to
collaborate on the same application.
 The code is stored across multiple files.
 Code is short, simple and easy to understand.
4
By- Er. Indrajeet Sinha , +919509010997
4.1.2- FUNCTION DECLARATION,
CALLING AND DEFINITION
 Definition:-
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.
 Defining a Function
The general form of a function definition in C programming
language is as follows −
return_type function_name( parameter list )
{
body of the function ;
}
5
By- Er. Indrajeet Sinha , +919509010997
CONT…
 Here are 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.
 Parameters − 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.
6
By- Er. Indrajeet Sinha , +919509010997
 Example:
/* function returning the max between two numbers */
int max(int num1, int num2)
{ /* local variable declaration */
int result;
if (num1 > num2) result = num1;
else result = num2;
return result;
}
7
By- Er. Indrajeet Sinha , +919509010997
 Function Declarations
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 );
int max(int num1, int num2);
Parameter names are not important in function declaration only
their type is required, so the following is also a valid declaration
int max(int, int);
8
By- Er. Indrajeet Sinha , +919509010997
 Calling a Function
 While creating a C function, we give a definition of what the
function has to do. To use a function, we will have to call that
function to perform the defined task.
 When a program calls a function, the program control is
transferred to the called function. A called function performs
a defined task and when its return statement is executed or
when its function-ending closing brace is reached, it returns
the program control back to the main program.
 To call a function, we simply need to pass the required
parameters along with the function name, and if the function
returns a value, then we can store the returned value.
9
By- Er. Indrajeet Sinha , +919509010997
For example −
#include <stdio.h>
int max(int num1, int num2); /* function declaration */
int main ()
{ /* local variable definition */
int a = 100;
int b = 200;
int ret;
ret = max(a, b); /* calling a function to get max value */
printf( "Max value is : %dn", ret );
return 0;
} /* function returning the max between two numbers */
int max(int num1, int num2)
{ /* local variable declaration */
int result;
if (num1 > num2) result = num1;
else result = num2;
return result;
}
10
By- Er. Indrajeet Sinha , +919509010997
4.1.3 & -1.4 STANDARD LIBRARY &
USER DEFINE FUNCTIONS
C functions can be classified into two categories:-
 Library functions
 User-defined functions
11
By- Er. Indrajeet Sinha , +919509010997
 Definition:
 Library functions are those functions which are defined
by C library, example printf(), scanf(), strcat() etc. we
just need to include appropriate header files to use these
functions. These are already declared and defined in C
libraries.
 User-defined functions are those functions which are
defined by the user at the time of writing program.
Functions are made for code reusability and for saving
time and space.
12
PASSING PARAMETERS,
USING RETURNED DATA
Lecture no.- 35,
UNIT- IV
By- Er. Indrajeet Sinha , +919509010997
4.2.1 PARAMETER PASSING
MECHANISM
Definition:
What is Parameter ?
In computer programming, a parameter is a special kind of
variable, used in a subroutine to refer to one of the pieces of
data provided as input to the subroutine.These pieces of data
are called arguments.
Function With Parameter :
add(a,b);
Here Function add() is Called and 2 Parameters are Passed to
Function. a,b are two Parameters.
Function Call Without Passing Parameter :
Display();
14
By- Er. Indrajeet Sinha , +919509010997
15
PARAMETERS
Example:
Formal parameters
float ave(float a, float b) { return (a+b)/2.0; }
Actual parameters
ave(x, 10.0)
By- Er. Indrajeet Sinha , +919509010997
4.2.1.1- BY VALUE
Function Arguments
While calling a function, there are two ways in which
arguments can be passed to a function −
1. Call by value
2. Call by reference
The call by value method of passing arguments to a
function copies the actual value of an argument into the
formal parameter of the function. In this case, changes made
to the parameter inside the function have no effect on the
argument.
16
By- Er. Indrajeet Sinha , +919509010997
 Example:
Consider the function swap()definition as follows.
/* 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;
}
17
By- Er. Indrajeet Sinha , +919509010997
let us call the function swap() by passing actual values as in the
following example −
#include <stdio.h> /* function declaration */
void swap(int x, int y);
int main ()
{ /* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %dn", a );
printf("Before swap, value of b : %dn", b );
/* calling a function to swap the values */
swap(a, b);
printf("After swap, value of a : %dn", a );
printf("After swap, value of b : %dn", b );
return 0;
} 18
Output:-
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
Note:-It shows that there are no changes in the values, though they
had been changed inside the function.
By- Er. Indrajeet Sinha , +919509010997
4.2.1.2 BY REFERENCE
The call by reference method of passing arguments to a
function copies the address of an argument into the formal
parameter. Inside the function, the address is used to access
the actual argument used in the call. It means the changes
made to the parameter affect the passed argument.
Example:
/* function definition to swap the values */
void swap(int *x, int *y)
{
int temp; temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
19
By- Er. Indrajeet Sinha , +919509010997
#include <stdio.h> /* function declaration */
void swap(int *x, int *y);
int main ()
{ /* local variable definition */
int a = 100;
int b = 200;
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;
}
20
Note:-It shows that the change has reflected outside the function as well, unlike
call by value where the changes do not reflect outside the function.
Output:-
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
PASSING ARRAYS, PASSING
CHARACTERS AND
STRINGS
Lecture no.- 36,
UNIT- IV
By- Er. Indrajeet Sinha , +919509010997
4.3.1 PASSING ARRAY TO A
FUNCTION
 Whenever we need to pass a list of elements as argument to
the function, it is prefered to do so using an array. 
 Declaring Function with array in parameter list
22
By- Er. Indrajeet Sinha , +919509010997
EXAMPLE PASSING ARRAY
Function:
double getAverage(int arr[], int size)
{
int i; double avg;
double sum = 0;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = sum / size;
return avg;
}
23
By- Er. Indrajeet Sinha , +919509010997
 Now, let us call the above function as follows −
#include <stdio.h> /* function declaration */
double getAverage(int arr[], int size);
int main ()
{ /* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf( "Average value is: %f ", avg );
return 0;
} 24
Output:-
Average value is: 214.400000
By- Er. Indrajeet Sinha , +919509010997
4.3.3 PASSING STRINGS TO
FUNCTION Strings are just char arrays. So, they can be passed to a function
in a similar manner as arrays.
#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
gets(str);
displayString(str); // Passing string c to function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
25
By- Er. Indrajeet Sinha , +919509010997
4.3.4 PASSING POINTERS TO A
FUNCTION C programming allows passing a pointer to a function. To do
so, simply declare the function parameter as a pointer type.
#include <stdio.h>
#include <time.h>
void getSeconds(unsigned long *par);
int main ()
{
unsigned long sec; getSeconds( &sec );
/* print the actual value */
printf("Number of seconds: %ldn", sec );
return 0;
}
void getSeconds(unsigned long *par)
{ /* get the current number of seconds */
*par = time( NULL );
return;
}
26
Output:-
Number of seconds :1294450468
PASSING STRUCTURES, ARRAY OF
STRUCTURES, POINTER TO
STRUCTURES, THE VOID POINTER
Lecture no.- 37,
UNIT- IV
By- Er. Indrajeet Sinha , +919509010997
4.4.1 PASSING STRUCTURE TO
FUNCTION
 In C, structure can be passed to functions by two methods:
 Passing by value (passing actual value as argument)
 Passing by reference (passing address of an argument)
 Passing structure by value
 A structure variable can be passed to the function as an
argument as a normal variable.
 If structure is passed by value, changes made to the structure
variable inside the function definition does not reflect in the
originally passed structure variable.
28
By- Er. Indrajeet Sinha , +919509010997
 C program to create a structure student, containing name and
roll and display the information.
29
#include <stdio.h>
struct student
{
char name[50];
int roll;
};
void display(struct student stu); //
function prototype should be below to
the structure declaration otherwise
compiler shows error
int main()
{
struct student stud;
printf("Enter student's name: ");
scanf("%s", &stud.name);
printf("Enter roll number:");
scanf("%d", &stud.roll);
display(stud); // passing structure
variable stud as argument
return 0;
}
void display(struct student stu)
{
printf("OutputnName:
%s",stu.name);
printf("nRoll: %d",stu.roll);
}
Output:
Enter student's name: Kevin
Amla
Enter roll number: 149
Output
Name: Kevin Amla
Roll: 149
By- Er. Indrajeet Sinha , +919509010997
 Passing structure by reference
• The memory address of a structure variable is passed to
function while passing it by reference.
• If structure is passed by reference, changes made to the
structure variable inside function definition reflects in the
originally passed structure variable.
 C program to add two distances (feet-inch system)
and display the result without the return
statement.
30
By- Er. Indrajeet Sinha , +919509010997
#include <stdio.h>
struct distance
{
int feet; float inch;
};
void add(struct distance d1,struct
distance d2, struct distance *d3);
int main()
{
struct distance dist1, dist2, dist3;
printf("First distancen");
printf("Enter feet: ");
scanf("%d", &dist1.feet);
printf("Enter inch: ");
scanf("%f", &dist1.inch);
printf("Second distancen");
printf("Enter feet: ");
scanf("%d", &dist2.feet);
printf("Enter inch: ");
scanf("%f", &dist2.inch);
add(dist1, dist2, &dist3);
//passing structure variables dist1
and dist2 by value whereas
passing structure variable dist3 by
reference
printf("nSum of distances =
%d'-%.1f"", dist3.feet,
dist3.inch);
return 0;
}
….
…..
Cont… in next slide
31
By- Er. Indrajeet Sinha , +919509010997
 #include <stdio.h>
 struct distance
 {
 int feet; float inch;
 };
 void add(struct distance d1,struct distance d2,
struct distance *d3);
 int main()
 {
 struct distance dist1, dist2, dist3;
 printf("First distancen");
 printf("Enter feet: ");
32
By- Er. Indrajeet Sinha , +919509010997
void add(struct distance d1,struct distance d2, struct distance
*d3)
{
//Adding distances d1 and d2 and storing it in d3
d3->feet = d1.feet + d2.feet; d3->inch = d1.inch + d2.inch;
if (d3->inch >= 12)
{
/* if inch is greater or equal to 12, converting it to feet. */
d3->inch -= 12; ++d3->feet;
}
}
Output
First distance Enter feet: 12
Enter inch: 6.8
Second distance Enter feet: 5
Enter inch: 7.5
33
By- Er. Indrajeet Sinha , +919509010997
 In this program, structure variables dist1 and dist2 are passed
by value to the add function (because value
of dist1 and dist2 does not need to be displayed in main
function).
 But, dist3 is passed by reference ,i.e, address of dist3 (&dist3) is
passed as an argument.
 Due to this, the structure pointer variable d3 inside
the add function points to the address of dist3 from the
calling main function. So, any change made to the d3 variable is
seen in dist3 variable in main function.
34
By- Er. Indrajeet Sinha , +919509010997
4.4.4- VOID POINTER
 Void Pointers in C : Definition
 Suppose we have to declare integer pointer, character pointer
and float pointer then we need to declare 3 pointer variables.
 Instead of declaring different types of pointer variable it is
feasible to declare single pointer variable which can act as
integer pointer, character pointer.
 Void Pointer Basics :
 In C General Purpose Pointer is called as void Pointer.
 It does not have any data type associated with it
 It can store address of any type of variable
 A void pointer is a C convention for a raw address.
 The compiler has no idea what type of object a void Pointer
really points to ?
35
By- Er. Indrajeet Sinha , +919509010997
Declaration of Void Pointer :
void * pointer_name;
Void Pointer Example :
void *ptr; // ptr is declared as Void pointer
char cnum;
int inum;
float fnum;
ptr = &cnum; // ptr has address of character data
ptr = &inum; // ptr has address of integer data
ptr = &fnum; // ptr has address of float data 36
By- Er. Indrajeet Sinha , +919509010997
Explanation :
void *ptr;
Void pointer declaration is shown above.
We have declared 3 variables of integer, character and float type.
1. When we assign address of integer to the void pointer,
pointer will become Integer Pointer.
2. When we assign address of Character Data type to void
pointer it will become Character Pointer.
3. Similarly we can assign address of any data type to the
void pointer.
4. It is capable of storing address of any data type 37
By- Er. Indrajeet Sinha , +919509010997
 Summary : Void Pointer
38
Scenario Behavior
When We assign address of
integer variable to void pointer
Void Pointer Becomes Integer
Pointer
When We assign address of
character variable to void
pointer
Void Pointer Becomes
Character Pointer
When We assign address of
floating variable to void
pointer
Void Pointer Becomes Floating
Pointer
COMPUTER, NUMBER SYSTEM
UNIT- V
Fundamental of Computer
programming -206

Mais conteúdo relacionado

Mais procurados

Function in c language(defination and declaration)
Function in c language(defination and declaration)Function in c language(defination and declaration)
Function in c language(defination and declaration)VC Infotech
 
Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C ProgrammingShuvongkor Barman
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C v_jk
 
Functions
FunctionsFunctions
FunctionsOnline
 
Functions in C - Programming
Functions in C - Programming Functions in C - Programming
Functions in C - Programming GaurangVishnoi
 
Pointers and call by value, reference, address in C
Pointers and call by value, reference, address in CPointers and call by value, reference, address in C
Pointers and call by value, reference, address in CSyed Mustafa
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIADheeraj Kataria
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)Faizan Janjua
 

Mais procurados (18)

Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
Function in c language(defination and declaration)
Function in c language(defination and declaration)Function in c language(defination and declaration)
Function in c language(defination and declaration)
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Functions
FunctionsFunctions
Functions
 
Function in c
Function in cFunction in c
Function in c
 
Functions in C - Programming
Functions in C - Programming Functions in C - Programming
Functions in C - Programming
 
Pointers and call by value, reference, address in C
Pointers and call by value, reference, address in CPointers and call by value, reference, address in C
Pointers and call by value, reference, address in C
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
C# programs
C# programsC# programs
C# programs
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)
 

Destaque

file handling, dynamic memory allocation
file handling, dynamic memory allocationfile handling, dynamic memory allocation
file handling, dynamic memory allocationindra Kishor
 
Control Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, StructuresControl Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, Structuresindra Kishor
 
Unit v computer, number system
Unit  v computer, number systemUnit  v computer, number system
Unit v computer, number systemindra Kishor
 
Definition and parameter
Definition and parameterDefinition and parameter
Definition and parameterEncep Abdullah
 
Diapositiva de tecnologia de la informacion y comunicacion i
Diapositiva de tecnologia de la informacion y comunicacion iDiapositiva de tecnologia de la informacion y comunicacion i
Diapositiva de tecnologia de la informacion y comunicacion ijazmin Rijo
 
Thesis (J. Kyle Treman)
Thesis (J. Kyle Treman)Thesis (J. Kyle Treman)
Thesis (J. Kyle Treman)J. Kyle Treman
 
Radio Information Doc4
Radio Information Doc4Radio Information Doc4
Radio Information Doc4Jim Kent
 
Escenario socioeconomico
Escenario socioeconomicoEscenario socioeconomico
Escenario socioeconomicoAnel Sosa
 
EBOOK FOR RUNNING CPI - USING GOOGLE ADWORDS
EBOOK FOR RUNNING CPI - USING GOOGLE ADWORDS EBOOK FOR RUNNING CPI - USING GOOGLE ADWORDS
EBOOK FOR RUNNING CPI - USING GOOGLE ADWORDS QuynhDaoFtu
 
Pertamina Solusi Bahan Bakar Berkualitas dan Ramah Lingkungan
Pertamina Solusi Bahan Bakar Berkualitas dan Ramah LingkunganPertamina Solusi Bahan Bakar Berkualitas dan Ramah Lingkungan
Pertamina Solusi Bahan Bakar Berkualitas dan Ramah Lingkunganraden pabelan
 
Contoh Laporan Keuangan
Contoh Laporan KeuanganContoh Laporan Keuangan
Contoh Laporan KeuanganFerry Rinaldi
 
Hazard analysuis food packaging manufacturing(2)
Hazard analysuis  food packaging manufacturing(2)Hazard analysuis  food packaging manufacturing(2)
Hazard analysuis food packaging manufacturing(2)Tom Dunn
 
Food Safety and Flexible Packaging Material
Food Safety and Flexible Packaging MaterialFood Safety and Flexible Packaging Material
Food Safety and Flexible Packaging MaterialEric Tu
 
Inspection of CloudML Hyper Parameter Tuning
Inspection of CloudML Hyper Parameter TuningInspection of CloudML Hyper Parameter Tuning
Inspection of CloudML Hyper Parameter Tuningnagachika t
 
Overview on Azure Machine Learning
Overview on Azure Machine LearningOverview on Azure Machine Learning
Overview on Azure Machine LearningJames Serra
 

Destaque (20)

file handling, dynamic memory allocation
file handling, dynamic memory allocationfile handling, dynamic memory allocation
file handling, dynamic memory allocation
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Control Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, StructuresControl Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, Structures
 
Unit v computer, number system
Unit  v computer, number systemUnit  v computer, number system
Unit v computer, number system
 
Definition and parameter
Definition and parameterDefinition and parameter
Definition and parameter
 
General ev
General evGeneral ev
General ev
 
Diapositiva de tecnologia de la informacion y comunicacion i
Diapositiva de tecnologia de la informacion y comunicacion iDiapositiva de tecnologia de la informacion y comunicacion i
Diapositiva de tecnologia de la informacion y comunicacion i
 
Thesis (J. Kyle Treman)
Thesis (J. Kyle Treman)Thesis (J. Kyle Treman)
Thesis (J. Kyle Treman)
 
Liberatore_Resume
Liberatore_ResumeLiberatore_Resume
Liberatore_Resume
 
Radio Information Doc4
Radio Information Doc4Radio Information Doc4
Radio Information Doc4
 
2015 ATO Certs & Ops Specs
2015 ATO Certs & Ops Specs2015 ATO Certs & Ops Specs
2015 ATO Certs & Ops Specs
 
Escenario socioeconomico
Escenario socioeconomicoEscenario socioeconomico
Escenario socioeconomico
 
EBOOK FOR RUNNING CPI - USING GOOGLE ADWORDS
EBOOK FOR RUNNING CPI - USING GOOGLE ADWORDS EBOOK FOR RUNNING CPI - USING GOOGLE ADWORDS
EBOOK FOR RUNNING CPI - USING GOOGLE ADWORDS
 
Pertamina Solusi Bahan Bakar Berkualitas dan Ramah Lingkungan
Pertamina Solusi Bahan Bakar Berkualitas dan Ramah LingkunganPertamina Solusi Bahan Bakar Berkualitas dan Ramah Lingkungan
Pertamina Solusi Bahan Bakar Berkualitas dan Ramah Lingkungan
 
Contoh Laporan Keuangan
Contoh Laporan KeuanganContoh Laporan Keuangan
Contoh Laporan Keuangan
 
Hazard analysuis food packaging manufacturing(2)
Hazard analysuis  food packaging manufacturing(2)Hazard analysuis  food packaging manufacturing(2)
Hazard analysuis food packaging manufacturing(2)
 
Contoh proposal pli
Contoh proposal pliContoh proposal pli
Contoh proposal pli
 
Food Safety and Flexible Packaging Material
Food Safety and Flexible Packaging MaterialFood Safety and Flexible Packaging Material
Food Safety and Flexible Packaging Material
 
Inspection of CloudML Hyper Parameter Tuning
Inspection of CloudML Hyper Parameter TuningInspection of CloudML Hyper Parameter Tuning
Inspection of CloudML Hyper Parameter Tuning
 
Overview on Azure Machine Learning
Overview on Azure Machine LearningOverview on Azure Machine Learning
Overview on Azure Machine Learning
 

Semelhante a Unit iv functions

UNIT3.pptx
UNIT3.pptxUNIT3.pptx
UNIT3.pptxNagasaiT
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloadingankush_kumar
 
unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfJAVVAJI VENKATA RAO
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfTeshaleSiyum
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdfTeshaleSiyum
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxvekariyakashyap
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxSangeetaBorde3
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxGebruGetachew2
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfBoomBoomers
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxsangeeta borde
 

Semelhante a Unit iv functions (20)

UNIT3.pptx
UNIT3.pptxUNIT3.pptx
UNIT3.pptx
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdf
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
Function in c
Function in cFunction in c
Function in c
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
 
Cpp functions
Cpp functionsCpp functions
Cpp functions
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
Array Cont
Array ContArray Cont
Array Cont
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Functions
Functions Functions
Functions
 
C function
C functionC function
C function
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdf
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 

Último

PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiessarkmank1
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"mphochane1998
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARKOUSTAV SARKAR
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadhamedmustafa094
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...drmkjayanthikannan
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilVinayVitekari
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Call Girls Mumbai
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...Amil baba
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxmaisarahman1
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 

Último (20)

PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech Civil
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 

Unit iv functions

  • 1. FUNCTIONS UNIT- IV Fundamental of Computer programming -206
  • 2. By- Er. Indrajeet Sinha , +919509010997 CONTENTS: UNIT-IV  Functions in C  Passing Parameters, using returned data  Passing arrays, passing characters and strings  Passing structures, array of structures, pointer to structure  The void pointer, 2
  • 3. FUNCTIONS IN C Lecture no.- 34, UNIT- IV
  • 4. By- Er. Indrajeet Sinha , +919509010997 4.1.1- INTRODUCTION TO MODULAR PROGRAMMING  Definition A modular programming is the process of subdividing a computer program into separate sub-programs.  The benefits of using modular programming include:  Less code has to be written.  A single procedure can be developed for reuse, eliminating the need to retype the code many times.  Programs can be designed more easily because a small team deals with only a small part of the entire code.  Modular programming allows many programmers to collaborate on the same application.  The code is stored across multiple files.  Code is short, simple and easy to understand. 4
  • 5. By- Er. Indrajeet Sinha , +919509010997 4.1.2- FUNCTION DECLARATION, CALLING AND DEFINITION  Definition:- 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.  Defining a Function The general form of a function definition in C programming language is as follows − return_type function_name( parameter list ) { body of the function ; } 5
  • 6. By- Er. Indrajeet Sinha , +919509010997 CONT…  Here are 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.  Parameters − 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. 6
  • 7. By- Er. Indrajeet Sinha , +919509010997  Example: /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } 7
  • 8. By- Er. Indrajeet Sinha , +919509010997  Function Declarations 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 ); int max(int num1, int num2); Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration int max(int, int); 8
  • 9. By- Er. Indrajeet Sinha , +919509010997  Calling a Function  While creating a C function, we give a definition of what the function has to do. To use a function, we will have to call that function to perform the defined task.  When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.  To call a function, we simply need to pass the required parameters along with the function name, and if the function returns a value, then we can store the returned value. 9
  • 10. By- Er. Indrajeet Sinha , +919509010997 For example − #include <stdio.h> int max(int num1, int num2); /* function declaration */ int main () { /* local variable definition */ int a = 100; int b = 200; int ret; ret = max(a, b); /* calling a function to get max value */ printf( "Max value is : %dn", ret ); return 0; } /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } 10
  • 11. By- Er. Indrajeet Sinha , +919509010997 4.1.3 & -1.4 STANDARD LIBRARY & USER DEFINE FUNCTIONS C functions can be classified into two categories:-  Library functions  User-defined functions 11
  • 12. By- Er. Indrajeet Sinha , +919509010997  Definition:  Library functions are those functions which are defined by C library, example printf(), scanf(), strcat() etc. we just need to include appropriate header files to use these functions. These are already declared and defined in C libraries.  User-defined functions are those functions which are defined by the user at the time of writing program. Functions are made for code reusability and for saving time and space. 12
  • 13. PASSING PARAMETERS, USING RETURNED DATA Lecture no.- 35, UNIT- IV
  • 14. By- Er. Indrajeet Sinha , +919509010997 4.2.1 PARAMETER PASSING MECHANISM Definition: What is Parameter ? In computer programming, a parameter is a special kind of variable, used in a subroutine to refer to one of the pieces of data provided as input to the subroutine.These pieces of data are called arguments. Function With Parameter : add(a,b); Here Function add() is Called and 2 Parameters are Passed to Function. a,b are two Parameters. Function Call Without Passing Parameter : Display(); 14
  • 15. By- Er. Indrajeet Sinha , +919509010997 15 PARAMETERS Example: Formal parameters float ave(float a, float b) { return (a+b)/2.0; } Actual parameters ave(x, 10.0)
  • 16. By- Er. Indrajeet Sinha , +919509010997 4.2.1.1- BY VALUE Function Arguments While calling a function, there are two ways in which arguments can be passed to a function − 1. Call by value 2. Call by reference The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. 16
  • 17. By- Er. Indrajeet Sinha , +919509010997  Example: Consider the function swap()definition as follows. /* 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; } 17
  • 18. By- Er. Indrajeet Sinha , +919509010997 let us call the function swap() by passing actual values as in the following example − #include <stdio.h> /* function declaration */ void swap(int x, int y); int main () { /* local variable definition */ int a = 100; int b = 200; printf("Before swap, value of a : %dn", a ); printf("Before swap, value of b : %dn", b ); /* calling a function to swap the values */ swap(a, b); printf("After swap, value of a : %dn", a ); printf("After swap, value of b : %dn", b ); return 0; } 18 Output:- Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :100 After swap, value of b :200 Note:-It shows that there are no changes in the values, though they had been changed inside the function.
  • 19. By- Er. Indrajeet Sinha , +919509010997 4.2.1.2 BY REFERENCE The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument. Example: /* function definition to swap the values */ void swap(int *x, int *y) { int temp; temp = *x; /* save the value at address x */ *x = *y; /* put y into x */ *y = temp; /* put temp into y */ return; } 19
  • 20. By- Er. Indrajeet Sinha , +919509010997 #include <stdio.h> /* function declaration */ void swap(int *x, int *y); int main () { /* local variable definition */ int a = 100; int b = 200; 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; } 20 Note:-It shows that the change has reflected outside the function as well, unlike call by value where the changes do not reflect outside the function. Output:- Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :100 After swap, value of b :200
  • 21. PASSING ARRAYS, PASSING CHARACTERS AND STRINGS Lecture no.- 36, UNIT- IV
  • 22. By- Er. Indrajeet Sinha , +919509010997 4.3.1 PASSING ARRAY TO A FUNCTION  Whenever we need to pass a list of elements as argument to the function, it is prefered to do so using an array.   Declaring Function with array in parameter list 22
  • 23. By- Er. Indrajeet Sinha , +919509010997 EXAMPLE PASSING ARRAY Function: double getAverage(int arr[], int size) { int i; double avg; double sum = 0; for (i = 0; i < size; ++i) { sum += arr[i]; } avg = sum / size; return avg; } 23
  • 24. By- Er. Indrajeet Sinha , +919509010997  Now, let us call the above function as follows − #include <stdio.h> /* function declaration */ double getAverage(int arr[], int size); int main () { /* an int array with 5 elements */ int balance[5] = {1000, 2, 3, 17, 50}; double avg; /* pass pointer to the array as an argument */ avg = getAverage( balance, 5 ) ; /* output the returned value */ printf( "Average value is: %f ", avg ); return 0; } 24 Output:- Average value is: 214.400000
  • 25. By- Er. Indrajeet Sinha , +919509010997 4.3.3 PASSING STRINGS TO FUNCTION Strings are just char arrays. So, they can be passed to a function in a similar manner as arrays. #include <stdio.h> void displayString(char str[]); int main() { char str[50]; printf("Enter string: "); gets(str); displayString(str); // Passing string c to function. return 0; } void displayString(char str[]) { printf("String Output: "); puts(str); } 25
  • 26. By- Er. Indrajeet Sinha , +919509010997 4.3.4 PASSING POINTERS TO A FUNCTION C programming allows passing a pointer to a function. To do so, simply declare the function parameter as a pointer type. #include <stdio.h> #include <time.h> void getSeconds(unsigned long *par); int main () { unsigned long sec; getSeconds( &sec ); /* print the actual value */ printf("Number of seconds: %ldn", sec ); return 0; } void getSeconds(unsigned long *par) { /* get the current number of seconds */ *par = time( NULL ); return; } 26 Output:- Number of seconds :1294450468
  • 27. PASSING STRUCTURES, ARRAY OF STRUCTURES, POINTER TO STRUCTURES, THE VOID POINTER Lecture no.- 37, UNIT- IV
  • 28. By- Er. Indrajeet Sinha , +919509010997 4.4.1 PASSING STRUCTURE TO FUNCTION  In C, structure can be passed to functions by two methods:  Passing by value (passing actual value as argument)  Passing by reference (passing address of an argument)  Passing structure by value  A structure variable can be passed to the function as an argument as a normal variable.  If structure is passed by value, changes made to the structure variable inside the function definition does not reflect in the originally passed structure variable. 28
  • 29. By- Er. Indrajeet Sinha , +919509010997  C program to create a structure student, containing name and roll and display the information. 29 #include <stdio.h> struct student { char name[50]; int roll; }; void display(struct student stu); // function prototype should be below to the structure declaration otherwise compiler shows error int main() { struct student stud; printf("Enter student's name: "); scanf("%s", &stud.name); printf("Enter roll number:"); scanf("%d", &stud.roll); display(stud); // passing structure variable stud as argument return 0; } void display(struct student stu) { printf("OutputnName: %s",stu.name); printf("nRoll: %d",stu.roll); } Output: Enter student's name: Kevin Amla Enter roll number: 149 Output Name: Kevin Amla Roll: 149
  • 30. By- Er. Indrajeet Sinha , +919509010997  Passing structure by reference • The memory address of a structure variable is passed to function while passing it by reference. • If structure is passed by reference, changes made to the structure variable inside function definition reflects in the originally passed structure variable.  C program to add two distances (feet-inch system) and display the result without the return statement. 30
  • 31. By- Er. Indrajeet Sinha , +919509010997 #include <stdio.h> struct distance { int feet; float inch; }; void add(struct distance d1,struct distance d2, struct distance *d3); int main() { struct distance dist1, dist2, dist3; printf("First distancen"); printf("Enter feet: "); scanf("%d", &dist1.feet); printf("Enter inch: "); scanf("%f", &dist1.inch); printf("Second distancen"); printf("Enter feet: "); scanf("%d", &dist2.feet); printf("Enter inch: "); scanf("%f", &dist2.inch); add(dist1, dist2, &dist3); //passing structure variables dist1 and dist2 by value whereas passing structure variable dist3 by reference printf("nSum of distances = %d'-%.1f"", dist3.feet, dist3.inch); return 0; } …. ….. Cont… in next slide 31
  • 32. By- Er. Indrajeet Sinha , +919509010997  #include <stdio.h>  struct distance  {  int feet; float inch;  };  void add(struct distance d1,struct distance d2, struct distance *d3);  int main()  {  struct distance dist1, dist2, dist3;  printf("First distancen");  printf("Enter feet: "); 32
  • 33. By- Er. Indrajeet Sinha , +919509010997 void add(struct distance d1,struct distance d2, struct distance *d3) { //Adding distances d1 and d2 and storing it in d3 d3->feet = d1.feet + d2.feet; d3->inch = d1.inch + d2.inch; if (d3->inch >= 12) { /* if inch is greater or equal to 12, converting it to feet. */ d3->inch -= 12; ++d3->feet; } } Output First distance Enter feet: 12 Enter inch: 6.8 Second distance Enter feet: 5 Enter inch: 7.5 33
  • 34. By- Er. Indrajeet Sinha , +919509010997  In this program, structure variables dist1 and dist2 are passed by value to the add function (because value of dist1 and dist2 does not need to be displayed in main function).  But, dist3 is passed by reference ,i.e, address of dist3 (&dist3) is passed as an argument.  Due to this, the structure pointer variable d3 inside the add function points to the address of dist3 from the calling main function. So, any change made to the d3 variable is seen in dist3 variable in main function. 34
  • 35. By- Er. Indrajeet Sinha , +919509010997 4.4.4- VOID POINTER  Void Pointers in C : Definition  Suppose we have to declare integer pointer, character pointer and float pointer then we need to declare 3 pointer variables.  Instead of declaring different types of pointer variable it is feasible to declare single pointer variable which can act as integer pointer, character pointer.  Void Pointer Basics :  In C General Purpose Pointer is called as void Pointer.  It does not have any data type associated with it  It can store address of any type of variable  A void pointer is a C convention for a raw address.  The compiler has no idea what type of object a void Pointer really points to ? 35
  • 36. By- Er. Indrajeet Sinha , +919509010997 Declaration of Void Pointer : void * pointer_name; Void Pointer Example : void *ptr; // ptr is declared as Void pointer char cnum; int inum; float fnum; ptr = &cnum; // ptr has address of character data ptr = &inum; // ptr has address of integer data ptr = &fnum; // ptr has address of float data 36
  • 37. By- Er. Indrajeet Sinha , +919509010997 Explanation : void *ptr; Void pointer declaration is shown above. We have declared 3 variables of integer, character and float type. 1. When we assign address of integer to the void pointer, pointer will become Integer Pointer. 2. When we assign address of Character Data type to void pointer it will become Character Pointer. 3. Similarly we can assign address of any data type to the void pointer. 4. It is capable of storing address of any data type 37
  • 38. By- Er. Indrajeet Sinha , +919509010997  Summary : Void Pointer 38 Scenario Behavior When We assign address of integer variable to void pointer Void Pointer Becomes Integer Pointer When We assign address of character variable to void pointer Void Pointer Becomes Character Pointer When We assign address of floating variable to void pointer Void Pointer Becomes Floating Pointer
  • 39. COMPUTER, NUMBER SYSTEM UNIT- V Fundamental of Computer programming -206