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

C Unit 4

The document discusses user-defined functions in C programming. It covers the need for functions, elements of functions including definition, declaration, and calls, and return values and their types. Examples are provided to illustrate function definitions and calls.

Uploaded by

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

C Unit 4

The document discusses user-defined functions in C programming. It covers the need for functions, elements of functions including definition, declaration, and calls, and return values and their types. Examples are provided to illustrate function definitions and calls.

Uploaded by

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

UNIT – IV

User-Defined Functions: Introduction – Need and Elements of User-Defined Functions-


Definition-Return Values and their types - Function Calls – Declarations – Category of
Functions- Nesting of Functions - Recursion – Passing Arrays and Strings to Functions - The
Scope, Visibility and Lifetime of Variables- Multi file Programs. Structures and Unions

USER DEFINED FUNCTIONS Introduction


C functions can be classified into two categories, namely, library functions and userdefined
functions. Main is an example of user-defined functions, printf and scanf belong tothe category of library
functions. The main difference between these two categories is that library functions are not required to be
written by us whereas a user-defined function has tobe developed by the user at the time of writing the
program.

NEED FOR USER-DEFINED FUNCTIONS


Every program must have a main function to indicate where the program has to begin its
execution.The program may become too large and complex as a result of debugging,testing and
maintaining.
If a program is divided into finctional parts,then it will be independently coded and later combined
into a single unit.The independently coded programs are called subprograms. Such subprograms are
referred to as ‘functions’.
This “division” approach has number of advantages.
 It facilitates top-down modular programming.
• The length of the source program can be reduced by using functions at  appropriate places.
• It is easy to locate and isolate a faulty function for further investigations.
• A function can be used by many other programs
In order to make use of a user-defined functions,we need to establish three elements that are
related to

Use of a function
If we want to perform a task repetitively, then it is not necessary to rewrite the
particular block of the program again and again. We can shift the particular block of
statements in a user defined function and we can call the function, when needed. Using
functions large program can be reduced to smaller ones. It is easy to debug and find out the
errors in it. It also increases the readability.

Example:
printline()
{
int a;
for(a=1;a<40;a++)
printf(“*”);
printf(“\n”);
}
This example defines a function called printline that prints a line of 40 characters. The
function is used in main as follows.

