0% found this document useful (0 votes)
2 views16 pages

Unit 4 CPRG

The document provides an overview of user-defined functions and data types in C programming, detailing their structure, advantages, and usage. It explains the components of functions, including function definition, declaration, and calling, as well as the differences between structures and unions. Additionally, it covers examples of function implementations and the significance of modular programming for code reusability and maintenance.

Uploaded by

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

Unit 4 CPRG

The document provides an overview of user-defined functions and data types in C programming, detailing their structure, advantages, and usage. It explains the components of functions, including function definition, declaration, and calling, as well as the differences between structures and unions. Additionally, it covers examples of function implementations and the significance of modular programming for code reusability and maintenance.

Uploaded by

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

DMSMs College of Computer Applications, Belgaum 9880177097

Unit 4: User defined functions, User defined data types


User Defined Functions: Need for user defined functions; Format of C user defined functions;
Components of user defined functions - return type, name, parameter list, function body, return
statement and function call; Categories of user defined functions - With and without parameters
and return type.
User defined data types: Structures - Structure Definition, Advantages of Structure, declaring
structure variables, accessing structure members, Structure members initialization, comparing
structure variables, Array of Structures; Unions - Union definition; difference between Structures
and Unions.

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.

Need for User Defined functions


 Large and complex programs may become difficult to debug and to maintain. Functions help
in both.

 Functions are used to implement Modular Programming


o Large program divided into smaller, functional parts called subprograms
o Each part can be independently coded, tested and then combined into a single unit

 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.

Programming in C (2021-22) Unit 4 Page 1


DMSMs College of Computer Applications, Belgaum 9880177097

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

 By using functions, length of source program can be reduced

 Functions help in saving memory space where memory space is limited

 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

User defined functions


Functions are classified as derived datatypes in C, hence they are similar to variables. Function
names have the same rules as variable names. Since functions have types (int, float, char) associated
with them, function names and their types must be declared and defined before they can be used.
The various elements of functions are:

 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).

Programming in C (2021-22) Unit 4 Page 2


DMSMs College of Computer Applications, Belgaum 9880177097

Syntax of function definition


function_type function_name(parameter_list)  function header
{
local variable declarations;
executable statement;
executable statement;
.  function body
.
.
return statement;
}

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);

Programming in C (2021-22) Unit 4 Page 3


DMSMs College of Computer Applications, Belgaum 9880177097

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);

Points to note about function parameters


Parameters are used in
• Function declaration/prototype – formal parameters
• Function calls – actual parameters
• Function definition – formal parameters
• Parameter list must be separated by commas

Programming in C (2021-22) Unit 4 Page 4


DMSMs College of Computer Applications, Belgaum 9880177097

• 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

No Arguments and no return values


• No arguments: The function does not receive any data from the calling function, hence
parameter list is void.
• No return values: The function does not give back any data to the calling function, hence
function type is void.
• Effectively, there is no communication(data transfer) between the calling function and the
called function.
• Only a transfer of control will happen.
Example program is shown below:
#include<stdio.h>
void printline(void); //function declaration
main()
{
printline(); //function call
printf(“Hello, Welcome to C programming”);
printline(); //function call
}

//function definition
void printline(void)
{
printf(“\n****** ^^^^^^ ******\n”);
}

Programming in C (2021-22) Unit 4 Page 5


DMSMs College of Computer Applications, Belgaum 9880177097

With Arguments but no return values


 Data can be passed from calling function to called function through arguments.

 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);
}

With arguments and one return value


• Data can be passed from calling function to called function through arguments. The datatype
and number should be mentioned in the parameter list.
• Actual and formal arguments should match in number, type and order
• Since the function returns a value, its type should be specified in the function header.
• Alongwith transfer of control, data is also transferred both into the function and back to the
calling function.
Example program is shown below:
#include<stdio.h>
int printvalue(char); //function declaration

main()
{
char ch1;
int val=0;

Programming in C (2021-22) Unit 4 Page 6


DMSMs College of Computer Applications, Belgaum 9880177097

printf(“\nEnter any character:”);


scanf(“%c”, &ch1);
val=printvalue(ch1); //function call
printf(“Hello, Welcome to C programming”);
printf(“The int value of %c is %d”, ch1, val);
}

//function definition
int printvalue(char a)
{
int char_value=0;
char_value=a; //copies integer value of character
return(char_value);
}

Another example of a simple program without using function is shown below.


/*Program to multiply two numbers*/
#include<stdio.h>
main()
{
int result, a, b;
printf(“Enter 2 numbers”);
scanf(“% d %d”, &a, &b);
result=a*b;
printf(“The result is %d”, result);
}

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

mul(); // function call


}

//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);
}

Programming in C (2021-22) Unit 4 Page 7


DMSMs College of Computer Applications, Belgaum 9880177097

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);
}

Programming in C (2021-22) Unit 4 Page 8


