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

C Unit 4

best notes

Uploaded by

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

C Unit 4

best notes

Uploaded by

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

Functions and Structures

Function is a part of a program that performs a specific and well-defined task.


It reduces the complexity of the program. There are 2 types of c functions
● Built-in functions or library functions.
● User defined functions.
Built-in functions (standard library functions): These are the functions
whose meaning is defined in some header files.
e.g.: printf(),scanf(),getch(),putchar(), etc defined in stdio.h.
sqrt(n),pow(r,n),abs(x) defined under math.h
strcpy(),strlen(),strupr() etc under string.h
isalpha(), toupper() etc are defined under ctype.h

User defined functions: User can define one or more functions within a
program to perform special tasks. They are written for the requirement of
its creator. They contain the block of statements to perform a task. The
execution always starts from the main (), all other functions are invoked or called
from the main().
Need for user defined functions
User defined functions are used for the following reasons
1) To improve the readability of code.
2) Improves the reusability of the code.
3) Debygging of the code would be easier.
4) Reduces the overall complexity of the program.
General Syntax of Function Definition : A function definition consists of
a function header and function body. The function header contains function's
name, return type and parameters. The general form of function definition
is as follows
R_type function name (parameter list)
{
Local variable declaration;
Statement 1;

Statement n;
return (value computed);
}
R_Type🡪 the data type of the return value. If nothing is returned the data type
is void.
Parameter list 🡪 list of variables that receives value from calling function.
return 🡪 is a keyword used to return a value from sub function to calling
function.
Components of user defined functions: The user defined function has
multiple parts
Function declaration or prototype.
Function call.
Function definition.
Return statement.
Function prototype is the declaration of a function with return type, function
name and argument list. Function prototype is optional in c while
compulsory in c++.
R_type is the data type of the value the function returns. Some functions
perform the operations without returning a value then the return type is void.

Function Name is the name of the function which is a valid identifier.


Parameter list is optional i.e. a function may contain no parameters.
Function Body: The function body contains a collection of statements that
define what the function does.
The return statement: return is a key word used to send the output of the function
back to the calling function. It is a means of communication from calling function to
the called function. After processing, the computed value is returned back to the
calling function.
Syntax: return;
or return (value);
st
The 1 return returns the control back to the calling function.
The return (value) returns both the control and value back to the calling function.

Actual parameters and Formal parameters:


Actual parameters: The variables used in the calling function are called Actual
parameters since they are accepted in the calling function.
Formal parameters: The variables used in the function definition are called formal
parameters. These are not the accepted values. They have a copy of actual
parameters.
Local variable and global variable: Variables whose existence is known only
within the function are called as local or automatic variables. Variables whose
existence is known to the entire program are called as global variables. These
variables are active & alive throughout the program. Any function can access the
global variable & change its value.
Note: “There is a one to one correspondence between the actual parameters and the
formal parameters” i.e. the no. of actual parameters is equal to the no of formal
parameters. Also the data type of actual parameter & formal parameter must be
same.
Categories of user defined functions: There are 4 types of functions based
on argument list and return value
1. Function with no arguments and no return value.
2. Function with no arguments and a return value.
3. Function with arguments and no return value.
4. Function with arguments and with return value.
1. Function with no arguments and no return value: In this case 1st
function does not passing any arguments and 2 nd function does not sending
any return value back.
#include<stdio.h>
main()
{
add();
}
add()
{
int a=5,b=5,c;
c=a+b;
printf(“%d+%d=%d”,a,b,c);
}
In this program main ( ) function is not passing any arguments and add()
function does not sending any return value.
2. Function with arguments and no return value: In this case first function is
passing arguments and second function does not sending any return value.
#include<stdio.h>
main()
{
int a,b;
printf(“enter a and b value”);
scanf(“%d%d”,&a,&b);
add(a,b);
}
add (int m,int n)
{
int c;
c=m+n;
printf (“%d+%d=%d”,a,b,c);
}
In this program main () function is passing the arguments a, b (actual
parameters) and m and n are the formal parameters. The add function does not
return any value.
3.Function with arguments and return value: In this case first function is
passing arguments and second function is sending the return value.
#include<stdio.h>
main()
{
int a,b, res;
printf(“enter a and b values\n”);
scanf(“%d%d”,&a,&b);
res=add (a,b);
printf(“sum=%d”,res);
}
int add(int m,int n)
{
int c;
c=m+n;
return(c);
}
In this program main () function passing the arguments a and b to the
parameters m and the add function returns a computed value of c. The return
type of this value is int .
4.Function with no arguments and with return value. In this case first
function is not passing arguments and second function is sending the return
value.
#include<stdio.h>
main()
{
int res;
res=add ();
printf(“sum=%d”,res);
}
int add(int m,int n)
{
int a,b,c;
printf(“enter a and b values\n”);
scanf(“%d%d”,&a,&b);
c=a+b;
return(c);
}
In this program main ( ) function is not passing any arguments and add()
function is sending the return value back to the calling function.