Example:
printline()
{
int a;
for(a=1;a<40;a++)
printf(“*”);
printf(“\n”);
}
This example defines a function called printline that prints a line of 40 characters. The
function is used in main as follows.
main()
{
printline();
printf(“Use of C functions”);
printline();

OUTPUT
Use of C functions

**************************************
Need for functions:
1. To reduce the length of the program.
2. To reduce the complexity of program.
3. Easy to debug, test and maintain.
4. To call the function wherever it is needed.

ELEMENTS OF USER-DEFINED FUNCTIONS


Functions are classified as one of the derived data types in C.
• Both functions names and variable names are considered identifiers and therefore they
must adhere to the rules for identifiers.
• Like variables, functions have types associated with them.
• Like variables, functions names and their types must be declared and defined before they
are used in a program.
In order to make use of a user-defined function,there are three elements that are related to
functions.
1. Function definition.
2. Function call.
3. Function declaration.
The function definition is an independent program module that is specially
written to implement the requirements of the function.
In order to use this function we need to invoke it at a required place in the
program.This is known as the function call.
The program that calls the function is referred to as the calling program or calling
function.
The calling program should declare any function that is said to be used as the
function declaration or function prototype.

FUNCTION DEFINITION
A function definition, also known as function implementation shall include the following
elements,
1. Function name;
2. Function type;
3. List of parameters;
4. Local variable declarations; 5. Function statements;and
6. A return statement.
All the six elements are grouped into two parts namely,
• function header
• function body

Function can be declared as per the format given below

Syntax:

function_ type function-name(parameter list)


{
local variable declarations;
executable statement1; executable
statement2;
-------------------------
------------------------
return(statement);
}

The first line function_ type function-name(parameter list) is known as the function header
and the statements within the opening and closing braces constitute the function body. Function
header
The function header consists of three parts:
1. function type
2. function name
3. formal parameter list

Name and Type


The function type specifies the type of value like float, that the function is expected to return to
the program calling the function.
The function name is any valid C identifier and must follow the same rules of formation as
other variable names in C.

Formal parameter list


The parameter list declares the variables that will receive the data sent by the calling
program. They serve as input data to the function to carry out the specified task. Since
they represent actual input values, they are often referred to as formal parameters.

float quadratic ( int a, int b, int c )


{
……….
}

double power ( double x, int n )


{
……….
}

float mul ( double x, int n )


{
……….
}

int sum ( int a, int b)


{
……….
}

To indicate parameter list is empty,the keyword void must be used between the paranthesis as in
void printline(void)
{
……….
}

Many compilers accept an empty set of parentheses,without specifying anything as in

void printline( )

It is a good practice to use void to indicate a nill parameter list.

Function body
The function body contains the declarations and statements necessary for performing the
required task.
1. Local declarations that specify the variables needed by the
function.
2. Function statements that perform the task of the function.
3. A return statement that returns the value evaluated by the function.
Some examples of typical function definitions are:

(a) float mul ( float x, float y )


{
float result; result = x * y;
return (result);
}

(b) void sum( int a, int b )


{
printf (“sum = %s”, a+b );
return;
}

(c) void display( void)


{
printf (“No type, no parameters”);
}

RETURN VALUES AND THEIR TYPES


In C/C++, return exp; (where exp is an expression) is a statement that tells a function to return
execution of the program to the calling function, and report the value of exp. If a function has the
return type void, the return statement can be used without a value, in which case the program just
breaks out of the current function and returns to the calling one.
return;
or
return(expression);

In Pascal there is no return statement. A subroutine automatically returns when execution reaches
its last executable statement. Values may be returned by assigning to an identifier that has the same
name as the subroutine, a function in Pascal terminology. This way the function identifier is used
for recursive calls and as result holder; this is syntactically similar to an explicit output parameter
An example of use of simple return statement as follows:
if ( error )
return;
The second form of return with an expression returns the value of the expression. For example, the
function

int mul ( int x, int y )


{
int result; result = x
* y;
return (result);
}
The situation arises when the value returned is based on certain conditions. For example :
if (x <= 0 ) return(0);
else
return(1);
Functions that return values
One of the most useful forms of function is one that returns a value that is a function of its
parameters. In this case the type given to the function is that of the value to be returned. Thus
consider the function, previously considered, which given the co-ordinates of a point (x,y) will
return its distance from the origin:
float distance(float x, float y)
// Returns the distance of (x, y) from origin
{
float dist; //local variable
dist = sqrt(x * x + y * y);
return dist;
}
The function prototype for this function is:
float distance(float, float); // function prototype
This function introduces several new features. Note the following:
• The function has been given the type float because it is going to return a float value.
• The parameter-list now has two parameters, namely, x and y. Each parameter is
declared by giving its type and name and successive parameter declarations are
separated by a comma.
• A local variable dist has been declared to temporarily hold the calculated distance.
• Because this function returns a value it includes a return statement which returns the
value. In a statement return value the value may be a constant, a variable or an
expression. Hence the use of the local variable dist was not essential since the return
statement could have been written:
• return sqrt(x*x + y*y);
When the function is called the formal parameters x and y are replaced by actual parameters of
type float and in the same order, i.e. the x co-ordinate first. Since the function returns a value it
can only be used in an expression.

FUNCTION CALLS
A function can be called by simply using the function name in a statement. When
the function encounters a function call, the control is transferred to the called function.
Then the function is then executed line by line as described and the value is returned when
a return statement is encountered.
Example 1:
main( )
{
int y ;
y = mul ( 10, 5 );
printf(“%d\n”, y);
}

When the compiler encounters a function call, the control is transferred to the function
mul( ).This function is then executed line by line.
main ( )
{
int y ;
y = mul (10, 5);
……….
}

int mul(int x, int y)

Int p;

p=x * y;

The function calls sends two integer values 10 and 5 to the function.

Example 2:
main( )
{
int p;
p=add(10,15);
printf(“%d”,p);
}
int add(int a, int b)
{
int c;
c=a+b;
return( c );
}
In the above example, the function is called using the function name add and
passing the values (10,5). Thus after encountering the function call, the control is
transferred to the called function add and it is executed.
There if it encounters the return statement then the control is transferred to main
function.

Working of functions
Actual argument
The arguments of calling function are actual arguments In
the above example, ‘x’ , ‘y’ and ‘z’ are actual arguments.

main()
{
_______
_______
abc(x,y,z); Function call

Actual argument
_______
_______
}

abc(l,k,j) Function definition


{
Formal argument

________
________
return();
}

Formal arguments
The arguments of called function are formal arguments. In
the above example, ‘l’ , ‘k’ and ‘j’ are formal arguments.

Function name
Here, ‘abc’ is a function name.
Argument list
Variable names enclosed within parenthesis are called
argument list. Function call
A function can be called by its name, terminated by a semicolon.
Example
function fact (int n1)
{
int f1; for(i
=1;i<=n1;i++)
f1=f1*i; return(f1);
}

Suppose if the return type is integer then there is no need to mention about the
return type in the function definition as well as in the proto type. If the function returns
non integer value then there is need for explicit specification about the return type. The
return statement is used to return a value to the calling function. It takes the following
form

Return Or

return(expression);

FUNCTION DECLARATION
Functions and Variables:
Each function behaves the same way as C language standard function main(). So a
function will have its own local variables defined. In the above example total variable is local to
the function Demo.
A global variable can be accessed in any function in similar way it is accessed in main()
function.
Declaration and Definition
When a function is defined at any place in the program then it is called function definition. At the
time of definition of a function actual logic is implemented with-in the function.
1. A function declaration does not have any body and they just have their interfaces.
2. A function declaration is usually declared at the top of a C source file, or in a separate
header file.
A function declaration is sometime called function prototype or function signature. For the above
Demo() function which returns an integer, and takes two parameters a function declaration will
be as follows:
int Demo( int par1, int par2);
A function declaration are also known as function prototype consists of four parts.
• Function type(return type)
• Function name
• Parameter list
• Terminating semicolon.
They are coded in the following format:
Function – type function name (parameter list); Example:
Int mul (int m,int n);/* Function prototype */
A function prototype or function interface in C or C++ is a declaration of a function
that omits the function body but does specify the function's return type, name and argument
types. While a function definition specifies what a function does, a function prototype can be
thought of as specifying its interface.
In a prototype, argument names are optional (and have function prototype scope, meaning
they go out of scope at the end of the prototype), however, the type is necessary along with all
modifiers (e.g. if it is a pointer or a const argument).
Different forms of declarations are:
Int mul (int , int );
mul ( int a , int b );
mul (int , int );
Consider the following function prototype:
int fac(int n);
This prototype specifies that in this program, there is a function named "fac" which takes
a single integer argument "n" and returns an integer. Elsewhere in the program a function
definition must be provided if one wishes to use this function. It's important to be aware that a
declaration of a function does not need to include a prototype.
The following is a prototype-less function declaration, which just declares the function
name and its return type, but doesn't tell what parameter types the definition expects.
double fac()
In C, if a function is not previously declared and its name occurs in an expression
followed by a left parenthesis, it is implicitly declared as a function that returns an int and nothing
is assumed about its arguments. In this case the compiler will not be able to perform compile-
time checking of argument types and arity when the function is applied to some arguments. This
can cause problems. The following code illustrates a situation in which the behavior of an
implicitly declared function is undefined.
#include <stdio.h>

int fac(int n); /* Prototype */

int main(void) { /* Calling function */


printf("%d\n", fac()); /* Error: forgot argument to fac */
return 0;
}

int fac(int n) { /* Called function definition */


if (n == 0)
return 1;
else
return n * fac(n - 1);
}
The function fac expects an integer argument to be on the stack or in a register when it is
called. If the prototype is omitted, the compiler will have no way of enforcing this and fac will
end up operating on some other datum on the stack (possibly a return address or the value of a
variable that is currently not in scope).
Local and Global variables
There are 2 kinds of declarations.
1. Above all the functions.
2. Inside a function definition

Global prototype
The declaration above all the functions, the prototype is referred to as lobal prototype.

Local prototype
When we place it in a function definition are called local prototype. Multiple functions
can use them.

Local variables: Global variables:

Can be accessed only in the function where it Can be accessed by all the functions in the
has been declared. program.
Needs to be declared inside the function where it is Needs to be declared in the global
to be used. declaration section outside all programs.
Can be used by many functions and so are
Variables are secure.
not secure.
Stored in separate locations , so accessing will
Stored in one location, so any function
change the value only in the function where it’s
accessing can change its value.
used.

Example:
int m;
main( )
{
int i;
float balance;
……..
…..
function1( );
}
function1( )
{
int i;
float sum;
……
……
}

In the above example, variable m is a global variable and can be accessed anywhere in the
program where as variable i is a local variable and should be accessed only in the function in
which it is declared. The variables balance and sum are local variables and can be accessed in
the functions main and function1 respectively.

CATEGORIES OF FUNCTIONS
Depending on whether the argument is present or not and whether a value is returned or
not, may belong to one of the following categories.
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
4. Functions with no arguments and return values.
5. Functions that return multiple values.

No Arguments and no return values:

When a function has no arguments, it does not receive any data from the calling function.
Similarly, when it does not return a value, the calling function does not receive any data from the
called function.
So there is only a transfer of control between the calling and the called function, but not
a data transfer.
Example:
/* addition of two numbers*/
#include<stdio.h>
main( )
{
add ( );
}

/* function definition*/
add()
{
int a,b;
a=a+b;
printf(“%d”,a);
return(0);
}
Example:
/* addition of two numbers*/
#include<stdio.h>
main( )
{
add ( );
}

/* function definition*/
add()
{
int a,b;
a=a+b;
printf(“%d”,a);
return(0);
}

With Arguments but no return values:


In the previous category there is no data communication
between the functions. So this approach is not better. To make it efficiently we could make the
calling function to read data from the terminal and pass it on to the called function. The nature of
data communication between the calling function and the called function is with arguments but
no return values.
Example:
/* addition of two numbers*/
#include<stdio.h>
main( )
{
int a=2,b=3;
add (a,b);
} Actual

/* function definition*/
add(int a1,int b1)
{ Formal
a1=a1+b1;
printf(“%d”,a1); return;
}

 The arguments that we are using in the main function are called actual arguments. 
The arguments that we are using in the called function instead of the actual arguments
are called as formal arguments.
When a function call is made, only a copy of the values of
actual arguments is passed into the called function. Changes inside the function will have no
effect on variables used in the actual argument list.

With Arguments and return values:


In the previous category the calling function sends some data to the called function, but
the called function does not return anything to the calling function. So it is like one-way
communication. To make it more effective, both send and receive data in this category. If there is
any change of values in called function, it has to be shown in the main function also.

Example:
/* addition of two numbers*/
#include<stdio.h>
main( )
{
int a,b,c;
c=add (a,b);
printf(“%d”,c);
getch();
}
/* function definition*/
add(int a1,int b1)
{
a1=a1+b1; return(a1); }

Example:
/* addition of two numbers*/
#include<stdio.h>
main( )
{
int a,b,c;
c=add (a,b);
printf(“%d”,c);
getch();
}
/* function definition*/
add(int a1,int b1)
{
a1=a1+b1;
return(a1);
}

With no arguments and return values:


We may need a function which does not take any argument but only returns values to the
calling function then this type of function is useful. The best example of this type of function is
“getchar()” library function which is declared in the header file “stdio.h”. We can declare a
similar library function of own.

Example:

/*C program to check whether a number entered by user is prime or not using function
with no arguments and no return value*/
#include<stdio.h> void prime(); int main(){
prime();//No argument is passed to prime().
return0; }
void prime(){
/* There is no return value to calling function main(). Hence, return type of prime() is
void */ int num,i,flag=0;
printf("Enter positive integer enter to check:\n");
scanf("%d",&num); for(i=2;i<=num/2;++i){
if(num%i==0){
flag=1;
}
}
if(flag==1)
printf("%d is not prime",num);
else
printf("%d is prime",num);
}

