0% found this document useful (0 votes)
17 views59 pages

CFP - Unit 5

This document covers the concepts of structures and functions in C programming. It explains the definition, declaration, and usage of structures to store dissimilar data types, as well as the definition, calling, and organization of functions within a C program. Key points include accessing structure members with the dot operator and the distinction between standard and user-defined functions.

Uploaded by

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

CFP - Unit 5

This document covers the concepts of structures and functions in C programming. It explains the definition, declaration, and usage of structures to store dissimilar data types, as well as the definition, calling, and organization of functions within a C program. Key points include accessing structure members with the dot operator and the distinction between standard and user-defined functions.

Uploaded by

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

COMPUTER FUNDAMENTALS AND PROGRAMMING

UNIT 5

STRUCTURE AND FUNCTIONS

By. Prof. N. D. Kapale


No.
Unit- of C
V Structure and Functions Ho Os
urs

Structure and Union:


Definition, Declaration of Structure,
Initialization, Declaration of Structure
Variables and Accessing Members.
C
Functions:Definition, 06
O5
Prototyping ,Function Call,Return
Statement, Call By Value and Call By
Reference, Standard Library Functions
and User Defined Functions.
Definition of Structure
 Why Use Structures :
 We have seen earlier how ordinary variables
can hold one piece of information and how arrays
can hold a number of pieces of information of the
same data type. These two data types can handle
a great variety of situations.
 But quite often we deal with entities that are
collection of dissimilar data types.
 For example, suppose you want to store data
about a book. You might want to store its name (a
string), its price (a float) and number of pages in it
(an int).
Continue….
 If data about say 3 such books is to be stored,
then we can follow two approaches:
a) Construct individual arrays, one for storing
names, another for storing prices and still
another for storing number of pages.
b) Use a structure variable.
Let us begin with a program that
uses arrays.
void main( )
{ char name[3] ;
float price[3] ;
int pages[3], i ;
printf ( "\n Enter names, prices and no. of pages of 3 books\n" )
;
for ( i = 0 ; i <= 2 ; i++ )
{ scanf ( "%c %f %d", &name[i], &price[i], &pages[i] );
}
printf ( "\n And this is what you entered\n" ) ;
for ( i = 0 ; i <= 2 ; i++ )
{ printf ( "%c %f %d\n", name[i], price[i], pages[i] );
}
}
Continue…..
And here is the sample run...
Enter names, prices and no. of pages of 3 books
A 100.00 354
C 256.50 682
F 233.70 512
And this is what you entered
A 100.000000 354
C 256.500000 682
F 233.700000 512
Continue….
 This approach allows you to store names,
prices and number of pages using arrays.
 The program becomes more difficult to handle
as the number of items relating to the book
go on increasing.
 For example, we would be required to use a
number of arrays, if we also decide to store
name of the publisher, date of purchase of
book, etc.
 To solve this problem, C provides a special
data type — the structure.
Continue…..
 A structure contains a number of data
types grouped together. These data
types may or may not be of the same
type.
 The following example illustrates the use of
this data type.
Continue…..
void main( )
{
struct book {
char name ; float price ; int pages ;
};
struct book b1, b2, b3 ;
printf ( "\nEnter names, prices & no. of pages of 3 books\n" ) ;
scanf ( "%c %f %d", &b1.name, &b1.price, &b1.pages ) ;
scanf ( "%c %f %d", &b2.name, &b2.price, &b2.pages ) ;
scanf ( "%c %f %d", &b3.name, &b3.price, &b3.pages ) ;
printf ( "\nAnd this is what you entered" ) ;
printf ( "\n%c %f %d", b1.name, b1.price, b1.pages ) ;
printf ( "\n%c %f %d", b2.name, b2.price, b2.pages ) ;
printf ( "\n%c %f %d", b3.name, b3.price, b3.pages ) ;
Continue…
And here is the output...
Enter names, prices and no. of pages of 3 books
A 100.00 354
C 256.50 682
F 233.70 512
And this is what you entered
A 100.000000 354
C 256.500000 682
F 233.700000 512
Continue…..
 This program demonstrates two fundamental
aspects of structures:
 declaration of a structure
 accessing of structure elements
 Let us now look at these concepts one by one.
Declaring a Structure
 In our example program, the following statement
declares the structure type:
struct book
{
char name ;
float price ;
int pages ;
};
 This statement defines a new data type called
struct book. Each variable of this data type will
consist of a character variable called name, a float
variable called price and an integer variable called
Continue….
 The general form of a structure declaration
statement is given below:
struct <structure name>
{
structure element 1 ;
structure element 2 ;
structure element 3 ;
...... ……
};
Continue….
 Once the new structure data type has been
defined one or more variables can be declared
to be of that type.
 For example the variables b1, b2, b3 can be
declared to be of the type struct book as,
 struct book b1, b2, b3 ;
 This statement sets space in memory. It
makes available space to hold all the
elements in the structure—in this case, 7
bytes—one for name, four for price and two
for pages.
Continue….
For example, We can combine the
struct book { declaration of the structure
char name ; type and the structure
variables in one statement.
float price ; struct book
int pages ; {
}; char name ;
struct book b1,
float price ;
b2, b3 ;
int pages ;
} b1, b2, b3 ;
Continue….
 Like primary variables and arrays, structure variables can
also be initialized where they are declared.
 The format used is quite similar to that used to initiate

arrays.
struct book
{
char name[10] ;
float price ;
int pages ;
};
struct book b1 = { "Basic", 130.00, 550 } ;
struct book b2 = { "Physics", 150.80, 800 } ;
Note the following points while declaring
a structure type:

a) The closing brace in the structure type


