Class-12 Computer Science UNIT 4. Programming in C Functions: Functions are the self-contained program that contains several block of stat...
UNIT 4. Programming in C
Functions:
Functions
are the self-contained program that contains several block of statement which
performs the defined task. In C language, we can create one or more functions
according to the requirements.
Usually, In C programs flows from top left to right bottom of main()
functions. We can create any number of functions below that main() functions.
These function are called from main() function. Requirement while creating a
functions.
a) Declare a
function
b) Call statement
c) Definition of
function.
After the function is called from the main(), the flow of control will
return to the main() function.
Program example of function
WAP to calculate simple interest using function
#include
float interest(void); //function declaration
int main()
{ float si;
si=interest(); //function
call
printf("Simple interst
is %.2f\n",si);
return 0;
}
float interest() //function definition
{
float p,t,r,i;
printf("Enter Principal,
Time and Rate");
scanf("%f%f%f",&p,&t,&r);
i=(p*t*r)/100;
return i; //function return
value
}
WAP to calculate area of rectangle using function.
#include
Int area (void);
int main()
{
int
a;
a
= area();
printf(“area
is %d”,a);
return
0;
}
int area()
{
int
l,b,ar;
printf(“Enter
length and breadth”);
scanf(“%d%d”,&l,&b);
ar
= l*b
return
ar;
}
Advantage:
- Big programs can be divided into smaller module using functions.
- Program development will be faster.
- Program debugging will be easier and faster.
- Use of functions reduce program complexity.
- Program length can be reduced through code reusability.
- Use of functions enhance program readability.
- Several developer can work on a single project.
- Functions are used to create own header file i.e mero.h
- Functions can be independently tested.
Recursive functions: (V.Imp)
Those function which calls itself is known as recursive function and
the concept of using recursive functions to repeat the execution of statements
as per the requirement is known as recursion. The criteria for recursive
functions are:
- The function should call itself.
- There should be terminating condition so that function calling will not be for infinite number of time.
Program example of recursive function
WAP to calculate factorial of a given number using recursion/recursive
function. (V.IMP)
#include
int fact (int);
int main()
{
int n,f;
printf("Enter any
number");
scanf("%d",&n);
f = fact(n);
printf("factorial is
%d",f);
return 0;
}
int fact (int n)
{
if (n<=1)
return 1;
else
return (n*fact(n-1));
}
WAP to calculate sum of n-natural number using recursion/recursive
function.
#include
int sum (int);
int main()
{
int n,s;
printf("Enter any
number");
scanf("%d",&n);
s = sum(n);
printf("Sum is
%d\n",s);
return 0;
}
int sum (int n)
{
if (n<=0)
return 0;
else
return (n+sum(n-1));
}
Pointer (v-imp)
Pointers in C are similar to as other variables that we use to hold the data in our program but, instead of containing actual data, they contain a pointer to the address (memory location) where the data or information can be found.
These is an important and advance concept of C language since, variables names are not sufficient to provide the requirement of user while developing a complex program. However, use of pointers help to access memory address of that entities globally to any number of functions that we use in our program.
Importance of Pointer.
While using several numbers of functions in C program, every functions
should be called and value should be passed locally. However, using pointer
variable, which can access the address or memory location and points whatever
the address (memory location) contains.
Pointer declaration
Data_type *variable_name
Eg, int *age;
Advantages
- It helps us to access a variable that is not defined within a function.
- It helps to reduce program length and complexity i.e. faster program execution time.
- It is more convenient to handle data’s.
- It helps to return one or more than one value from the functions.
#include
int main()
{
int n,*ptr;
printf("Enter any
number");
scanf("%d",&n);
ptr =&n;
printf("Value is
%d\n",*ptr);
return 0;
}
Pointers with program examples in C
Pointers are almost same as any other variable in C, as we know variables stores values (actual data). However, Instead of containing actual data pointers stores the memory location of that variable where information can be found. This is a very useful and important concept, and many complex programs are designed using pointers.
Contrast of Pointers in C
Variable names are not sufficient to fulfill all the requirements of C program. Specially, when the program are complex and relies on several function. Local variables can be accessed only within their functions. However, memory addresses can be accessed globally by all functions. One function can pass the address of local variable to another function, and the second function can use this address to access the contents of first function's local variable. Hence, we use pointer variable, which can store the address or memory location and points to whatever that memory location holds.
Advantages / Pros / Merits of Pointes in C
- It provides direct memory access.
- It helps in global access of data. [I.e. actual data that variable holds can be accessed from outside of the function.]
- It reduce length and complexity of program.
- It reduces memory consumption of a program.
- It increase execution speed.
- It more efficient to data tables using pointers.
- It helps to develop complex data structures i.e. stack, queue, list, linked list etc
- It helps in Dynamic Memory Allocations.
Disadvantages / cons / Demerits of Pointes in C
- Comparatively, pointers variables are slower than any other variables.
- Memory leak can be a major issue if dynamically allocated memory are not freed on time.
- If Pointers variable are not declared that it may lead to segmentation fault.
Why should we use Pointers?
Understanding pointer thoroughly,Let us consider, an integer variable age which value is 16, which is declared as
int age =16;
This declaration tells the C compiler:
- To reserve space in memory to hold the integer value.
- Associate the name ‘age’ with this memory location.
- Store the value 16 at this location.
[Note: Every value is stored in any memory location.]
We can display this address by following program C program
#include
int main()
{
int age=16;
printf("Address of age is %u”, &age);
printf(“Value of age is %d”, age);
return 0;
}
Output of the above program is
Address of age is 65676
Value of age is 16
[Note: &age return memory address, %u denotes unsigned integer generally used for large positive numbers i.e address of age in this case. Memory address may vary with computers. Same program may give different memory location but should give same value]
Declaration of Pointer Variable
Syntax:
datatype *pointer_varible;
For eg:
int *a;
char *b;
float *c;
Simple program example of pointers in C
#include
int main()
{
int age=16, *a;
a = &age;
printf("Address of age is %p”, a);
printf(“Value of age is %d”, *a);
return 0;
}
[Note: %p format specifier is used for printing the address to which
pointer points in C]
Output of the above program
is
Address of age is 65676
Value of age is 16
Explanation of above program
In above program two different operators are used: &(ampersand)
and *(asterisk). '&' operator gives the address of the variable associated
with it and called "address of” operator. ‘*’ operator gives the value
stored at a particular address. It is called "value at address"
operator or also called "indirection" operator.
We have declared two integer variable, first age=16 is normal integer
variable where as *a is pointer variable. After declaration statement using
above mentioned operators we store address of variable age in pointer variable
p.
Thus, in output printing ‘a’ result to address of age=16, where as, printing ‘*a’ results to the actual value 16 because pointer variable point to the value at address.
Q) Differentiate between structure and union (v.imp)
Structure |
Union |
Keyword used is “struct” |
Keyword used is “union” |
Memory occupied by structure is sum of a memory occupied by
individual data type. |
Memory occupied by union is highest memory occupied by data type
among all data type. |
Memory allocation is the total sum of all elements. |
Memory allocation is performed by sharing memory with highest
datatype. |
Can be used un complex data structure. |
Cannot be used un complex data structure. |
Cannot be used to interact with hardware. |
Suitable for interacting with hardware. |
Example: struct sample{ int a; float p; char n[10] } a;
|
Example: union sample{ int a; float p; char n[10] } a; |
File Handling in C
As we know, while program is in
execution the content of variables are temporarily stored in main memory i.e.
RAM. Data reside temporarily in RAM only at the time of program execution. After
the completion of execution data gets erased away which means the data cannot
be used for future references. To overcome this problem, file handling comes
into existence through which we can store data permanently in our secondary
storage and retrieve it whenever in future. Data are stored as datafile in our
disk.
File handling in C
Opening a data file
Syntax:
FILE
*fptr
fptr
= fopen (“filename” , ”mode”)
Where, File name can be “library.txt”,
“student.dat” ..etc
Mode:
“w” to write/store data in a data file.
“r” to display/read/retrieve/access data from
a datafile.
“a” to add/append data in existing datafile.
Store/write
data
Syntax:
fprintf(fptr , ”format specifiers”
,variables);
Eg; suppose if we want to store name, disease,
age and bed number of a patient then, it is written as
fprintf(fptr , ”%s %s %d %d”, n, d, a, b);
Where, variable are initialized as:
char n[10], d[10];
int a, b;
Program
example
1) Create a datafile “patient.txt” and store name, disease, age and bed number of a patient.
#include
int main()
{
char
n[10], d[10];
int
a, b;
FILE
*fptr;
fptr
= fopen(“patient.txt”,”w”);
printf("Enter name, disease, age and bed number");
scanf(“%s %s %d %d”, n, d, &a, &b);
fprintf(fptr,"%s %s %d %d\n”, n, d, a, b);
fclose(fptr);
return 0;
}
[Note: This program will store only single record to store multiple record we have to use loop as following programs.
2) Create a datafile “student.txt” and store name, class and marks obtained in 3 different subject for few students/n-students.
#include
int main()
{
char
n[10];
int
c, e, ne, m, i, num;
FILE
*fptr;
fptr
= fopen("student.txt","w");
printf("How many record?");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
printf("Enter name class and 3 marks");
scanf("%s %d %d %d %d",n, &c, &e, &ne, &m);
fprintf(fptr,"%s %d %d %d %d \n",n, c, e, ne, m);
}
fclose(fptr);
return 0;
}
3) Create a datafile “student.txt” and store name, class and marks obtained in 3 different subject until user press “y” / as per user requirement.
#include
int main()
{
char
n[10],ch[3];
int
c, e, ne, m;
FILE
*fptr;
fptr
= fopen("student.txt","w");
do
{
printf("Enter name class and 3 marks");
scanf("%s %d %d %d %d",n, &c, &e, &ne, &m);
fprintf(fptr,"%s %d %d %d %d\n",n, c, e, ne, m);
printf("Press Y to continue");
scanf("%s",ch);
}
while (strcmp(ch,"Y") == 0 || strcmp(ch,"y")==0);
fclose(fptr);
return 0;
}
Add/Append
data
1) A
datafile “student.txt” contain name, class and marks obtained in 3 different
subject of few students. Write a C program to add 200 more records.
#include
int main()
{
char
n[10];
int
c, e, ne, m, i;
FILE
*fptr;
fptr
= fopen("student.txt","a");
for(i=1;i<=200;i++)
{
printf("Enter name class and 3 marks");
scanf("%s %d %d %d %d", n, &c, &e, &ne, &m);
fprintf(fptr,"%s %d %d %d %d \n",n, c, e, ne, m);
}
fclose(fptr);
return 0;
}
2) A
datafile “student.txt” contain name, class and marks obtained in 3 different
subject of few students. Write a C program to add more records until user press
“y” / as per user requirement.
#include
int main()
{
char
n[10], ch[3];
int
c, e, ne, m;
FILE
*fptr;
fptr
= fopen("student.txt”,”a”);
do
{
printf("Enter name class and 3 marks");
scanf("%s %d %d %d %d", n, &c, &e, &ne, &m);
fprintf(fptr,"%s %d %d %d %d\n", n, c, e, ne, m);
printf("Press Y to continue");
scanf("%s",ch);
}
while (strcmp(ch,"Y") == 0 || strcmp(ch,"y")==0);
fclose(fptr);
return 0;
}
Read/Display/retrieve/access data from a datafile
Syntax:
fscanf(fptr , ”format specifiers” ,variables);
Eg; suppose if we want to display/read name,
disease, age and bed number of a patient from data file then, it is written as
fscanf(fptr , ”%s %s %d %d”, n, d, &a,
&b);
Where, variable are initialized as:
char n[10], d[10];
int a,b;
EOF: End of file
Program example
1) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students. Write a C program to read and display all records.
#include
int main()
{
char
n[10];
int
c, e, ne, m;
FILE
*fptr;
fptr
= fopen("student.txt","r");
printf("Name\tPercentage\n");
while(fscanf(fptr,"%s %d %d %d
%d",n,&c,&e,&ne,&m) != EOF)
{
printf("%s %d %d %d %d", n, c, e, ne,
m);
}
fclose(fptr);
return 0;
}
2) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students. Write a C program to read and display only records whose name is Ram.
#include
int main()
{
char
n[10];
int
c, e, ne, m;
FILE
*fptr;
fptr
= fopen("student.txt","r");
while(fscanf(fptr,"%s %d %d %d
%d",n,&c,&e,&ne,&m) != EOF)
{
strlwr(n);
if (strcmp(n,”ram”) == 0)
{
printf("%s %d %d %d %d", n, c, e, ne,
m);
}
}
fclose(fptr);
return 0;
}
3) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students. Write a C program to read and display only records who pass in all subjects.
#include
int main()
{
char
n[10];
int
c, e, ne, m;
FILE
*fptr;
fptr =
fopen("student.txt","r");
while(fscanf(fptr,"%s %d %d %d
%d",n,&c,&e,&ne,&m) != EOF)
{
if (e>=40 && ne>=40 && m>=40)
{
printf("%s %d %d %d %d", n, c, e, ne,
m);
}
}
fclose(fptr);
return
0;
}
4) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students. Write a C program to read and display only records who fail in any one subject.
#include
int main()
{
char
n[10];
int
c, e, ne, m;
FILE
*fptr;
fptr
= fopen("student.txt","r");
while(fscanf(fptr, "%s %d %d %d %d", n, &c, &e,
&ne, &m) != EOF)
{
if (e<40 || ne<40 || m<40)
{
printf("%s %d %d %d %d", n, c, e, ne,
m);
}
}
fclose(fptr);
return 0;
}
5) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students. Write a C program to read and display only name and percentage of all students
#include
int main()
{
char
n[10];
int
c, e, ne, m;
float p;
FILE
*fptr;
fptr
= fopen("student.txt","r");
while(fscanf(fptr, "%s %d %d %d %d", n, &c, &e,
&ne, &m) != EOF)
{
p = (e+ne+m)/3;
printf("%s %f", n, p);
}
fclose(fptr);
return 0;
}
6) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students. Write a C program to read and display only records of all students who secure distinction.
#include
int main()
{
char
n[10];
int
c, e, ne, m;
float p;
FILE
*fptr;
fptr
= fopen("student.txt","r");
while(fscanf(fptr, "%s %d %d %d %d", n, &c, &e,
&ne, &m) != EOF)
{
p
= (e+ne+m)/3;
if (p>=80)
{
printf("%s %d %d %d %d", n, c, e, ne, m);
}
}
fclose(fptr);
return 0;
}
COMMENTS