Function prime() is used for asking user a input, check for whether it is prime of not
and display it accordingly. No argument is passed and returned form prime() function.
Functions that return multiple values:
A return statement can return only one value.We have used arguments to send values to
the called function, in the same way we can also use arguments to send back information to the
calling function. The arguments that are used to send back data are called Output Parameters.
The mechanism of sending back information through arguments are known as address
operator ( &) and indirection operator ( * ). We can get memory address of any variable by
simply placing “&” before variable name.
In the same way we get value stored at specific memory location by using “*” just before
memory address Example 1 :
#include <stdio.h> void
doubleit(int &x, int &y){ x
*= 2; y *= 2;
}

int main(void){ int


x = 10;
int y = 5;

doubleit(x,y);

printf("%i %i",x,y);

return 0;
}

Example 2:
#include<stdio.h>
#include<conio.h>

void calc(int x, int y, int *add, int *sub) {


*add = x+y;
*sub = x-y;
}
void main()
{ int a=20,
b=11, p,q; clrscr();
calc(a,b,&p,&q);
printf("Sum = %d, Sub =
%d",p,q); getch(); } Output:
Sum = 31 , Sub = 9

Explanation: “Calc()” function has four arguments, first two arguments need no
explanation. Last two arguments are integer pointer which works as output parameters
(arguments). Pointer can only store address of the value rather than value but when we add
* to pointer variable then we can store value at that address.
When we call function “calc()” in the line no. 14 then following assignments
occurs. Value of variable “a” is assigned to “x”, value of variable “b” is assigned to “y”,
address of “p” and “q” to “add” and “sub” respectively. In line no. 6 and 7 we are adding
and subtracting values and storing the result at their respective memory location.

Call by value and Reference


Thereare 2 ways in which we can pass arguments to the function.
Call by value
• Values of actual arguments are passed to the formal arguments and the
operation is done on the formal arguments.
• Any change made in the formal argument does not affect the actual
arguments.

Example
/* swapping of two numbers*/
#include<stdio.h>
main( )
{
int a=3,b=4;
swap(a, b);
printf(“In main”);
printf(“a=%d, b=%d”, a, b);
getch();
}
/* function definition*/
swap(int a, int b)
{
int t;
t=a;
a=b; b=t;
printf(“In function swap”);
printf(“a=%d, b=%d”, a, b)
}

OUTPUT
In function
swap a=4, b=3
In main
a=3, b=4

Call by Reference
• Instead of passing value, addresses are passed.
• Function operates on addresses rather than values.
• Any change made in the formal argument will affect the actual arguments.
Example
/* swapping of two numbers*/
#include<stdio.h>
main( )
{
int a=3,b=4;
swap(&a, &b);
printf(“In main”);
printf(“a=%d, b=%d”, a, b);
getch();
}

/* function definition*/
swap(int *a, int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
printf(“In function swap”);
printf(“a=%d, b=%d”, a, b)
}

OUTPUT
In function
swap a=4, b=3
In main
a=4, b=3
Functions with arrays:
Like the values of simple variables, it is also possible to pass the values of an array
to a function. To pass an array to a called function, it is enough to list the name of the
array, without any subscripts and the size of the array as arguments.
Example:
Lar(a,n);

Array size of the array


Name

/* program to find smallest element among given set of elements*/


#include<stdio.h>
main() {
float smallest(float,int);
static float a[5]={1.0 , 4.0 , 50.34 , 60.3 , 1.0};
printf(“%f”,smallest(a,5));
}

/* function definition*/ float


smallest (float a[], int m)
{
int i; float
small;
small=a[0];
for(i=1;i<m;i++)
if (a[i]<small)
small=a[i];
return(small);
}

NESTING OF FUNCTION
C permits nesting of functions.Calling any function inside another function call is known
as nesting function call. Sometime it converts a difficult program in easy one.
Try to find out maximum number among the five different integers without using nested function
call.

Example 1:
int max(int x,int y){return x>y?x:y;}
void main(){
int m;

m=max(max(4,max(11,6)),max(10,5));
printf("%d",m); getch();
}

Output: 11

Example 2:
//program to calculate a / b-c
#include<stdio.h> main()
{
float a,b,c,res;
scanf(“%f%f
%f”.&a,&b,&c);
res=result(a,b,c);
if(res==0)
printf(“cannot calculate ratio since denominator= 0”);
else
printf(“ratio - %f”,res);
}
//module that returns the value of a/diff
float result(float a, float b, float c)
{
float diff;
diff=difference(b,c);
if(diff==0)
return 0;
else
return(a/diff);
}
//module that returns the difference b-c
float difference(float b, float c)
{
float a;
a=b-c;
if(a==0)
return 0;
else
return a;
}

RECURSION
• Recursion is the process where a function is called
repetitively by itself.
• The recursion can be used directly or indirectly. Direct
recursion
A function calls itself till the condition is true.
Example 1.
main()
{
printf(“this is main”);
main();
}
Example 2:
//program to find the factorial of a number
#include<stdio.h>
main()
{
int n;
scanf(“%d”,&n);
printf(“%d”,factorial(n));
}

factorial(int n)
{
int fact;
if(n==1)
return 1; else
fact=n*factorial(n-1);
return(fact);
}

Steps:
1. When n=3, fact=3*factorial(2)
2. When n=2, fact=2*factorial(1)
3. When n=1, 1 is returned & control goes to step 1 where fact = 2*1=2 & control is
returned to step 1 where fact = 3*2=6 & value is given to the calling function

Indirect Recursion
A function calls another function then the called function calls
the calling function.
Example.
void main()
{
add();
}
add()
{
static int i=0;
while (i<5)

{ i++;

main();
}
}

Recursive functions apply to problems where the solution is expressed interms of


successively applying the same solution to the subsets of the problem. When a recursive
function is used then if statement is required to force the function to halt & return a value
to the calling function. Otherwise the loop will continue on endlessly.

PASSING ARRAYS TO FUNCTIONS


To pass an array to a called function, it is sufficient to list the name of the array, without
any subscripts, and the size of the array as arguments.
Eg: 1) largest(a,n);
The following program demonstrates how to pass an array to a function.
/* example program to demonstrate the passing of an array */
#include <stdio.h>
int maximum( int [] );

int maximum( int values[5] )


{
int max_value, i;

max_value = values[0];
for( i = 0; i < 5; ++i )
if( values[i] > max_value )
max_value = values[i];

return max_value;
}

main()
{
int values[5], i, max;

printf("Enter 5 numbers\n");
for( i = 0; i < 5; ++i )
scanf("%d", &values[i] );

max = maximum( values );


printf("\nMaximum value is %d\n", max );
}

Output
Enter 5 numbers
7 23 45 9 121
Maximum value is 121
The program defines an array of five elements (values) and initializes each element to the
users inputted values. The array values is then passed to the function. The declaration int
maximum( int values[5] )
defines the function name as maximum, and declares that an integer is passed back as the result,
and that it accepts a data type called values, which is declared as an array of five integers.
One-Dimensional arrays
In C programming, a single array element or an entire array can be passed to a function.
Also, both one-dimensional and two-dimensional array can be passed to function as argument.

Passing One-dimensional Array In Function


C program to pass a single element of an array to function

#include <stdio.h>
void display(int a)
{
printf("%d",a);
}
int main(){ int c[]={2,3,4}; display(c[2]);
//Passing array element c[2] only.
return 0;
} Output
4
Single element of an array can be passed in similar manner as passing variable to a
function.
Passing entire one-dimensional array to a function
While passing arrays to the argument, the name of the array is passed as an argument(,i.e,
starting address of memory area is passed as argument).

Write a C program to pass an array containing age of person to a function. This function
should find average age and display the average age in main function.
#include<stdio.h> float
average(float a[]); int
main(){
float avg, c[]={23.4,55,22.6,3,40.5,18};
avg=average(c);/* Only name of array is passed as argument.
*/ printf("Average age=%.2f",avg); return0; }
float average(float a[]){ int
i;
float avg, sum=0.0;
for(i=0;i<6;++i)
{ sum+=a[i];
} avg
=(sum/6); return
avg;
}
Output
Average age=27.08

Two-Dimensional arrays
To pass two-dimensional array to a function as an argument, starting address of memory
area reserved is passed as in one dimensional array It is similar to the One-Dimensional array.
The rules are:
1. The function must be called by passing only the array name.
2. In the function definition,we must indicate that the array has two-dimensional by
including two sets of brackets.
3. The size of the second dimension must be specified.
4. The prototype declaration should be similar to the function header.

Example to pass two-dimensional arrays to function

#include
voidFunction(int c[2][2]);
int main(){ int c[2][2],i,j;
printf("Enter 4 numbers:\n");
for(i=0;i<2;++i) for(j=0;j<2;+
+j){
scanf("%d",&c[i][j]);
}
Function(c);/* passing multi-dimensional array to function */
return0; }
voidFunction(int c[2][2]){
/* Instead to above line, void Function(int c[][2]){ is also valid */ int
i,j;
printf("Displaying:\n");
for(i=0;i<2;++i) for(j=0;j<2;+
+j)
printf("%d\n",c[i][j]);
}
Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5

THE SCOPE, VISIBILITY AND LIFETIME OF VARIABLES


A storage class defines the scope (visibility) and life time of variables and/or functions
within a C Program.
There are following storage classes which can be used in a C Program
• Automatic variables
• Register variables
• Static variables
• External variables
Scope
Scope is defined as the area in which the declared variable is ‘available’. There are five scopes in
C: program, file, function, block, and prototype
Lifetime
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”). There are three lifetimes in C: static, automatic and
dynamic. Visibility
Visibility is the “accessibility” of the variable declared. It is the result of hiding a variable
in outer scopes.
Scope, lifetime and visibility are related to each other, but are distinct. Scope is about the
‘availability’ of the declared variable: within the same scope, it is not possible to declare/define
two variables of the same type with the same name. Lifetime is about the duration in which the
variable is ‘alive’: it determines how long the named or unnamed variable has memory allocated
to it.
Visibility is about the ‘accessibility’ of the declared variables: it arises because of the
possibility of variables in outer scope having the same name as the ones in inner scopes, resulting
in ‘hiding’