declaration must be followed by a semicolon.
b) It is important to understand that a
structure type declaration does not tell
the compiler to reserve any space in
memory. All a structure declaration
does is, it defines the “form” of the
structure.
c) Usually structure type declaration appears at
the top of the source code file, before any
variables or functions are defined.
Accessing Members of
structure
 Having declared the structure type and the
structure variables, let us see how the elements of
the structure can be accessed.
 Structure use a dot (.) operator.
 So to refer to pages of the structure defined in
sample program we have to use,
 b1.pages
 Similarly, to refer to price we would use,
 b1.price
 Note that before the dot there must always be a
structure variable and after the dot there must
always be a structure element. (structure
Lets C
void main( )
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b1 = { 'B', 130.00, 550 } ;
printf ( "\n Address of name = %u", &b1.name ) ;
printf ( "\n Address of price = %u", &b1.price ) ;
printf ( "\n Address of pages = %u", &b1.pages ) ;
OUTPUT
 Address of name = 65518
 Address of price = 65519
 Address of pages = 65523
 structure elements are stored in memory as
shown in the Figure
Array of Structures
/* Usage of an array of int i ;
structures */
for ( i = 0 ; i <= 99 ; i++ )
main( )
{
{
printf ( "\n Enter name, price &
struct book pages" ) ;
{ scanf ( "%c %f %d", &b[i].name,
char name ; &b[i].price, &b[i].pages ) ;
float price ; }
int pages ; for ( i = 0 ; i <= 99 ; i++ )
}; {
struct book b[100] ; printf ( "\n%c %f %d", b[i].name,
/* Array of Book b[i].price, b[i].pages ) ;
Summary
 A structure is usually used when we wish to
store dissimilar data together.
 Structure elements can be accessed through a
structure variable using a dot (.) operator.
 All elements of one structure variable can be
assigned to another structure variable using
the assignment (=) operator.
 It is possible to create an array of structures.
FUNCTION
Definition
 What is a Function?
 A function is a self-contained block of
statements that perform a coherent task of
some kind.
 Every C program can be thought of as a
collection of these functions.
 Using a function is something like hiring a
person to do a specific job for you.
Definition
 A large C program is divided into basic
building blocks called C function.
 Function contains set of instructions enclosed
by “{.... }” which performs specific operation
in a C program.
 Actually, Collection of these functions creates
a C program.
 Simple Definition : Function is a block of
code written to do a certain task.
Example
void main( )
{
message( ) ;
printf( "\n Cry, and you stop the monotony!" ) ;
}
message( )
{
printf( "\n Smile, and the world smiles with
you..." ) ;
}
Continue
 Here, main( ) itself is a function and through it we are
calling the function message( ).
 What do we mean when we say that main( ) ‘calls’the
function message( )?
 We mean that the control passes to the function
message( ).
 The activity of main( ) is temporarily suspended; it
falls asleep while the message( ) function wakes up
and goes to work.
 When the message( ) function runs out of statements
to execute, the control returns to main( ), which
comes to life again and begins executing its code at
the exact point where it left off
Lets C
 Thus, main( ) becomes the ‘calling’ function,
whereas message( ) becomes the
‘called’function. italy( )
void main( ) {
printf( "\n I am in italy" ) ;
{ }
printf( "\n I am in main" brazil(
); )
{ printf( "\n I am in brazil" )
italy( ) ; ;
brazil( ) ; }
argentina( )
argentina( ) ; {
} printf( "\n I am in
output
 I am in main
 I am in italy
 I am in brazil
 I am in argentina
Continue….
 Any C program contains at least one function.
 If a program contains only one function, it must be
main( ).
 If a C program contains more than one function, then
one (and only one) of these functions must be main( ),
because program execution always begins with main( ).
 There is no limit on the number of functions that might
be present in a C program.
 Each function in a program is called in the sequence
specified by the function calls in main( ).
 After each function has done its thing, control returns
to main( ). When main( ) runs out of function calls, the
program ends.
main( )
{
printf( "\n Iam in main" ) ;
italy( ) ;
printf( "\nI am finally back in main" ) ;
}
italy( )
{
printf( "\n I am in italy" ) ;
brazil( ) ;
printf( "\n I am back in italy" ) ;
}
brazil( )
{
printf( "\n I am in brazil" ) ;
argentina( ) ;
}
argentina( )
{
printf( "\nIam in argentina" ) ;
}
Continue

 C program is a collection of one or more


functions.
 A function gets called when the function name

is followed by a semicolon.
 For example,

main( ) {
argentina( ) ;
}
Continue
 A function is defined when function name is
followed by a pair of braces in which one or
more statements may be present.
 For example,

argentina( )
{
statement 1 ;
statement 2 ;
statement 3 ;
}
Continue
 Any function can be called from any other function.
Even main( ) can be called from other functions.
For example,
main( )
{
message( ) ;
}
message( )
{
printf( "\n Can't imagine life without C" ) ;
main( ) ;
A function can be called any number of
times.

For example,
main( )
{
message( ) ;
message( ) ;
}
message( )
{
printf( "\n Jewel Thief!!" ) ;
}
Function Order
 The order in which the functions are defined in a program and the
order in which they get called need not necessarily be same.
 For example,
void main( )
{
message1( ) ;
message2( ) ;
}
message2( )
{
printf( "\n But the butter was bitter" ) ;
}
message1( )
{
printf( "\n Mary bought some butter" ) ;
}
Continue
 Here, even though message1( ) is getting
called before message2( ), still, message1( )
has been defined after message2( ).
 However, it is advisable to define the
functions in the same order in which they are
called. This makes the program easier to
understand.
 A function can call itself. Such a process is
called ‘recursion’.
Continue
 A function can be called from other function, but a function
cannot be defined in another function.
 Thus, the following program code would be wrong, since

argentina( ) is being defined inside another function, main( ).


 See example :

main( )
{
printf( "\nIam in main" ) ;
argentina( )
{
printf( "\nIam in argentina" ) ;
}
}
Continue
 There are basically two types of functions:
1. Standard Functions / Built-in Functions or
Library functions
 Defined in C programming Libraries/Header Files
,
 Ex. printf( ), scanf( ) etc.
2. User-defined functions
 User can define functions in C program as per
his/her need .
 E.g. to draw a circle , user can define c function
as drawcircle()
Three Aspects of
Function
 Function Declaration, Function Call and Function
Definition
 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.
Functions Aspects Syntax
Function Declaration return type function_name (argument list);
Function Call function_name (arguments list);
Function Definition return_type function_name (arguments
list) {
Body of function; }
Why Use Functions?
 Why write separate functions at all?
 Why not squeeze the entire logic into one function,
main( )?
 Two reasons:
1. Writing functions avoids rewriting the same code over
and over. Suppose you have a section of code in your
program that calculates area of a triangle. If later in
the program you want to calculate the area of a
different triangle, you won’t like it if you are required
to write the same instructions all over again. Instead,
you would prefer to jump to a ‘section of code’ that
calculates area and then jump back to the place from
where you left off. This section of code is nothing but
Continue….
2. Using functions it becomes easier to write programs
and keep track of what they are doing. If the operation
of a program can be divided into separate activities,
and each activity placed in a different function, then
each could be written and checked more or less
independently. Separating the code into modular
functions also makes the program easier to design
and understand
3. The core concept of C functions are:
 Re-usability,

 Dividing a big task into small pieces to achieve the

functionality &
 To improve understandability of very large C
Example
#include<stdio.h> /*Program illustrates function aspects */
float squareNo( floatx );/*function Prototype, also
called function Declaration*/
void main( )/* main function, program starts from
here*/
{
float m, n ;
printf( "\nEnter some number for finding square \n");
scanf( "%f", &m ) ;
n = squareNo( m ) ;/*Function Call*/
printf( "\n Square of the given number %f is %f",m,n);
getch( );
}
float squareNo( floatx )/* function
Definition*/
{
float p ;
p=x*x;
return( p ) ;
}
Continue
 There are two ways that a C function can be
called from a program. They are,
1. Call by Value

2. Call by Reference
Call by Value
 In call by value method, the value of the variable
is passed to the function as parameter.
 The value of the actual parameter can not be
modified by formal parameter.
 Different Memory is allocated for both actual and
formal parameters. Because, value of actual
parameter is copied to formal parameter.
 Note:
 Actual parameter :- This is the argument which is
used in function call.
 Formal parameter:- This is the argument which is
used in function definition
EXAMPLE :
 USING CALL BY VALUE In this program, the
values of the variables “m” and “n” are
passed to the function “swap”. These values
are copied to formal parameters “a” and “b”
in swap function and used.
SWAPPING
#include<stdio.h>
void swap(inta, intb);/ *function Prototype, also called function
Declaration*/
void main()
{
int m = 22, n = 44;
printf(“ \n values before swap: %d %d", m, n);
swap(m, n);/*calling function by value*/
getch();
}
void swap(int a, int b) /*Function Definition*/
{
int tmp;
tmp= a;
a = b;
b = tmp;
printf(" \n values after swap : %d %d", a, b);
Call by Reference
 In call by reference method, the address of
the variable is passed to the function as
parameter.
 The value of the actual parameter can be
modified by formal parameter.
 Same memory is used for both actual and
formal parameters since only address is used
by both parameters
EXAMPLE
 USING CALL BY REFERENCE In this program,
the address of the variables “m” and “n” are
passed to the function “swap”

 These values are not copied to formal


parameters “a” and “b” in swap function.
Because, they are just holding the address of
those variables. This address is used to access
and change the values of the variables.
Lets C
#include<stdio.h>
void swap(int*a, int*b); /*function Prototype, also called function Declaration*/
void main()
{
int m = 22, n = 44;
printf(“ Values before swap %d %d",m, n);
swap(&m, &n);/*calling function by Reference*/
getch();
}
void swap(int*a, int*b) /*Function Definition */
{
int tmp;
tmp= *a;
*a = *b;
*b = tmp;
printf("\n values after swap = %d %d", *a, *b);
}
Passing Values between Functions

/* Sending and receiving values between functions */


main( )
{
int a, b, c, sum ;
printf( "\nEnterany three numbers " ) ;
scanf( "%d %d %d", &a, &b, &c ) ;
sum = calsum( a, b, c ) ;
printf( "\nSum= %d", sum ) ;
}
calsum( x, y, z )
intx, y, z ;
{
int d ;
d=x+y+z;
return ( d ) ;
Continue
 In this program, from the function main( ) the values of a,
b and c are passed on to the function calsum( ), by making
a call to the function calsum( ) and mentioning a, b and c
in the parentheses:
 sum = calsum( a, b, c ) ;
 In the calsum( ) function these values get collected in
three variables x, y and z:
 calsum( x, y, z )
 Int x, y, z ;
 The variables a, b and c are called ‘actual arguments’,
whereas the variables x, y and z are called ‘formal
arguments’. Any number of arguments can be passed to a
function being called. However, the type, order and
number of the actual and formal arguments must always
Continue
 There are two methods of declaring the formal
arguments.
 The one that we have used in our program is
known as Kernighan and Ritchie (or just K & R)
method.
 calsum( x, y, z )
 int x, y, z ;
 Another method is,
 calsum( intx, inty, intz )
 This method is called ANSI method and is
more commonly used these days.
Continue
 There is no restriction on the number of return statements that
may be present in a function.
 Also, the return statement need not always be present at the end

of the called function.


 The following program illustrates these facts.

fun( )
{
char ch;
printf( "\n Enter any alphabet " ) ;
scanf( "%c", &ch) ;
if ( ch>= 65 && ch<= 90 )
return ( ch) ;
else
return ( ch+ 32 ) ;
Continue
 All the following are valid return statements.
return ( a ) ;
return ( 23 ) ;
return ( 12.34 ) ;
return ;
 In the last statement a garbage value is returned to the calling
function since we are not returning any specific value.
 If we want that a called function should not return any value, in
that case, we must mention so by using the keyword void as
shown below.
void display( )
{
printf( "\n Heads I win..." ) ;
printf( "\n Tails you lose" ) ;
Continue
 A function can return only one value at a time.
 Thus, the following statements are invalid.

return ( a, b ) ;
return ( x, 12 ) ;
Continue
 If the value of a formal argument is changed in the called function,
the corresponding change does not take place in the calling
function.
main()
{ OUTPUT:
inta=30; 60
fun(a); 30
printf("\n%d",a);
}
fun(intb)
{
b=60;
printf("\n%d",b);
THANK YOU

You might also like