[go: up one dir, main page]

0% found this document useful (0 votes)
10 views22 pages

Function and Structure

The document provides an overview of functions in C programming, detailing their definition, syntax, and rules for writing them. It explains the types of functions, including built-in and user-defined functions, and discusses how to pass arrays and arguments to functions. Additionally, it covers recursion, its advantages, and disadvantages, highlighting the importance of functions in organizing code and enhancing reusability.

Uploaded by

ravalkaran187
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)
10 views22 pages

Function and Structure

The document provides an overview of functions in C programming, detailing their definition, syntax, and rules for writing them. It explains the types of functions, including built-in and user-defined functions, and discusses how to pass arrays and arguments to functions. Additionally, it covers recursion, its advantages, and disadvantages, highlighting the importance of functions in organizing code and enhancing reusability.

Uploaded by

ravalkaran187
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/ 22

FUNCTION

A function is a block of code that performs a particular task. There are times when
we need to write a particular block of code for more than once in our program. This
may lead to bugs and irritation for the programmer. C language provides an
approach in which you need to declare and define a group of statements once and
that can be called and used whenever required. This saves both time and space.

Writing a Function:Function Definition Syntax :

return_type function_name ( Parameter List ) // Function Header


{ // Function Body Start
Local declaration ;
Statements ;
} // Function Body End

Different Sub parts of Above Syntax:


return-type

1. Return Type is Type of value returned by function


2. Return Type may be “Void” if function is not going to return a value.

function-name

1. It is Unique Name that identifies function.


2. All Variable naming conversions are applicable for declaring valid
function name.

parameters

1. Comma-separated list of types and names of parameters


2. Parameter injects external values into function on which function is going to
operate.
3. Parameter field is optional.
4. If no parameter is passed then no need to write this field

value

1. It is value returned by function upon termination.


2. Function will not return a value if return-type is void.

Example :

#include<stdio.h>
int sum(int n1,int n2)
{
return(n1+n2);
}

int main()
{
int num1=11,num2=22;
int result;

result = sum(num1,num2);
printf("\nResult : %d",result);
return(0);
}

Rules of Writing Function in C Programming

Rule 1. C program is a collection of one or more functions


void main()
{
pune();
mumbai();
maharashtra();
}

Rule 2. A function gets called when the function name is followed by a


semicolon.
void main( )
{
display( ) ;
}

Rule 3 : A function is defined when function name is followed by a pair of


braces in which one or more statements may be present.
void display( )
{
statement 1 ;
statement 2 ;
statement 3 ;
}

Rule 4. Any function can be called from any other function.( main also )
void main( )
{
message( ) ;
}

void message( )
{
printf ( "\nWe are going to call main" ) ;
main( ) ;
}

Rule 5.A function can be called any number of times.


void main()
{
message( );
message( );
}

void message()
{
printf("\nLearning C is very Easy");
}

Rule 6. The order in which the functions are defined in a program and the
order in which they get called need not necessarily be same
void main( )
{
message1( ) ;
message2( ) ;
}
void message2( )
{
printf ( "\n I am First Defined But Called Later " ) ;
}
void message1( )
{
printf ( "\n I am Defined Later But Called First ") ;
}

Rule 7. A function can call itself ( Process of Recursion )


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

Rule 8. A function can be called from other function, but a function cannot
be defined in another function.
Example-
main( )
{
printf ( "\nI am in main" ) ;
italy( ) ;
printf ( "\nI am finally back in main" ) ;
}
italy( )
{
printf ( "\nI am in italy" ) ;
brazil( ) ;
printf ( "\nI am back in italy" ) ;
}
brazil( )
{
printf ( "\nI am in brazil" ) ;
argentina( ) ;
}
argentina( )
{
printf ( "\nI am in argentina" ) ;
}

And the output would look like...


I am in main
I am in italy
I am in brazil
I am in argentina
I am back in italy
I am finally back in main

Advantages of user defined functions