Automatic variables auto is the default storage


class for all local variables.
{
int Count;
auto int Month;
}
The example above defines two variables with the same storage class. auto can only be used
within functions, i.e. local variables.
Register variables
 Register variables tells the compiler to store the value of a variable in a register.
 Register access is much faster than memory access.
 Frequently used variables can be placed in the register.
 Leads to faster execution of programs.
 Most compilers allow only int and char data type to be placed in the register.
 C automatically converts register variables into non-register variables once the limit is
reached.

Syntax:

register datatype variablename;

Example:
Write a program to declare and use variables of register class

void main ()
{
register int m=1;
clrscr(); for(;m<=5;m++)
printf(“\t %d”,m);
}
OUTPUT

1 2 3 4 5

Explanation:
In the above program variable ‘m’ is declared and initialized to 1. The for loop display values
from 1 to 5. The register class variable is used as loop variable.
External variables extern is used to give a reference of a global variable that is visible to ALL
the program files. When you use 'extern' the variable cannot be initialized as all it does is point
the variable name at a storage location that has been previously defined.
External variables are declared outside a function. For example ,the external declaration of
integer and float are declared as:
Int number;
float length = 7.5 ;
main ( )
{
-----------
-----------
}
function1 ( ) {
-----------
-----------
}
function2
(){
-----------
-----------
}
When you have multiple files and you define a global variable or function which will be used in
other files also, then extern will be used in another file to give reference of defined variable or
function. Just for understanding extern is used to declare a global variable or function in another
files.
File 1: main.c
int count=5;

main()
{
write_extern();
}
File 2: write.c void
write_extern(void);

extern int count;

void write_extern(void)
{
printf("count is %i\n", count);
}
Here extern keyword is being used to declare count in another file. Now
compile these two files as follows
gcc main.c write.c -o write
This fill produce write program which can be executed to produce result.

Count in 'main.c' will have a value of 5. If main.c changes the value of count - write.c will see the
new value

Static variables static is the default storage class for global variables. The two variables below
(count and road) both have a static storage class.
static int Count;
int Road;

