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

Unit 4

The document discusses user-defined functions in C. It explains that a function definition contains a function header with the name, type and parameters, and a function body with local declarations and statements. A function call passes actual parameters to the formal parameters in the function definition. Functions can return values using the return statement or have no return value if the return type is specified as void. Arrays of structures allow declaring multiple structures as array elements to represent related data like student records. Pointers declare a variable that contains the address of another variable. Examples are given of functions with and without arguments and return values to demonstrate their use.

Uploaded by

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

Unit 4

The document discusses user-defined functions in C. It explains that a function definition contains a function header with the name, type and parameters, and a function body with local declarations and statements. A function call passes actual parameters to the formal parameters in the function definition. Functions can return values using the return statement or have no return value if the return type is specified as void. Arrays of structures allow declaring multiple structures as array elements to represent related data like student records. Pointers declare a variable that contains the address of another variable. Examples are given of functions with and without arguments and return values to demonstrate their use.

Uploaded by

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

Unit-4

1. Explain the elements of user defined functions.


The three elements needed to make use of a user-defined function, are :
● Function definition
● Function call
● Function declaration
Definition of Functions
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
Function statements 6.A return statement
All the six elements are grouped into two parts, namely,
● Function header(First three elements)
● Function body (Second three elements)
A general format of a function definition to implement these two parts is given below:
function_type function_name(parameter list)
{
local variable declaration; executable statement1; executable statement2;
……
return statement;
}

Function Header
The function header consists of three parts: The function return type, the function name
and the formal parameter list.
Name and Type
The function type specifies the type of value that the function is expected to return to calling
function. If the function is not returning anything, then we need to specify the return type as
void.
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.
Function Body
The function body contains the declarations and statements necessary for performing the
required task. The body enclosed in braces, contains three parts, in the order given below:
● Local declarations that specify the variables needed by the function.
● Function statements that perform the task of the function.
A return statement that returns the value evaluated by the function.
Return Values and Their Types
A function may or may not send back any value to the calling function. If it is returning any
value, then it is done using the return statement. All functions, by default return integer type
data. We can make function return any other type data by specifying the same as type
specifier in function header.
Function Calls
A function can be called by simply using the function name followed by a list of actual
parameters, if any, enclosed in
parentheses. Example:
void main()
{
int y;
y=mul(10,5); /* Function call */
printf(“%d\n”,y);
}
A function that does not return any value may not be used in expressions. It can be called by
simply stating its name. E.g:
printline(); clrscr(); strcpy(s1,s2);
Function Declaration
Like variables, all functions in a C program must be declared, before they are invoked. A
function declaration (function prototype) consists of four parts.
● Function type(return type)
● Function name
● Parameter list
● Terminating semicolon
The general form of function declarations is as under :
function-type function-name (parameter list);

2. Explain union and array of structures.


Unions like structure contain members whose individual data types may differ from one
another. However all the members a union share the same storage area within the
computers memory where as each member within a structure is assigned its own unique
storage area. Thus unions are used to save memory. They are useful for application
involving multiple members, where values need not be assigned to all the members at the
same time.
Like structures union can be declared using the keyword union as follows:
union item
{
int m; float p;
char c;
} code;
this declares a variable code of type union item. The union contains three members each
with a different data type. However we can use only one of them at a time. This is because if
only one location is allocated for union variable irrespective of size. The compiler allocates a
piece of storage that is large enough to access a union member we can use the same
syntax that we use to access structure members. That is
code.m code.p code.c
are all valid member variables
ARRAYS OF STRUCTURES
We use structure to describe the format of a number of related variables. For example, in
analyzing the marks obtained by a class of students, we may use a template to describe
student name and marks obtained in various subjects and then declare all the students as
structure variables. In such cases, we may declare an array of structure, each elements
of the array representing a structure variable. For example,
struct class student[100];
It defines an array called student, that consists of 100 elements. Each elements is
defined to be of the type struct class. Consider the following declaration:

struct marks
{
int subject1; int subject2; int subject3;
};
main()
{
struct marks student[3] ={ {45, 68, 81}, {75, 53, 69}, {57,36,71}}; …….
This declares the student as an array of three elements student[0], student[1], and student[2]
and initializes their members as follows:
student[0].subject1=45; student[0].subject2=68;
………….
………….
student[2].subject3=71;
An array of structures is stored inside the memory in the same way as a multi- dimensional
array.

3. Explain with example (i) Defining a pointer


(ii) declaring and accessing pointer variable.
(i) Pointer is a variable that contains an address of another variable in memory.
(ii) Accessing the address of a variable
The actual location of a variable in the memory is system dependent and therefore, the
address of a variable is not known to us immediately. The operator ‘&’ immediately
preceding a variable returns the address of the variable associated with it. For example, the
statement
p = &quantity;
would assign the address 5000 to the variable p. The &operator is called as ‘address of’
operator and can be used only with a simple variable or an array element. The following
statements are not valid.
1. &50 (pointing at constant)
2. int x[10];
&x (pointing at array name)
3. &(x+y) (pointing at expressions).
If x is an array , then expressions such as &x[0] and &x[i+3] are valid and represent the
addresses of 0th and (i+3) th elements of x.
Declaration of pointer variable
The declaration of the pointer variable takes the following form:
data type *pt_name;
This tells the compiler three things about the variable pt_name.
The asterisk ( * ) tells that the variable pt_name is a pointer variable.
pt_name needs a memory location.
pt_name points to a variable of type data type. For example,
int *ip; float *fp;
declare the variables ip and fp as a pointer variables that points to an integer and floating
point data type respectively.
/*example for pointers:swapping two numbers using pointers*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, *c, *d, temp;
clrscr() ;
printf("enter two integers:") ;
scanf("%d%d", &a, &b) ;
c=&a;
d=&b;
printf("before swapping a=%d, b=%d", a, b) ;
temp=*c;
*c=*d;
*d=temp;
printf("\n after swapping a=%d, b=%d", a, b) ;
getch() ;
}

4. Write a short note on argument but no return value.


When a function does not have arguments and no return value, main() function has no
control over the way the functions receive the input data. We could make the calling
program to read data from terminal and pass it on to the called function after data validity
checking if necessary.
We shall modify the definition of the called function to include arguments as follows:
void sum(int x, int y)
The calling function can now sent values to these arguments using function calls containing
appropriate arguments as under :
sum(a,b);
Here, x and y, the arguments used in function definition are called formal arguments. The
parameters and b used in function call of calling function are called actual arguments.
The actual and formal arguments should match in number, type, and order.
While the formal arguments must be valid variable names, the actual arguments may be
variable names, expressions,or constants.
The variables used in actual arguments must be assigned values before the function call is
made.
When a function call is made, only a copy of the values of actual arguments is passed into
the called function. What occurs inside the function will have no effect on the variables used
in the actual argument list.
The variables declared inside a function are known as local variables and therefore their
values are local to the function and cannot be accessed by any other function.
/*Function with arguments and no return value : sum of two numbers*/
#include<stdio.h>
#include<conio.h>
void sum(int, int);
void main()
{
int a,b;
clrscr();
printf("Enter two numbers :"); scanf("%d%d",&a,&b);
sum(a,b);
getch();
}
void sum(int x, int y)
{
printf("The sum is %d",x+y);
}

5. Explain function that returns one value.


Many times, we may not want to print the result of a function. Instead use it in the calling
function for further processing.
Also, to assure a high degree of portability between programs, a function is generally coded
without involving I/O operations.
E.g. : sqrt, pow, strlen etc.
A self-contained and independent function should behave like a ‘black box’ that receives a
predefined form of input and outputs a desired value. Refer figure below which illustrates the
use of two-way data communication between the calling and the called functions.
/* Functions with arguments and return values : Sum of two integers */
#include <stdio.h>
#include <conio.h>
int sum(int,int);
void main()
{
int a,b,c;
clrscr();
printf("Enter a and b :");
scanf("%d%d",&a,&b);
c=sum(a,b);
printf("Sum is %d",c);
getch();
}

int sum(int x, int y)


{
int z=x+y;
return z;
}

6. Write the use of sizeof operator with example.


The number of bytes used to store various data types depends on the system and can be
found by making use of sizeof operator. If x is a variable, then sizeof(x) returns the number
of bytes needed for the variable.

7. What is structure, define, declare and associate structure member with example.
Structure is a collection of data items of different types using a single name. Structure is
used to represent a set of attributes, such as student_name, roll_number and marks. The
individual structure elements are referred to as members.
General format of a of a structure definition is as follows :
struct tag_name
{
data_type member1;
data_type member2;
……….
……
data_type member n;
};
We can declare structure variables using the tag name anywhere in the program. For
example, the statement
struct book_bank book1, book2, book3;
declares book1, book2, and book3 as variables of type struct book_bank.
Each one of these variables has 4 members as specified by the template. The complete
declaration is like ....
struct book_bank
{
char title[20];
int author[15];
int pages;
float price;
};
struct book_bank book1,book2,book3,book3;
The members of a structure themselves are not variables. They do not occupy any memory
until they are associated with the structure variable such as book1.
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;
We can access and assign values to members of a structure. The structure members
themselves are not variables. They should be linked to the structure variables 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
book1.price book1.title book1.pages
strcpy(book1.title, “COBOL”);
strcpy(book1.author, “M.K.ROY”); book1.pages = 350;
book1. price =140;
We can also use scanf to give the values through the keyboard as under :
scanf(“%s\n”, book1.title);
scanf(“%d\n”, &book1.pages);
/*program to add two complex number using structure*/
#include<stdio.h>
#include<conio.h>
struct complex
{
float real, img;
};
void main()
{
struct complex c1, c2, c3;
printf("enter first complex number:\n") ;
scanf("%f%f", &c1.real, &c1.img);
printf("enter second complex number:\n") ;
scanf("%f%f", &c2.real, &c2.img);
c3.real=c1.real+c2.real;
c3.img=c1.img+c2.img;
printf("result is : %f+i%f", c3.real, c3.img) ;
getch() ;
}

8. How do you call, declare and define user defined function with example.
Same answer of 1st one.
Example:
/* Factorial of n using functions*/
#include <stdio.h>
#include <conio.h>
long fact(int);
void main()
{
int n;
clrscr();
printf("Enter n :");
scanf("%d",&n);
printf("Factorial of %d is %ld",n,fact(n));
getch();
}

long fact(int n)
{
long f=1;
int i;
for(i=1;i<=n;i++)
f*=i;
return f;
}
9. Write a note on pointer arithmetic.
Like other variables, pointer variables can be used in expressions. For example, if p1 and p2
are properly declared and initialized pointers, then the following statements are valid.

y=*p1 * *p2; same as (*p1) * (*p2)


sum=sum + *p1;
*p2=*p2 + 10;

C allows us to add integers to or subtract integers from pointers, as well as to subtract one
pointer from another. p1 + 4, p2 – 2 and p1 – p2 are all allowed. If p1 and p2 are both
pointers to the same array, then p2 – p1 gives the number of elements between p1 and p2.
We may also use short-hand operators with the pointers. p1++; --p2; sum += *p2; Pointers
can also be compared using the relational operators. p1>p2, p1==p2, p1!=p2
But pointers cannot be used in division or multiplication. Similarly two pointers cannot be
added. Thus expressions such as p1/p2 or p1*p2 or p1/3 are not allowed.

10. What is union. How does it differ from structure with example.
Unions like structure contain members whose individual data types may differ from one
another. However all the members a union share the same storage area within the
computers memory where as each member within a structure is assigned its own unique
storage area. Thus unions are used to save memory. They are useful for application
involving multiple members, where values need not be assigned to all the members at the
same time.
Like structures union can be declared using the keyword union as follows:
union item
{
int m;
float p;
char c;
} code;
this declares a variable code of type union item. The union contains three members each
with a different data type. However we can use only one of them at a time. This is because if
only one location is allocated for union variable irrespective of size. The compiler allocates a
piece of storage that is large enough to access a union member we can use the same
syntax that we use to access structure members. That is
code.m code.p code.c

are all valid member variables. During accessing we should make sure that we are
accessing the member whose value is currently stored. For example a statement such as
code.m=456; code.p=456.78;
printf(“%d”,code.m); would produce erroneous result.
In effect a union creates a storage location that can be used by one of its members at a time.
When a different number is assigned a new value the new value supercedes the previous
members value. Unions may be used in all places where a structure is allowed. The notation
for accessing a union member that is nested inside a structure remains the same as for the
nested structure.
11. What are the advantages of using pointer.
There are a number of reasons for using pointers.
1. Pointer can be used to return multiple values from a function.
2. Pointers are more efficient in handling arrays and the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
5. The use of a pointer array to character strings results in saving of data storage space
in memory.
6. Pointers allow C to support dynamic memory management. The real power of C lies
in the proper use of pointers.

12. Write categories of function.


C function can be classified into two categories, namely, library functions and user- defined
functions. main is an example of user-defined functions. printf and scanf belong to the
category of library functions.

You might also like