Recursive functions: The process by which a function calls itself is called


recursion. Or Recursion is the process of defining a problem (or the solution to a
problem) in terms of itself. The function involved in the process is called
recursive function. Recursive functions are called repeatedly until some
specified condition is satisfied.
e.g: 1. Factorial 5! =5x4x3x2x1
Generally n! = n (n-1)!
2. Fibonacci series: A series that starts with 0 and 1, the subsequent
member of the series is obtained by adding the immediate two numbers.

0 1 1 2 3 5 8
Advantages of Recursion:
(i) Reduce unnecessary calling of function.
(ii) When the iterative solution is complex, recursion solve the problem in an easy
way
Program to find the factorial of the given number using recursive
function.
#include<stdio.h>
main()
{
int n;
printf(“Enter any nonnegative integer\n”); scanf(“%d”,&n);
printf(“Factorial of %d is = %d\n”,n, fact(n));
getch();
}
int fact(int n)
{
if(n==0)
return(1);
else
return(n*fact(n-1));
}
Program to generate N Fibonacci numbers using recursive function
#include<stdio.h>
main()
{
int i,n;
printf(“Enter number of elements \n”); scanf(“%d”,&n);
printf(“\nFibonacci number\n\n”);
for(i=1;i<=n;i++)
printf(“%d\t”,fibo(i));
getch();
}
int fibo(int k)
{
if(k==1)
return(0);
if(k==2)
return(1);
else
return(fibo(k-1)+fibo(k-2));
}
Types of functions based on passing parameters:
The communication between calling function and called function is done through
parameters. Based on passing parameter from calling function to called function,
there are 2 types of functions
1. Call by value (pass by value)
2. Call by address (pass by address)
Call by value: The process of calling the function by passing the value is
called call by value.
Program to illustrate the function using call by value.
#include<stdio.h>
void main()
{
int a=10,b=20;
clrscr();
printf( “Before interchange\n “a=%d\t b==%d\t”,a,b);
swap(a,b);
printf( “After interchange\n “a=%d\t b==%d\t”,a,b);
getch();
}
void swap(int x,int y)
{
int temp
temp=x;
x=y;
y=temp;
}
In call by value, any change made to the formal parameters will not change the
value of actual parameters.

Call by address (pass by address): In call by address, the memory


address of the arguments is passed. Hence the receiving parameter must
be a pointer.

Program to illustrate the function using call by address.


#include<stdio.h>
void main()
{
int a=10, b=20;
clrscr();
printf( “Before interchange\n “a=%d\t b==%d\t”,a,b);
swap(&a,&b);
printf( “After interchange\n “a=%d\t b==%d\t”,a,b);
getch();
}
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
In call by address, any change made to the formal parameter will change the
original value of the variables.
Nesting of functions: A function defined inside another function is known as
“nested function”. Nested function is not supported by C because the compiler
cannot find the correct memory location of the inner function. We can only
declare a function within another function.
void main()
{
printf("INDIA\n");
function_one();
getch();
}
void function_one()
{
printf("KARNATAKA\n");
function_two();
}
void function_two()
{
printf("TUMKUR\n");
}
Advantages of functions:

● Program development and testing made easy:


● Code sharing becomes possible :
● Code re-usability increases :
● Increases program readability :
● Function facilitates abstraction and reduces complexity :

Pass Array to Functions in C


In C, the whole array cannot be passed as an argument to a function. However, you can
pass a pointer to an array without an index by specifying the array’s name.
Arrays in C are always passed to the function as pointers pointing to the first element of the
array.

Syntax
In C, we have three ways to pass an array as a parameter to the function. In the function
definition, use the following syntax:
( array_type array_name[size], ...);
return_type foo
Mentioning the size of the array is optional. So the syntax can be written as:
return_type foo ( array_type array_name[], ...);
In both of the above syntax, even though we are defining the argument as
array it will still be passed as a pointer. So we can also write the syntax as:
return_type foo( array_type* array_name, ...);
But passing an array to function results in array decay due to which the
array loses information about its size. It means that the size of the array or
the number of elements of the array cannot be determined anymore.