{
printf("%d\n", Road);
}
static variables can be 'seen' within all functions in this source file. At link time, the static
variables defined here will not be seen by the object modules that are brought in.
static can also be defined within a function. If this is done the variable is initalised at run time but
is not reinitalized when the function is called. This inside a function static variable retains its
value during vairous calls.
void func(void);

static count=10; /* Global variable - static is the default */

main()
{
while (count--)
{
func();
}

void func( void )


{
static i = 5;
i++;
printf("i is %d and count is %d\n", i, count);
}

This will produce following result

i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
Here keyword void means function does not return anything and it does not take any parameter.
You can memoriese void as nothing. static variables are initialized to 0 automatically.
Definition vs. Declaration:
Before proceeding, let us understand the difference between defintion and declaration of
a variable or function. Definition means where a variable or function is defined in realityand
actual memory is allocated for variable or function. Declaration means just giving a reference of
a variable and function.
Through declaration we assure to the complier that this variable or function has been
defined somewhere else in the program and will be provided at the time of linking. In the above
examples char *func(void) has been put at the top which is a declaration of this function where as
this function has been defined below to main() function.
Place of
Storage class Visibility Lifetime
Declaration
Before all
Entire file + other files where variable is Entire
None functions in
declared as extern. Program(Global)
a file
Before all Entire file + other files where variable is
Extern functions in declared as extern and the file where it is Global.
a file originally declared as global.
Before all O
Static(external) functions in Global
a file le
Inside a Until end of
None or auto Only in that function
function function
Inside a Until end of
Register Only in that function
function function
Inside a
Static(internal) Only in that function Global
function

MULTI-FILE PROGRAMS
In a program consisting of many different functions, it is often convenient to place each
function in an individual file, and then use the make utility to compile each file separately and
link them together to produce an executable.
Multiple source files can share a variable provided it is declared as an external variable
appropriately. Variables that are shared by two or more files are global variables and therefore
we must declare them accordingly in one file and then explicitly define them with extern in other
files. Figure ….illustrates the use of extern declarations in a multifile program.
The function main in file1 can reference the variable m that is declared as global in file2.
Remember, function1 cannot access the variable m. If, however, the extern int m; statement is
placed before main, then both the functions could refer to m. This can also be achieved by using
extern int m; statement each function in file1.
The extern specifier tells the compiler that the following variable types and names have
already been declared elsewhere and no need to create storage space for them. It is the
responsibility of the linker to resolve the reference problem. It is important to note that a multifile
global variable should be declared without extern in one (and only one) of the files. The Extern
declaration is is done in places where secondary references are made. If we declare a variable as
global in two different files used by a single program, then the linker will have a conflict as to
which variable to use and , therefore, issues a warning.
file1.c file2.c
main() int m / *global variable */
{ function2()
Extern int m; {
int i; int i;
……… ……….
……… ………..
} }
function1 () function3()
{ {
int j; int count;
…….. ……………
……… ……………
} }
Fig (a)Use of extern in a multifile program.
The multifile program shown in fig.(a) can be modified as shown in Fig. (b)
file1.c file2.c
int m; /* global variable */ extern int m;
main() function2()
{ {
int i; int i;
………. ……..
} }
funciton1() funciton3()
{ {
int j; int count;
………. ………
} }
Fig.(b)Another version of a multifile program.
STRUCTURES & UNION
Introduction:
Structure is a constructed data type for packing data of different types. It is a convenient tool for
handling a group of logically related data items.
Some of the examples of structures in as follows.
Time : seconds,minutes,hours
Date : day,month,year Book
: author,title,price,year.
City : name,country,population.

1. Structures enable the user to group together a collection of different data items of
different data types using a single name.
2. Structures help to organize complex data in a more meaningful way.

Features of Structures:
1. To copy elements of one array to another array of same type elements are copied one by
one. It is not possible to copy all the elements at a time. Whereas in structures it is
possible to copy the contents of all the structure elements of different data types to
another structure variable of its type using assignment (=) operator. It is possible because
the structure elements are stored successive memory locations.
2. Nesting of structures is possible .ie creating structure within another structure.
3. It is possible to pass structure elements to a function.
4. It is possible to create structure pointers.

Defining a structure:
A structure can be used to represent a student’s details such as student_name, rollno, marks etc
as follows
Struct student
{
char stud_name[20];
char stud_rollno[10];
float stud_mark1; float
stud_mark2; float
stud_mark3;
};
A structure definition creates a format that may be used to declare structure variables.
General format for structure definition is as follows:

struct tag-name

data-type member1;
data-type member2;

……………

……………};

Example:

Struct book_bank name of the structure or structure tag


{
char title[20];
char author[15]; structure elements or members
int pages; float price;
};
struct book_bank b1,b2,b3; structure variables

In the above example book bank is a tag-name that is optional one. If you give the tagname
then later in the program you can declare the variables using the given tag-name otherwise it is
not possible. The title, author, pages and price are members of the structure.
While defining the structure memory is not allocated for its members. Only during the
declaration the memory is allocated for the members. Thus the structure definition creates a
template to represent a group of logically related information. In the structure definition we
should follow the rules stated below
1. The template is terminated with semicolon.
2.While the entire declaration is considered as a statement, each member is declared
independently for its name and type in a separate statement inside the template.
3. The tag name such as book_bank can be used to declare structure variables of its type
later in the program.

Declaring structure variables:


A structure variable declaration is similar to the declaration of variables of any other data types.
It includes the following elements.
1. The keyword struct.
2. The structure tag name.
3. List of variable names separated by commas.
4. A terminating semicolon.
For example the statement
Struct book_bank,book1,book2,book3;
Declares book1,book2 and book3 as variables of type struct book_bank.

There are 2 ways in which we can declare a structure.


The user can combine the template declaration and the variable declaration in a single statement
as follows

struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
}book1,book2,book3;

The use of tag name is optional as follows


struct
{
char title[20];
char author[15];
int pages;
float price;
}
book1,book2,book3;

Accessing structure members:


We can assign values to members of a structure. The structure members themselves are not
variables. They should be linked to the structure variables in order to make them meaningful
members.
For example the word title, has no meaning when it appears alone. The same structure member
when it appears with the structure variable book1 as book1’s title has a meaning. The link
between a structure member and a structure variable is established using the member operator
‘.’, which is also called as “dot operator” or “period operator”. Thus we can assign a value to
the member using dot operator like as follows b1.price=150.00;
b2.title=”c programming”;
The same dot operator can be used to assign values to the structure members through the
keyboard as follows scanf(“%s”,book1.title);

Example:
/*Program to illustrate the dot operator*/
#include<stdio.h>
struct student
{
char stud_name[25];
char stud_rollno[10]; float
mark1,mark2,mark3,tot;
}student1;
void main()
{
printf(“Enter student details\n”);
printf(“\nStudent Name : “);
scanf(“%s”,student1.stud_name); printf(“\nRoll
no : “); scanf(“%s”,student1.stud_rollno);
printf(“\nMark1 : “); scanf(“%f”,&student.mark1);
printf(“\nMark2 : “);
scanf(“%f”,&student.mark2); printf(“\nMark3
: “);
scanf(“%f”,&student.mark3);
student1.tot = student1.mark1 + student1.mark2 + student1.mark3;
printf(“The student details are as follows….\n”);
printf(“Student name : %s\n”,student1.stud_name);
printf(“Roll no : %s\n”,student1.stud_rollno);
printf(“Marks:%f%f %f\n”,student1.mark1,student1.mark2,student1.mark3);
printf(“Total : %f\n”,student1.tot);
}