1. User defined functions helps to decompose the large program into small
segments which makes programmer easy to understand, maintain and
debug.
2. If repeated code occurs in a program. Function can be used to include those
codes and execute when needed by calling that function.
3. Programmer working on large project can divide the workload by making
different functions.

TYPES OF FUNCTION

There are two types of function in c

1) Built in(library) functions – these functions are provided by the system and
stored in library , therefore it is called as Library function” example scanf(),
printf(),strlen(),strcpy() etc. To use these functions we need to include
appropriate header file in C program.
2) User defined functions – these functions are defined by the user at the time
of writing the program.
User-defined functions can be categorized as:
1. Function with no arguments and no return value

In this type of functions ,the user defined function does not receive any input
and does not send back any result to the calling function.
Ex:
void msg();
void main()
{
msg();
}
void msg()
{
printf(“hello world\n”);
}

2. Function with no arguments and return value

int sum();
void main()
{
int x;
x=sum();
printf(“\n Sum=%d”,x);
}
int sum()
{
int a,b;
scanf(“%d%d”,&a,&b);
return(a+b);
}

3. Function with arguments but no return value

In this category of functions, the called function receives one or more input
values, but does not send any output(return value) to the calling function
Ex:
void sum(int,int);
void main()
{
int a,b;
scanf((“%d%d”,&a,&b);
sum(a,b);
}
void sum(int p, int q)
{
int r;
r=a+b;
printf(“sum of two numbers=%d\n”,r);
}

4. Function with arguments and return value.

*Program to demonstrate the working of user defined function*/


#include <stdio.h>
int add(int a, int b);
int main(){
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=add(num1,num2);
printf("sum=%d",sum);
return 0;
}
int add(int a,int b)
{
int add;
add=a+b;
return add;
}

Array Definition :
Array is collection of elements of similar data types .
Passing array to function :

Rules for passing an array to a function –

1) The function must be called by passing only the name of the array.
2) In the function definition, the formal parameter must be an array type; the of
the array does not need to be specified.
3) The function prototype must show that the argument is an array.

Array can be passed to function by two ways :

1. Pass Entire array


2. Pass Array element by element

1 . Pass Entire array

 Here entire array can be passed as a argument to function .


 Function gets complete access to the original array .
 While passing entire array Address of first element is passed to function , any
changes made inside function , directly affects the Original value .
 Function Passing method : “Pass by Address“

#include<stdio.h>
#include<conio.h>
//---------------------------------
void fun(int arr[])
{
int i;
for(i=0;i< 5;i++)
arr[i] = arr[i] + 10;
}
//--------------------------------
void main()
{
int arr[5],i;
clrscr();
printf("\nEnter the array elements : ");
for(i=0;i< 5;i++)
scanf("%d",&arr[i]);

printf("\nPassing entire array .....");


fun(arr); // Pass only name of array

for(i=0;i< 5;i++)
printf("\nAfter Function call a[%d] : %d",i,arr[i]);

getch();
}

Output :

Enter the array elements : 1 2 3 4 5

Passing entire array .....


After Function call a[0] : 11
After Function call a[1] : 12
After Function call a[2] : 13
After Function call a[3] : 14
After Function call a[4] : 15

2 . Pass Array element by element

 Here individual elements are passed to function as argument.


 Duplicate carbon copy of Original variable is passed to function .
 So any changes made inside function does not affects the original value.
 Function doesn’t get complete access to the original array element.
 Function passing method is “Pass by Value“

C Program to Pass Array to Function Element by Element :


#include< stdio.h>
#include< conio.h>
//---------------------------------
void fun(int num)
{
printf("\nElement : %d",num);
}
//--------------------------------
void main()
{
int arr[5],i;
clrscr();
printf("\nEnter the array elements : ");
for(i=0;i< 5;i++)
scanf("%d",&arr[i]);

printf("\nPassing array element by element.....");

for(i=0;i< 5;i++)
fun(arr[i]);

getch();
}

Output :
Enter the array elements : 1 2 3 4 5
Passing array element by element.....
Element : 1
Element : 2
Element : 3
Element : 4
Element : 5

Disadvantage of this Scheme:

1. This type of scheme in which we are calling the function again and again but
with different array element is too much time consuming. In this
scheme we need to call function by pushing the current status into the
system stack.
2. It is better to pass complete array to the function so that we can save some
system time required for pushing and popping.
Passing Argument to Function :

1. In C Programming we have different ways of parameter passing schemes


such as Call by Value and Call by Reference.
2. Function is good programming style in which we can write reusable code that
can be called whenever require.
3. Whenever we call a function then sequence of executable statements gets
executed. We can pass some of the information to the function for processing
called argument.

Two Ways of Passing Argument to Function in C Language :

1. Call by Reference
2. Call by Value

call by value call by reference


In call by value, a copy of actual In call by reference, the location
arguments is passed to formal (address) of actual arguments is passed
arguments of the called function and any to formal arguments of the called
change made to the formal arguments in function. This means by accessing the
the called function have no effect on the addresses of actual arguments we can
values of actual arguments in the calling alter them within from the called
function. function.
In call by value, actual arguments will In call by reference, alteration to actual
remain safe, they cannot be modified arguments is possible within from called
accidentally. function; therefore the code must handle
arguments carefully else you get
unexpected results.
#include<stdio.h> #include<stdio.h>

void interchange(int number1,int void interchange(int *num1,int *num2)


number2) {
{ int temp;
int temp; temp = *num1;
temp = number1; *num1 = *num2;
number1 = number2; *num2 = temp;
number2 = temp; }
}
int main() {
int main() {
int num1=50,num2=70;
int num1=50,num2=70; interchange(&num1,&num2);
interchange(num1,num2);
printf("\nNumber 1 : %d",num1);
printf("\nNumber 1 : %d",num1); printf("\nNumber 2 : %d",num2);
printf("\nNumber 2 : %d",num2);
return(0);
return(0); }
}
Output :
Output :
Number 1 : 70
Number 1 : 50 Number 2 : 50
Number 2 : 70

Passing 1-D Array Element by Element to function


#include<stdio.h>

void show(int b[3]);

void main()
{
int arr[3] = {1,2,3};
int i;
for(i=0;i<3;i++)
show(arr[i]);
}

void show(int x)
{
printf("%d ",x);
}

Passing Multi-dimensional Arrays to Function

To pass two-dimensional array to a function as an argument, starting address of


memory area reserved is passed as in one dimensional array

Example to pass two-dimensional arrays to function

#include
void Function(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 */
return 0;
}
void Function(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

Function With Parameter

add(a,b);

1. Here Function add() is Called and 2 Parameters are Passed to Function.


2. a,b are two Parameters.

Function Call Without Passing Parameter :

Display();

What is Actual Definition of Parameter ?

In computer programming, a parameter is a special kind of variable, used in a


subroutine to refer to one of the pieces of data provided as input to the
subroutine.These pieces of data are called arguments.

Note :

1. Parameter Means Values Supplied to Function so that Function can


Utilize These Values.
2. Parameters are Simply Variables.
3. Difference between Normal Variable and Parameter is that “These
Arguments are Defined at the time of Calling Function“.
4. Syntactically We can pass any number of parameter to function.
5. Parameters are Specified Within Pair of Parenthesis .
6. These Parameters are Separated by Comma (,)

Display(a,b,c,d,e);

 Parameter : The names given in the function definition are called


Parameters.
 Argument : The values supplied in the function call are called Arguments.

Formal Parameter :

 Parameter Written In Function Definition is Called “Formal Parameter”.

void main()
{
int num1;
display(num1);
}

void display(int x)
{
-----------
-----------
}

 x is “Formal Parameter“

Actual Parameter :

 Parameter Written In Function Call is Called “Actual Parameter”.

void main()
{
int num1;
display(num1);
}

void display(int x)
{
-----------
-----------
}

 num1 is “Actual Parameter“

RECURSION

A function that calls itself is known as recursive function and this technique is
known as recursion.

void recursion()
{
recursion(); /* function calls itself */
}

int main()
{
recursion();
}

Factorial recursion Fibonacci recursion


#include<stdio.h> int fibonaci(int i)
int fact(int); {
int main(){ if(i == 0)
int num,f; {
printf("\nEnter a number: "); return 0;
scanf("%d",&num); }
f=fact(num); if(i == 1)
printf("\nFactorial of %d is: %d",num,f); {
return 0; return 1;
} }
return fibonaci(i-1) + fibonaci(i-2);
int fact(int n){ }
if(n==1)
return 1; int main()
else {
return(n*fact(n-1)); int i;
} for (i = 0; i < 10; i++)
{
printf("%d\t%n", fibonaci(i));
}
return 0;
}

Advantages and Disadvantages of Recursion

Recursion is more elegant and requires few variables which make program clean.
Recursion can be used to replace complex nesting code by dividing the problem into
same problem of its sub-type.

In other hand, it is hard to think the logic of a recursive function. It is also difficult
to debug the code containing recursion.

STRUCTURE

Structure is the collection of variables of different types under a single name for
better handling. For example: You want to store the information about person
about his/her name, citizenship number and salary. You can create these
information separately but, better approach will be collection of these information
under single name because all these information are related to person.

Structure Definition in C

Keyword struct is used for creating a structure.

Syntax of structure

struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};

