Unit 4 CPRG
Unit 4 CPRG
C Functions:
A function is a self contained block of code that performs a particular task.
It can be considered as a black box. It may take some data from the main program, and may return
values back to the main program. Inner details are invisible to the rest of the program.
In c, a large program can be divided into the basic building blocks known as function. The function
contains the set of programming statements enclosed by {}. A function can be called multiple times
to provide reusability and modularity to the C program. A collection of functions creates a program.
The function is also known as procedure or subroutine in other programming languages.
There are two types of Functions, library and user defined.
Inbuilt or Library : These functions are not required to be written/coded, but are already present,
and can be used by anybody. Egs. main(), printf(), scanf(), sqrt(), strcmp()
User-Defined : These functions have to be developed by user at the time of writing the program.
Reusability: Program segments which are repeated can be coded as a separate part
(subprogram) and reused wherever required. Therefore, by using functions, we can avoid
rewriting same logic/code again and again in a program.
Advantages of functions
Functions help in implementing modular programming, where
o High level logic of overall program is solved first
o Details of each lower level are addressed later
It is easy to locate and isolate a faulty function, thus helps in debugging and maintenance.
Since functions can be reused, user defined functions can be used in other programs
A C programmer can build upon what others have already done, no need to start all over
again
Function Definition
Function Call
Function Declaration
Function Definition
The function definition consists of
1. Function name
2. Function type
3. List of parameters
4. Local variable declarations
5. Function statements and
6. Return statement
The above six elements are grouped into 2 parts, namely, Function header (first 3 parts) and Function
body (last 3 parts).
Function Header
The function header consists of function type, function name and parameter list.
Function type specifies the type of value the function is expected to return. If function type is not
specified, C will assume that it is int. If function is not returning anything, the type should be specified
as void
Function name is similar to a variable name (i.e., it follows the same rules). The function name should
be appropriate to the task it is going to perform. It should not be the same as a library function name
or a variable name.
Parameter list declares the variables that will receive the data sent by the calling program. This is
also called as formal parameters or arguments
Function Body
This contains the declarations and statements for performing the particular task. It contains three
parts.
1. Local declarations that specify the variables needed by the function
2. Function statements that perform the task of the function
3. Return statement that returns the value evaluated by the function
Return statement can be
return;
or
return(expression/variable);
Function Call
A function can be called by using function name followed by argument list in brackets
Eg: y = mul(10,5);
When a function is called, control is transferred to the function from the calling program. Then the
function is executes line by line till the return statement, or the ending }.
A function call syntax will vary depending on what type of function is declared. A function call
statement can be a simple statement or it can be part of an expression. It may contain arguments(list
of variables) and it may return a value. The function call statement will appear in the calling function,
usually the main(), but it can also be part of any other user defined function.
Function Declaration
All functions must be declared before they can be called. A function declaration is also called
function prototype.
It consists of four parts
1. Function type
2. Function name
3. Parameter list
4. Terminating semicolon;
The syntax of function declaration is :
function_type function_name(parameter_list);
Eg.
int mul(int, int);
void add_two_numbers(void);
• Parameter names need not be the same in the function declaration (prototype) and function
definition
• Types must match the types in the definition, in number and order
• Use of parameter names in declaration is optional
• If the function has no formal parameters, the list is written as void
Category of functions
• Functions with no arguments and no return values
• Functions with arguments and no return values
• Functions with arguments and one return value
• Functions with no arguments but one return value
• Functions with multiple return values
//function definition
void printline(void)
{
printf(“\n****** ^^^^^^ ******\n”);
}
Actual and formal arguments should match in number, type and order
Since the function does not return any value, its type should be void
Alongwith transfer of control, data is transferred from calling function to called function. But
no data is transferred back to the calling function.
Example program is shown below:
#include<stdio.h>
void printline(char, char); //function declaration
main()
{
char ch1, ch2;
printf(“\nEnter any two characters:”);
scanf(“%c %c”, &ch1,&ch2);
printline(ch1,ch2); //function call
printf(“Hello, Welcome to C programming”);
printline(ch1,ch2); //function call
}
//function definition
void printline(char a, char b)
{
printf(“\n%c %c %c\n”, a, b, a);
}
main()
{
char ch1;
int val=0;
//function definition
int printvalue(char a)
{
int char_value=0;
char_value=a; //copies integer value of character
return(char_value);
}
The above program is rewritten using a function with no arguments and no return values:
/*Program to multiply two numbers*/
#include<stdio.h>
main()
{
void mul(); // function declaration
//function definition
void mul()
{
int x, y, result;
printf(“Enter 2 numbers”);
scanf(“% d %d”, &x, &y);
result=x*y;
printf(“The result is %d”, result);
}
The same program written again with function call using arguments but no return values.
/*Program to multiply two numbers*/
#include<stdio.h>
main()
{
int a, b;
void mul(int, int); // func declaration
printf(“Enter 2 numbers”);
scanf(“% d %d”, &a, &b);
mul(a,b); // function call
}
//function definition
void mul(int x, int y)
{
int result;
result=x*y;
printf(“The result is %d”, result);
}
The same program written again with function call using arguments and return values.
/*Program to multiply two numbers*/
#include<stdio.h>
main()
{
int result, a, b;
int mul(int, int); // func declaration
printf(“Enter 2 numbers”);
scanf(“% d %d”, &a, &b);
result=mul(a,b); // func call
printf(“The result is %d”, result);
}
//function definition
int mul(int x, int y)
{
int r;
r = x*y;
return(r);
}
#include<stdio.h>
main()
{
int n;
int isprime(int); // function declaration
//function definition
int isprime(int a)
{
int i, prime=1;
i=2;
while((i<a)&&(prime==1))
{
if (a%i==0)
prime=0;
i++;
}
if(prime==1)
return(1);
else
return(0);
}
17 is a prime number
Structures:
Arrays can be used to represents a group of data items that belong to the same type, say, int or float.
But, if items of different types need to be represented as a collection of data items, an array cannot
be used to do this.
A structure is a data type which can be used to represent a collection of data items belonging to
different data types. It can be used to handle a group of logically related data items. A structure is
used to define the format of a number of related data items.
For eg., data related to a student can be of different types, but still logically related. Name, roll-
number and marks are all data related to a student. A collection of such data cannot be stored in an
array because an array can only store names or roll-numbers or marks, not all at the same time. This
is where a structure can be used.
Some more examples of such structures are time(hours, minutes, seconds), date(day, month, year),
book(author, title, price, year), city(name, country, population), address(name, door-number,
street, city).
Thus the advantage of using structures is that different types of data related to a single object can
be stored in a single variable with different types of sub-parts. Otherwise, a number of arrays of
different data types would have to be used to store the same data.
Defining a structure:
The general format of structure definition is as follows:
struct tag_name
{
datatype member1;
datatype member2;
.
.
};
This does not declare any variables, but it creates a new datatype in C.
For eg. If details of a book need to be stored as a structure, with book_name, author, pages and
price as members of the structure, then we can define such a structure in the following manner:
struct book_details
{
char book_name[20];
char author[15];
int pages;
float price;
};
This just defines a format for storing book information, but does not create any variables of this
type.
Pls note, struct definition ends with a semicolon. It can be considered as a single statement, but each
member is declared independently for its name and type inside this definition.
Or the definition can be done even without specifying a tag_name as shown below.
struct
{
char book_name[20];
char author[15];
int pages;
float price;
} book1, book2, book3;
Structure Initialization:
Structure variables can be initialized at compile time as shown below:
main()
{
struct person
{
int weight;
float height;
} student= {60, 180.75};
…..
…..
}
Or
main()
{
struct person
{
int weight;
float height;
};
struct person student1={60, 180.75};
struct person student2={50, 170.50};
…..
…..
}
Compile time initialization of structure variables must have
1. The keyword struct
2. The structure tag_name
3. The name of the variable to be declared
4. The assignment operator =
5. A set of values for the members of the structure, separated by commas, and enclosed in
braces
6. A terminating semicolon ;
Arrays of structures:
Structure is used to define the format of a number of related data items.
For eg., if data related to marks of a class of students needs to be analysed, it can be done by
describing a template for student name and marks in all subjects. Then, using this template, an array
of such structures can be declared.
struct class students[10];
The above declaration creates an array of type class containing data related to 10 students.
Each element of the array will be of the following type:
struct class
{
char student_name[20];
int marks1;
int marks2;
int marks3;
};
If appropriate data is stored in the member variables, this array can be represented as
class (tag_name)
student[0].student_name Abhishek
student[0].marks1 75
student[0].marks2 65
student[0].marks3 52
student[1].student_name Akanksha
student[1].marks1 78
student[1].marks2 62
student[1].marks3 45
student[2].student_name Jyotsna
student[2].marks1 56
student[2].marks2 66
student[2].marks3 76
And so on…..
Unions
Unions are similar to structures, and so, the syntax remains the same except for the keyword, union.
When a structure is defined and variables are declared, all member variables are reserved memory
space as per their datatype. At a time, all member variables can be having data stored
simultaneously.
But, when a union is defined and variables are declared, the maximum storage reserved in memory
is equivalent to the largest member variable. In effect, in any union variable, at a time, only one
member variable can be stored.
This is the difference between a structure and a union.
The syntax for declaring a union is as follows
union item
{
int m;
float x;
char c;
};
A union variable can be declared as follows:
union item code;
Where code is a variable of type item. Its individual member variables can be accessed by using the
dot operator.
For eg., code.m, code.x, code.c etc.
Its memory representation will be as follows:
item (tag_name)
code m or x or c
(variable name)
Max size 4 bytes(float)
Since, in a union variable, only any one member variable can be stored at any given time, during
accessing member variables, care should be taken to access only the member variable whose data
is currently stored.
For eg., the following will give unpredictable results.
code.m=376;
code.x=175.4;
printf(“%d”, code.x);
#include<stdio.h>
void main()
{
//defining a structure called student
struct student
{
int num;
char name[20];
float marks;
};