Structure Initialization:
Like any other type, a structure variable can be initialized. However, a structure must be
declared as static if it is to be initialized inside a function.

Example:
main( )
static struct
{
int weight;
float height;
}student={100,150.45};
……………………..
……………………..
}
Thus in the above example the value 100 is stored in student.weight and 150.45 to
student.height. There is a one- to-one correspondence between the members and their initializing
values.
A variation in initializing a structure is as follows:
main( )
{
struct st_record
{
int weight;
float weight;
};
static struct st_record stu1={30,70.56};
static struct st_record stu2={45,65.73};
……………
……………
}
Another variation in initializing structure variable outside the function is as follows:
struct stu
{
int weight; float height;
}stu1={56,170.56};
main()
{
static struct stu student2 = {23,150.5};
………………..
………………..
}

Example :Write a program to read values using scanf() and assign them to structure
variables.

main()
{
struct book1
{
char book [30];
int pages;
float price;
};
struct book1 b;
clrscr();
printf(“Enter Book name ,pages & Price:”);
scanf(“%s”,b.book);
scanf(“%d”,&b.pages);
scanf(“%f”,&b.price); printf(“\n Book
name :“%s”,b.book); printf(“\n No.of
pages : %d”,b.pages);
printf(“\m Book Price : %d”,b.price);
}

Output:

Enter Book name ,pages & price : C 300 219.50


Book name : C
No.of pages : 300
Book Price : 219.50

Copying and comparing structure variables:


Two variables of the same structure type can be copied the same way as ordinary variables. If
person1 and person2 belong to the same structure, then the following statement are valid:
person1 = person2;
person2 = person1;
However, the statements such as
person1 == person2
person1!= person2 are not permitted. C does not permit any
logical operations on structure variables.

Example:
structclass
{ int
number;
char
name[20];
float marks;
};

main()
{
int x;
structclass student1 = {111,"Rao",72.50}; structclass
student2 = {222,"Reddy", 67.00};
structclass student3;

student3 = student2;

x = ((student3.number == student2.number) &&


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

if(x == 1)
{
printf("\nstudent2 and student3 are same\n\n");
printf("%d %s %f\n", student3.number,
student3.name,
student3.marks);
} else
printf("\nstudent2 and student3 are different\n\n");
}
Output

student2 and student3 are same

222 Reddy 67.000000

Array of structures
Array is a collection of similar data types. In the same way we can also define array of
structures. In such type of array every element is of structure type. Array of structures can be
declared as follows :

struct time
{
int second;
int minute;
int hour;
} t[3];

In the above example t[3] is an array of 3 elements containing three objects of time structure.
Each element of t[3] has structure of time with 3 members that are second, minute & hour .
Example:
main()
{
int k;
struct time
{
int second;
int minute;
int hour;
};
struct t
{
int carno;
struct time st;
struct time rt;
};

struct tt r1[3];
clrscr();
printf(“\n Enter car no starting time(hh:mm;ss) &reaching time(hh:mm:ss) :”);
for(k=0;k<3;k++)
{
scanf(“%d”,&r1[k].carno);
scanf(“%d %d %d”,&r1[k].st.hour,&r1[k].st.minute,&r1[k].st.second);
scanf( “%d %d %d”,&r1[k].rt.hour,&r1[k].rt.minute,&r1[k].rt.second);
}
printf(“\n\n Car No,\t Starting Time \t Reaching Time \n”);
for(k=0;k<3;k++)
{
printf(“\n\t %d \t”,r1[k].carno);
printf(“%d %d %d”,r1[k].st.hour,r1[k].st.minute,r1[k].st.second)
printf(“%d %d %d”,r1[k].rt.hour,r1[k].rt.minute,r1[k].rt.second);
}
}

output:
Enter car no starting time(hh:mm;ss) &reaching time(hh:mm:ss) :
120 2 20 25 3 25 58
121 3 25 40 4 40 25
122 4 30 52 5 40 10

Car No Starting Time Reaching Time

120 2 20 25 3 25 58
121 3 25 40 4 40 25
122 4 30 52 5 40 10

Explanation: In the above program two structures time and t are declared. An array of three –
elements r1[3] is defined. The first for loop executes three times and the scanf () statement reads
data through the keyboard for each element of the object. The second for loop and the printf ()
statements within it displays the contents of the array of objects with their elements.

Arrays within structures:


C permits the use of arrays as structure members. We have already used arrays of characters
inside a structure. Similarly, we can use single-dimensional or multi-dimensional arrays of type
int or float. For example, the following structure declaration is valid: struct marks
{
int number;
float subject[3];
} student[2];
Here the member subject contains three elements subject[0], subject[1] and subject[2]. These
elements can be accessed using appropriate subscripts. For example, the name
student[1].subject[2]; Example:
/* nested structure & array with in structure */
#include<stdio.h>
#include<conio.h>

struct date
{ int
dd; int
mm;
int yy; };
struct student
{
int rl; struct
date dob;
int m[3];
int t;
}; void
main()
{
struct student list[50];
int i,j,n;
clrscr();
printf("enter how many student\n");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("enter rollno,date of birth\n"); scanf("%d%d%d
%d", &list[i].rl,&list[i].dob.dd,
&list[i].dob.mm,&list[i].dob.yy);

list[i].t=0;
printf("enter three subject marks\n");
for(j=0;j<3;j++)
{
scanf("%d",&list[i].m[j]);
list[i].t+=list[i].m[j];
}
}
printf("student list\n");
for(i=0;i<n;i++)
{
printf("%d\t%d-%d-%d\t",list[i].rl,
list[i].dob.dd,
list[i].dob.mm,
list[i].dob.yy);
for(j=0;j<3;j++) printf("%d\
t",list[i].m[j]);
printf("%d\n",list[i].t);
}
getch();
}
Structures within structures:
Structure within structure can be used to create complex data applications.
Syntax:
Example:
struct time
{
int second;
int minute;
int hour;
};

struct t
{
int carno;
struct time st;
struct time et;
};
struct t player;