Examples of Passing Array to Function in C


Example 1: Checking Size After Passing Array as Parameter

// C program to pass the array as a function and check its size

#include <stdio.h>

#include <stdlib.h>

// Note that arr[] for fun is just a pointer even if square

// brackets are used. It is same as

// void fun(int *arr) or void fun(int arr[size])

void func(int arr[8])

{
printf("Size of arr[] in func(): %d bytes",

sizeof(arr));

// Drive code

int main()

int arr[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };

printf("Size of arr[] in main(): %dbytes\n",

sizeof(arr));

func(arr);

return 0;

Output
Size of arr[] in main(): 32bytes
Size of arr[] in func(): 8 bytes
As we can see,
 The size of the arr[] in the main() function (where arr[] is declared) is 32 bytes which is =
sizeof(int) * 8 = 4 * 8 = 32 bytes.
 But in the function where the arr[] is passed as a parameter, the size of arr[] is shown as
8 bytes (which is the size of a pointer in C).
It is due to the fact that the array decays into a pointer after being passed as a parameter.
One way to deal with this problem is to pass the size of the array as another parameter to
the function. This is demonstrated in the below example.
STRUCTURES
A structure is a meaningful collection of items of different data types. A structure
allows the user to create and manipulate a set of different types of data items.
The reserve word struct is used to construct structure. Structures are
considered as user-defined data types or derived data types or record types.
Note: Arrays are used to identify a group of similar data items using a common
name. Structures are used to identify a group of dissimilar data items using a
common name.
Definition and declaration of structure: The syntax of structure definition is
struct structure_name
{
type1 data1;
type2 data2;
……
type n data n;
};
The definition of structure does not create memory space in which values can be
stored. This is achieved by declaring the structure.
Syntax of structure declaration:
The syntax of structure declaration is

Member operator or dot operator: Every structure member is accessed by


writing a dot operator (‘.’) between a member and the dot operator. This
operator will apply to structure member only but not the entire structure
variable.
Memory allocation for structure variables: consider the following structure
definition and declaration,
struct student
{
char name[20]; //20 bytes
int age; //2 bytes
float fee; //4 bytes
};
struct student s;
The structure student contains 3 members: a character quantity name, an
integer quantity age and a float quantity fee. This structure stores 26 bytes of
memory.
name(string) int age float fee
2 bytes 4 bytes
20 bytes

26 bytes
Program to illustrate the use of structures
#include<stdio.h>
main() enter the value of a,b and c
{ #
struct example 25
{ 15.7
char a; value of a=#
int b; value of b=25
float c; value of c=15.700000
};
struct example e;
clrscr();
printf(“enter the value of a,b and c\n”);
scanf(“%c%d%f”, &e.a,& e.b,&e.c);
printf(“ value of a=%c\n value of b=%d\n value of c=%f\n”, e.a,e.b,e.c);
getch()
}

A program to read the name, age and fee of two students:

main ()
{
struct student Enter the 2nd student name, age and fee
{ Raja 35 500.00
char name[20]; st
The 1 student details are
int age; Kumar 25 300.75
float fee; The 2nd student details are
};
Raja 35 500.00
struct student s1, s2;
s1.name=strcpy(name, “Kumar”);
s1.age=25;
s1.fee=300.75;
printf(“Enter the 2nd student name, age and fee”);
scanf(“%s%d%f”,s2.name,& s2.age,& s2.fee);
printf(“The 1st student details are\n”);
printf(“name=%s \t Age= %d\t Fees= %f ”,s1.name, s1.age, s1.fee);
printf(“The 2nd student details are\n”);
printf(“name=%s \t Age= %d\t Fees= %f ”, s2.name, s2.age, s2.fee);
getch()
}
Copying and Comparing Structure Variables
Two variables of the same structure type can be copied the same way as ordinary
variables.
If e1 and e2 belong to the same type, then the following statement is valid. e1 = e2, and
e2 = e1;
However, the statements that are shown here:
e1 < e2; and e1 != e2; are not permitted.
C language doesn't permit any logical operations on structure variables.
We can compare two structure variables but comparison of members of a structure can
only be done individually.
C program to compare the structure variables

In C programming language, a structure is a collection of different datatype variables, which


are grouped together under a single name.

Declaration and initialization of structures

The general form of a structure declaration is as follows −

datatype member1;
struct tagname{
datatype member2;
datatype member n;
};

Here,

 struct is a keyword.
 tagname specifies the name of structure.
 member1, member2 specifies the data items that make up structure.

For example,

struct book{
int pages;
char author [30];
float price;
};

Structure variables

There are three methods of declaring structure variables, which are as follows −

First method
struct book{
int pages;
char author[30];
float price;
}b;
Second method
struct{
int pages;
char author[30];
float price;
}b;
Third method
struct book{
int pages;
char author[30];
float price;
};
struct book b;
Initialization and accessing of structures

The link between a member and a structure variable is established by using a member
operator (or) a dot operator.

Initialization can be done in the following methods −

First method
struct book{
int pages;
char author[30];
float price;
} b = {100, “balu”, 325.75};
Second method
struct book{
int pages;
char author[30];
float price;
};
struct book b = {100, “balu”, 325.75};
Third method by using a member operator
struct book{
int pages;
char author[30];
float price;
};
struct book b;
b. pages = 100;
strcpy (b.author, “balu”);
b.price = 325.75;

Example

Following is the C program for the comparison of structure variables −

Live Demo

struct class{
int number;
char name[20];
float marks;
};
main(){
int x;
struct class student1 = {001,"Hari",172.50};
struct class student2 = {002,"Bobby", 167.00};
struct class student3;
student3 = student2;
x = ((student3.number == student2.number) &&
(student3.marks == student2.marks)) ? 1 : 0;
if(x == 1){
printf("
student2 and student3 are same

");
printf("%d %s %f
", student3.number,
student3.name,
student3.marks);
}
else
printf("
student2 and student3 are different

");
}

Output

When the above program is executed, it produces the following output −

student2 and student3 are same


2 Bobby 167.000000

Operations on struct variables in C


In C, the only operation that can be applied to struct variables is assignment. Any other
operation (e.g. equality check) is not allowed on struct variables.
For example, program 1 works without any error and program 2 fails in compilation.
Program 1

#include <stdio.h>

struct Point {

int x;

int y;

};

int main()

struct Point p1 = {10, 20};

struct Point p2 = p1; // works: contents of p1 are copied to p2


printf(" p2.x = %d, p2.y = %d", p2.x, p2.y);

getchar();

return 0;

Program 2

#include <stdio.h>

struct Point {

int x;

int y;

};

int main()

struct Point p1 = {10, 20};

struct Point p2 = p1; // works: contents of p1 are copied to p2

if (p1 == p2) // compiler error: cannot do equality check for

// whole structures

printf("p1 and p2 are same ");

getchar();
return 0;

Array of structures: A single variable that represents a structure creates


memory space to store one set of information. We may increase the creation of
memory space using array. In array of a structure. We create the array of the
entire template.
e.g: struct student
{
int regno;
char name[‘ ‘];
float fee;
}s[50];
This structure defines an array of 50 students, for each student all the
memory locations are declared inside structure.
1st student info is 🡪 s[0].name, s[0].regno and s[0].fee
2nd student info is 🡪 s[1].name, s[1].regno and s[1].fee

50th student info is🡪s[49].name, s[49].regno and s[49].fee


Program to accept N student information and to display all students
information
#include<stdio.h>
main()
{
struct student
{
int reg_no;
char name[20];
char comb[6];
float fees;
};
struct student s[20];
int n,i;
printf(“enter number of students:\n”);
scanf(“%d”,&n);
printf(“enter reg_no, name,combination,fees\n”);
for(i=0;i<n;i++)
scanf(%d%s%s%f”,&s[i].reg_no,s[i].name, s[i].comb, &s[i].fees);
printf(“\n%d%s%s%f\n”,s[i].reg_no,s[i].name,s[i].comb, s[i].fees);
getch();
}
Structure within a structure (Nested structures or embedded
structures):
A structure where one structure is enclosed within another structure is called as
a nested structure or structure within a structure or embedded structure.
Program to illustrate structure with in a structure
#include<stdio.h>
main()
{
struct date enter student reg_no and name
{ 1111 Raja
int year; enter date of birth of the student
int month; 3 12 2010
int day;
}; student information
struct student reg_no: 1111
{ name : Raja
int reg_no; date of birth: 3-12-2010
char name[20];
struct date dob;
}s;
printf(“enter student reg_no and name\n”);
scanf(“%d%s”,&s.reg_no, s.name);
printf(“enter date of birth of the student\”); scanf(%d%d
%d”,&s.dob.day,&s.dob.month,&s.dob.year)
printf(“student information\n\n”);
printf(“reg_no : %d\n”,s.reg_no);
printf(“name : %s\n”,s.name);
printf(“date of birth: %d-%d-%d”,s.dob.day,s.dob.month,s.dob.year);
getch();
}

****************

You might also like