Example of Structure

struct Book
{
char name[15];
int price;
int pages;
};
Here the struct Book declares a structure to hold the details of book which
consists of three data fields, namely name, price and pages. These fields are called
structure elements or members. Each member can have different data type,like
in this case, name is of char type and price is of int type etc. Book is the name of
the structure and is called structure tag.

Declaring Structure Variables

It is possible to declare variables of a structure, after the structure is defined.


Structure variable declaration is similar to the declaration of variables of any other
data types. Structure variables can be declared in following two ways.

1) Declaring Structure variables separately

struct Student
{
char[20] name;
int age;
int rollno;
};

struct Student S1 , S2; //declaring variables of Student

2) Declaring Structure Variables with Structure definition

struct Student
{
char[20] name;
int age;
int rollno;
} S1, S2 ;
Here S1 and S2 are variables of structure Student. However this approach is not
much recommended.

Accessing Structure Members

Structure members can be accessed and assigned values in number of ways.


Structure member has no meaning independently. In order to assign a value to a
structure member, the member name must be linked with the structure variable
using dot . operator also called period or member access operator.

struct Book
{
char name[15];
int price;
int pages;
} b1 , b2 ;

b1.price=200; //b1 is variable of Book type and price is member of Book

We can also use scanf() to give values to structure members through terminal.

scanf(" %s ", b1.name);


scanf(" %d ", &b1.price);

Structure Initialization

Like any other data type, structure variable can also be initialized at compile time.

struct Patient
{
float height;
int weight;
int age;
};

struct Patient p1 = { 180.75 , 73, 23 }; //initialization


or,
struct patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;

Accessing members of a structure

There are two types of operators used for accessing members of a structure.

1. Member operator(.)
2. Structure pointer operator(->)Any member of a structure can be accessed
as: structure_variable_name.member_name

Uses of C structures:

1. C Structures can be used to store huge data. Structures act as a database.


2. C Structures can be used to send data to the printer.
3. C Structures can interact with keyboard and mouse to store the data.
4. C Structures can be used in drawing and floppy formatting.
5. C Structures can be used to clear output screen contents.
6. C Structures can be used to check computer’s memory size etc.
typedef
Using typedef we can assign a new name to an existing data-type or a complex
data-type. It will be said to be user defined data type. Variables can be defined
using this user defined data type; once it is established.
Its general form is
Syntax:Typedef type new-type;
Example. typedef int tool;
tool is the new user defined data type and can be used in place of int. and we can
use
tool x, y, z; in place of int x, y, z;
It is to be noted that new data-type is not established but a new name is given to
existing data-type.
Typedef feature is particularly convenient for structures since its use
eliminates the repeated use of struct tag while defining variables. Also the new
name often suggests the purpose of the structure.
We can write
typedef struct emp
{
char name [15];
int emp_no;
float salary;
} record;
And define variables of struct emp using record e1, e2, e3;