Example:
Write a program to enter full name and date of birth of a person and display the same. Use nested
structure.
void main()
{
struct name
{
char firstn [30];
char secondn[30];
char lastn[30];
};
struct b_date
{
int day ;
int month;
int year;
};

struct data
{
struct name n;
struct b_date d;
};
struct data s;
clrscr();
printf(“Enter your name :”);
scanf(“%s %s %s”,s.n.firstn,s.n.secondn,s.n.lastn);
printf(“Enter date of birth:”);
scanf(“%d %d %d”, s.d.day,s.d.month,s.d.year);
printf(“\n\nName:%s%s%s“,s.n.firstn,s.n.secondn,s.n.lastn);
printf(“Date of Birth :%d / %d /%d”,s.d.day,s.d.month.s.d.year);

output:
Enter your name: ram sham pande
Enter date of birth :12 12 1985

Name : ram sham pande


Date of Birth : 12/12/1985

Explanation:
In the above example structure name ,b_date and data are defined. The structure data have
member variable of type name and b_date structures respectively .Therefore, this type of
structure is called as nested structure. The variable ‘s’ is a variable of type data structure. Using
scanf() statement the program reads data from keyoard . In the same way, using printf()
statement entered data is displayed on the screen. Here , the dot (.) operator is used twice as we
are accessing variables of structure which are inside the another structure.

Structures and Functions:


Like the variables of standard data type structure variables also can be passed to the function by
value or address.
The general format of sending a copy of a structure to the called function is:
function_name(structure_variable_name);
The called function take the following form:
data_type function_name(struct_type st_name)
{
……
……
return(expression);
}

Example:
struct book
{
char name[35];
char author[35];
int pages;
} b1;

void main()
{
---------------
---------------
show(&b1); ____________
____________
}
show(struct book *b2)
{
____________
____________
}

Whenever a structure element is to be passed to any other function, it is essential to declare the
structure outside the main ( ) function i.e., global .
In the above example structure book is declared before main ().It is a global structure . Its
member elements are char name[35], char author [35] and int pages . They can be accessed by all
other functions.

Example:
Write a program to pass address of structure variable to user defined function and display the
contents.

# include<stdio.h>
#include<conio.h>
struct book
{ char
name[35]; char
author [35]; int
pages;
};

void main()
{
struct book b1={“LET US C”,”YESWANTH KANTIKAR”,345}; show(&b1);
}
show(struct book *b2)
{ clrscr()
;
printf(“\n%s by %s of %d pages”,b2name ,b2author,b2pages);
}

Output:
LET US C by YESWANTH KANITKAR of 375 PAGES

Explanation : In the above program structure book is defined before main ( ) .In the main ( )
function b1 is an object declared and initialized. The address of object b1 is passed to function
show ( ).In the function show ( ) the address is assigned to pointer *b2 that is a pointer to the
structure book. Thus , using operator contents of structure elements are displayed.

Example:
Write a program to pass entire structure to user defined function.

struct boy
{
char name[25];
int age;
int wt;

};

void main()
{
struct boy b1={“Amit”, 20 ,45};
print(b1);
}
print(struct boy b)
{
clrscr();
printf(“\n %s %d %d “,b.name ,b.age,b.wt)l
return 0;
}

Output:
Amit 20 45

Explanation: In the above program structure boy is defined outside the main ( ).so it is global
and every function can access it. The object defined on structure boy b1 is passed to function
print (). The formal argument (object) of function print ( ) receives contents of object b1. Thus ,
using dot operator contents of individual elements are displayed.

Pointer to Structure
A pointer is a variable that holds the address of another data variable. The variable may be of
any data type ie. int, float or double. In the same way we can define pointer to structure. Here ,
starting address of the member variables can be accessed. Thus, such pointers are called structure
pointers. Example:
struct book
{
char name [25];
char author[25];
int pages;
};
struct book *ptr;

Here, *ptr is pointer to structure book. Syntax for using pointer with member is as given
below.
5. ptr  name
6. ptr author
7. ptrpages
By executing these three statements starting address of each member can be estimated.
Example:
Write a program to declare pointer to structure and display the contents of the structure.

void main()
{
struct book
{
char name [25];
char author [25];
int pages ;
};
struct book b= {“Let us C”, ”Yeswanth kanitkar”,375};
struct book *ptr;

ptr=&b;
clrscr();
printf(“\n %s by %s of %d pages “,b.name,b.author,b.pages); printf(“\n
%s by %s of %d pages“,ptrname,ptrauthor,ptrpages); }

Output
Let us C by Yeswanth kanitkarof 375 pages
Let us C by Yeswanth kanitkarof 375 pages

Explanation: In the above program the function printf( ) statement prints structure elements by
calling them as usual. In the second printf( ) statement to print the structure elements using
pointer an arrow operator ( -and > together) is used instead of dot(.)operator. The ptr is not a
structure variable but pointer to a structure.
Example:
Write a program to declare pointer as members of structure and display the contents of the
structure without using  (arrow) operator.

void main()
{
struct boy
{
char *name;
int *age;
float *height;
};
struct boy b;

char nm[10]=”Akil”;
int ag=20;
float ht =5.4;

strcpy(b.name ,nm);
b.age =&ag;
b.height = &ht;

clrscr();
printf(“\n Name = %s”,b.name);
printf(“\n Age = %d”,*b.age);
printf(“\n Height = %d”,*b.height);
}

Output:

Name = Akil
Age = 20
Height = 5. 4

Explanation: Here no pointer is declared in structure. Hence, using dot operator we can display
the contents of the structure.

Example:
Write a program to display the contents of the structure using ordinary pointer.

void main()
{
int *p;
struct num
{
int a;
int b; int c;
};
struct num d;

d.a =2;
d.b=3;
d.c=4;

p=&d.a;
clrscr();

printf(“\n a=%d”,*p);
printf(“\n b=%d’,*(++p));
printf(“\n c=%d”,*(++p));
};

Output:
a=2 b=3
c=4
Explanation: In the above program *p and structure num are declared .The structure num has
three members a,b &c of integer data type and initialized with the values 2,3 and 4 respectively.
The structure variables are stored in successive memory locations. If we get starting address of
one variable we can display next elements. The address of variable a is assigned to pointer p. By
applying unary * and ++ operator pointer is increased and values are displayed.

Enumerated data type


The enum is a keyword. It is used for declaring enumeration types. The programmer can create
his/her own data type and define what values the variables of these data types can hold.

Example:
enum month{jan,feb,mar,apr,may,jun.jul,aug,sep,oct,nov,dec};

This statement creates a user-defined data type. The keyword enum is followed by the tag
name month. The identifiers are jan,feb etc., The identifier jan refers to 0,feb refers to 1etc., .The
identifiers are not to be enclosed within quotation marks.

Example:
Write a program to create enumerated data type for 12 months. Display their values in integer
constants.
#include<stdio.h>
#include<conio.h>
void main()
{
enum month
{jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec}; clrscr();
printf(“\n Januay =%d”,jan); printf(“\n April =%d”,apr);
printf(“\n July =%d”,jul); printf(“\n December =%d”,dec);
} Output:
January = 0
April = 3
July =6
December=11

Explanation:
In the above program enumerated data type month is declared with 12-month names within two
curly braces. The compiler assigns 0 value to first identifier and 11 to last identifier .Using printf
() statement the constants are displayed for different identifiers.
By default the compiler assigns values from 0 onwards. Instead of 0 the programmer can
initializes his/her own constant to each identifier .

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
enum month
{jan=1,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec}; clrscr();
printf(“\n Januay =%d”,jan);
printf(“sss\n April =%d”,apr);
printf(“\n July =%d”,jul);
printf(“\n December =
%d”,dec);
} Output:
January = 1
April = 4
July =7
December=12

UNION

 Union is a variable, which is similar to the structure.


 It contains number of members like structure but it holds only one object at a time.
 In the structure, each member has its own memory location whereas, members of unions