DMSMs College of Computer Applications, Belgaum 9880177097

//Program to find if a given number is a prime or not

#include<stdio.h>

main()
{
int n;
int isprime(int); // function declaration

printf("\nEnter any positive number:");


scanf("%d",&n);

if(isprime(n)==1) //function call


printf("\n%d is a prime number\n");
else
printf("\n%d is not a prime number\n");

//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);
}

****** Output ******

Enter any positive number:12

12 is not a prime number

Enter any positive number:17

17 is a prime number

Enter any positive number:101

101 is a prime number

Programming in C (2021-22) Unit 4 Page 9


DMSMs College of Computer Applications, Belgaum 9880177097

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;
};

Programming in C (2021-22) Unit 4 Page 10


DMSMs College of Computer Applications, Belgaum 9880177097

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.

Declaring a structure variable:


After defining a structure format, structure variables can be declared like other variables of any
datatype.
The general format of the declaration is:
struct tag_name var_name1, var_name2… ;
It contains the following elements:
1. The keyword struct
2. The structure tag_name
3. List of variable names separated by cpmmas
4. A terminating semicolon.
For ex. the statement
struct book_details book1, book2, book3;
declares three variables of the type book_details.
The definition can be combined with the declaration as shown below.
struct book_details
{
char book_name[20];
char author[15];
int pages;
float price;
} book1, book2, book3;
The above structure variable can be represented as follows
book_details
(tag_name)
book_name array of 20 chars
book1 author array of 15 chars
(variable name) pages int
price float

Programming in C (2021-22) Unit 4 Page 11


DMSMs College of Computer Applications, Belgaum 9880177097

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;

Accessing structure members:


Structure members can be accessed by using the member operator . also called as the dot operator
or period operator.
For example, book1.price or book1.author.
Assigning values to members of a structure can be done in the usual manner, but with the use of the
dot operator always.
strcpy(book1.author, “Balagurusamy”);
book1.price = 198.75;
scanf(“%s”, book1.book_name);
scanf(“%d”, book1.pages);

Difference between an array and a structure:


Array Structure
An array is a collection of related data items of Structure can have elements of different types.
same type.
Array is a derived datatype Structure is a programmer defined datatype
Array acts like a built-in datatype, We just have Structure datatypes have to be designed and
to declare an array variable and use it. declared before they can be used to create
structure variables.

Structure Initialization:
Structure variables can be initialized at compile time as shown below:
main()
{
struct person
{
int weight;
float height;
} student= {60, 180.75};

Programming in C (2021-22) Unit 4 Page 12


DMSMs College of Computer Applications, Belgaum 9880177097

…..
…..
}
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 ;

Copying and Comparing structure variables:


Two variables of the same type of structure can be copied like any normal variable.
student1 = student2;
is a valid statement.
But comparing cannot be done in the same manner.
So,
if (student1==student2)
is not a valid statement. No relational or logical operator can be used with structure variables, but
they can be used with individual member variables of a structure.
So,
if (student1.height==student2.height)
is a valid statement.

Programming in C (2021-22) Unit 4 Page 13


DMSMs College of Computer Applications, Belgaum 9880177097

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…..

Programming in C (2021-22) Unit 4 Page 14


DMSMs College of Computer Applications, Belgaum 9880177097

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);

Programming in C (2021-22) Unit 4 Page 15


DMSMs College of Computer Applications, Belgaum 9880177097

#include<stdio.h>
void main()
{
//defining a structure called student
struct student
{
int num;
char name[20];
float marks;
};

//declaring structure variables of student type


struct student sem1[10];

//declaring other variables


int i, n;

printf("\nProgram to demonstrate use of structure variables\n");


printf("Enter the total number of students in the class:");
scanf("%d",&n);
printf("\nEnter details for %d students:",n);
for(i=0;i<n;i++)
{
printf("\nEnter roll number:");
scanf("%d", &sem1[i].num);
printf("\nEnter name of student:");
scanf("%s",&sem1[i].name);
printf("\nEnter total marks:");
scanf("%f", &sem1[i].marks);
}
printf("\nThe details of all students are as shown below:\n");
printf("\tRoll No\t\tName\t\t\tMarks Scored\n");
for(i=0;i<n;i++)
printf("\t%7d%20s\t\t%5.2f\n",sem1[i].num,
sem1[i].name,sem1[i].marks);
}
**** Output ****
Program to demonstrate use of structure variables
Enter the total number of students in the class:3
Enter details for 3 students:
Enter roll number:1
Enter name of student:Abhijit
Enter total marks:67
Enter roll number:2
Enter name of student:Ajay
Enter total marks:76
Enter roll number:3
Enter name of student:Ashwini
Enter total marks:87
The details of all students are as shown below:
Roll No Name Marks Scored
1 Abhijit 67.00
2 Ajay 76.00
3 Ashwini 87.00

Programming in C (2021-22) Unit 4 Page 16

You might also like