Array of Structure

We can also declare an array of structure. Each element of the array representing
a structure variable. Example : struct employee emp[5];

The above code define an array emp of size 5 elements. Each element of array
emp is of type employee

#include< stdio.h>
#include< conio.h>
struct employee
{
char ename[10];
int sal;
};

struct employee emp[5];


int i,j;
void ask()
{
for(i=0;i<3;i++)
{
printf("\nEnter %dst employee record\n",i+1);
printf("\nEmployee name\t");
scanf("%s",emp[i].ename);
printf("\nEnter employee salary\t");
scanf("%d",&emp[i].sal);
}
printf("\nDisplaying Employee record\n");
for(i=0;i<3;i++)
{
printf("\nEmployee name is %s",emp[i].ename);
printf("\nSlary is %d",emp[i].sal);
}
}
void main()
{
clrscr();
ask();
getch();
}

Structures within structures/Nested Structure

Structures can be nested within other structures in C programming.

Following are the two ways to assign structure within structure –

1 2
Struct dob struct student
{ {
int dd; int rollno;
char month[15]; char name[20];
int yy; struct dob
}; {
struct student int dd;
{ char month[15];
int rollno; int yy;
char name[20]; }d;
struct dob d; }s1;
}s1;

To access the members of student like rollno and name – s1.rollno and s1.name
while to access the members of dob structure s1.d.dd, s1.d.month, s1.d.yy is used.

Passing structure to function in C:

It can be done in below 3 ways.


1. Passing structure to a function by value
2. Passing structure to a function by address(reference)
3. No need to pass a structure – Declare structure variable as global

passing structure to function in C by value:

Structure as function arguments

We can pass a structure as a function argument in similar way as we pass any


other variable or array.

Example :

#include< stdio.h>
#include< conio.h>
struct student
{
char name[10];
int roll;
};
void show(struct student st);
void main()
{
struct student std;
clrscr();
printf("\nEnter student record\n");
printf("\nstudent name\t");
scanf("%s",std.name);
printf("\nEnter student roll\t");
scanf("%d",&std.roll);
show(std);
getch();
}

void show(struct student st)


{
printf("\nstudent name is %s",st.name);
printf("\nroll is %d",st.roll);
}

Passing Array of Structure to Function in C Programming

1. Array of Structure can be passed to function as a Parameter.


2. Function can also return Structure as return type.
3. Structure can be passed as follow
Example :
#include<stdio.h>
#include<conio.h>
//-------------------------------------
struct Example
{
int num1;
int num2;
}s1[3];
//-------------------------------------
void accept(struct Example s2[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nEnter num1 : ");
scanf("%d",&s2[i].num1);
printf("\nEnter num2 : ");
scanf("%d",&s2[i].num2);
}
}
//-------------------------------------
void print(struct Example s2[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nNum1 : %d",s2[i].num1);
printf("\nNum2 : %d",s2[i].num2);
}
}
//-------------------------------------
void main()
{
int i;
clrscr();
accept(s1,3);
print(s1,3);
getch();
}

Output :
Enter num1 : 10
Enter num2 : 20
Enter num1 : 30
Enter num2 : 40
Enter num1 : 50
Enter num2 : 60
Num1 : 10
Num2 : 20
Num1 : 30
Num2 : 40
Num1 : 50
Num2 : 60

Union

Unions are quite similar to the structures in C. Union is also a derived type as
structure. Union can be defined in same manner as structures just the keyword
used in defining union in union where keyword used in defining structure was
struct.

union car
{
char name[50];
int price;
};
Union variables can be created in similar manner as structure variable.
union car
{
char name[50];
int price;
}c1, c2;

OR;

union car
{
char name[50];
int price;
};
-------Inside Function-----------
union car c1, c2;

In both cases, union variables c1, c2 for type union car is created.

Accessing members of an union


The member of unions can be accessed in similar manner as that structure.
Suppose, we you want to access price for union variable c1 in above example, it
can be accessed as c1.price.

You might also like