have sane memory locations.
 It can accommodate one member at a time in a single area of storage.
 Union can also contains members of types int ,float, long, arrays ,pointers etc.,
 It allocates fixed specific bytes of memory for access of data types irrespective of any
data type.
 The union requires bytes that are equal to the number of bytes required for the largest
members.

Example:
Write a program to find the size of union and member of bytes reserved for it.

main()
{
union result
{
int marks;
char grade;
};
struct res
{
char name[15];
int age;
union result perf;
}data;
clrscr();
printf(“Size of union :%d\n”,sizeof(data.perf));
printf(:Size of structure :%d \n”,sizeof(data));
}

Output
Size of union :2
Size of structure :19

Explanation:
Union contains two variables of data types int & char respectively. The int & char requires 2 & 1
bytes respectively for storage. According to the theory the union reserves two bytes because int
takes more space than char data type.
The structure ‘res’ are defined immediately after union,which contains data type char, int &
union variable. The size of structure is printed which are nothing but sum of 15 bytes of char
array, 2 bytes of int and 2 bytes of union variable perf. Thus, the total size of structure is 19.

Size of structures
We normally use structures, unions, and arrays to create variables of large sizes. The actual size
of these variables in terms of bytes may change from machine to machine. We may use the unary
operator sizeof to tell us the size of a structure (or any variable). The expression sizeof(struct
x)
will evaluate the number of bytes required to hold all the members of the structure x. If y is a
simple structure variable of type struct x, then the expression
sizeof(y)
would also give the same answer. However , if y is an array variable of type struct x , then
sizeof (y) would give the total number of bytes the array y requires.

Bit Fields
Bit field provides exact amount of bits required for storage of values. If a variable is 1 or 0, we
need a single bit to store it. If a variable is between 0 and 3, we need two bits to store them.
Similarly if variable is between 0 to 7,then three bits will be sufficient to hold the variable and so
on. The number of bits required for a variable is specified by non-integer followed by colon. The
variables occupy a maximum of one byte for char and two bytes for integer. Instead of using
complete integer if bits are used, space of memory can be saved.

Example:
Write a program to display the examination result of the student using bit fields.
#include<stdio.h>
#include<conio.h>

#define PASS 1
#define FAIL 0
#define A 0
#define B 1
#define C 2 void
main()
{
struct student
{
char *name;
unsigned result :1;
unsigned grade:2;
};
struct student v;
v,name =”Sachin”;
v.result=PASS;
v.grade=C; clrscr();
printf(“\n Name :%s”,v.name);
printf(“\n Result : %d”,v.result);
printf(“\n Grade : %d”,v.grade);
}

Output:
Name : Sachin
Result : 1
Grade :2

Explanation:
In the above program using #define macros are defined. The result of the student is indicated in
1 bit and the grade requires 2 bits. An object v is declared and using the object bits fields are
initialized with data.
UNION AND STRUCTURES
The union can be nested within another union .we can also create structure in a union or vice
versa

Example
Write a program to use structure within union .Display the contents of structure elements.

#inlcude<stdio.h>
#include<conio.h>
void main()
{
struct x
{
float f;
char p[2];
};
union z
{
structure x set;
};
union z st;
st.set.f=5.5;
st.set.p[0]=65;
st.set.p[1]=66;
clrscr();
printf(“\n %f”,st.set.f);
printf(“\n %c’,st.set.p[0]);
printf(“\n %c”,st.set.p[1]);
}

Output:
5.5
A
B

Explanation:
In the above program structure x is defined. The union z contains structure member as its
member variable. The variable st is an object of union z. The member variables of structure x are
assigned with certain values .Using objects of structure and union.

Sample programs:
1. C Program to Reverse a String by Passing it to Function
#include<stdio.h>
#include<string.h>
voidReverse(char str[]);
int main(){ char
str[100];
printf("Enter a string to reverse: ");
gets(str); Reverse(str);
printf("Reversed string: ");
puts(str);
return0; }
voidReverse(char str[]){ int
i,j;
char temp[100]; for(i=strlen(str)-1,j=0;
i+1!=0;--i,++j)
{
temp[j]=str[i];
} temp[j]='\0';
strcpy(str,temp);
}
Output
Enter a string to reverse: zimargorp Reversed
string: programiz

2. C program to Check Whether a Number can be Express as Sum of Two Prime Numbers

This program takes a positive integer from user and checks whether that number can be
expressed as the sum of two prime numbers. If that number can be expressed as sum of two
prime numbers then, that number is expressed as sum of two prime numbers in output. To
perform this task, a user-defined function is created to check prime number.
#include<stdio.h>
int prime(int n);
int main() {
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n); for(i=2;
i<=n/2;++i)
{
if(prime(i)!=0)
{
if( prime(n-i)!=0)
{
printf("%d = %d + %d\n", n, i, n-i);
flag=1;
}

}}
if(flag==0)
printf("%d can't be expressed as sum of two prime numbers.",n);
return0; }
int prime(int n)/* Function to check prime number */
{ int i, flag=1;
for(i=2; i<=n/2;++i)
if(n%i==0)
flag=0;
return flag; }
Output
Enter a positive integer: 34
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17

3. C Program to Find H.C.F Using Recursion


#include<stdio.h>
int hcf(int n1,int n2);
int main() { int n1,
n2;
printf("Enter two positive integers: "); scanf("%d
%d",&n1,&n2);
printf("H.C.F of %d and %d = %d", n1, n2, hcf(n1,n2));
return0; }
int hcf(int n1,int n2)
{ if(n2!=0) return
hcf(n2, n1%n2);
else return
n1;
}

Output:
Enter two positive integers: 366
60
H.C.F of 366 and 60 = 6
UNIT IV QUESTIONS SECTION A

1. A function is a self-contained block of code that performs a particular task is called


____________.
2. The arguments of calling functions are called _____________.
3. Variables enclosed within the parenthesis are called ____________.
4. The two types of variables are ___________ and ____________.
5. Local variables are defines within ____________.
6. Global variables are declared in ____________.
7. A__________ declaration consists of function’s return type, name and argument list.
8. The arguments that are used in the main function are called ___________.
9. The arguments that are used in the called function instead of the actual arguments are
called ___________.
10. The two ways where we can pass arguments to the function is by ________ and
_________.

SECTION B

1. What is a function and explain its uses and how it works.


2. Write short notes on local and global variables.
3. What is a function prototype explain with example.
4. Explain the types of functions with suitable example.
5. Write short notes on call by reference and call by value.
6. What is recursion? Explain.
7. How will you pass arrays with functions. Explain.
8. Write a c program to calculate the square of a number using user-defined functions.
9. What is a structure? Explain its features.
10. What is union? Explain with example.

SECTION C
1. Explain in detail about user-defined data types and enumerated data types with suitable
example.
2. How will you declare functions and function-prototypes. Explain with example.
3. What are the types of functions? Explain in detail with example.
4. Write a brief note on return() statement. Explain with example.
5. Write c program for
6. To display message using user-defined functions.
7. To display alphabets ‘A,’B’ and ‘C’ using functions.
8. How will you pass arrays with functions. Explain with example.
9. Explain in detail about Recursion with example.
10. Write a brief note on call by reference and call by value with example.

You might also like