0% found this document useful (0 votes)
13 views40 pages

Unit 3 Que & Ans

The document provides an overview of functions in C programming, explaining their definition, usage, and types including library and user-defined functions. It details categories of user-defined functions based on arguments and return values, as well as parameter passing mechanisms like call by value and call by reference. Additionally, it discusses recursion versus iteration, provides examples, and explains how to pass individual elements and whole arrays to functions.
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)
13 views40 pages

Unit 3 Que & Ans

The document provides an overview of functions in C programming, explaining their definition, usage, and types including library and user-defined functions. It details categories of user-defined functions based on arguments and return values, as well as parameter passing mechanisms like call by value and call by reference. Additionally, it discusses recursion versus iteration, provides examples, and explains how to pass individual elements and whole arrays to functions.
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/ 40

Unit 3

1. A. What is a function? Why we use functions in C language? Give an example.

Ans: Function in C:
( CO - 2, BT – 2 )
A function is a block of code that performs a specific task. It has a name and it is reusable
.It can be executed from as many different parts in a program as required, it can also return a
value to calling program.
All executable code resides within a function. It takes input, does something with it, then give
the answer. A C program consists of one or more functions.
A computer program cannot handle all the tasks by itself. It requests other program like entities
called functions in C. We pass information to the function called arguments which specified
when the function is called. A function either can return a value or returns nothing. Function is
a subprogram that helps reduce coding.
Simple Example of Function in C
#include<stdio.h>
#include <conio.h>
int adition (int, int); //Function Declaration
int addition (int a, int b) //Function Definition
{
int r;
r=a + b;
return (r);
}
int main()
{
int z;
z= addition(10,3); //Function Call

printf ("The Result is %d", z); return 0;


}
Output: The Result is 13
Why use function:
Basically there are two reasons because of which we use functions
1.Writing functions avoids rewriting the same code over and over. For example - if you have a
section of code in a program which calculates the area of triangle. Again you want to calculate
the area of different triangle then you would not want to write the same code again and again
for triangle then you would prefer to jump a "section of code" which calculate the area of the
triangle and then jump back to the place where you left off. That section of code is
called
„function'.
2. Using function it becomes easier to write a program and keep track of what they are doing.
If the operation of a program can be divided into separate activities, and each activity placed in
a different function, then each could be written and checked more or less independently.
Separating the code into modular functions also makes the program easier to design and
understand.

1. B. Distinguish between Library functions and User defined functions in C and Explain with
examples. (CO - 2, BT – 3 )
Ans: Types of Function in C:
(i). Library Functions in C
C provides library functions for performing some operations. These functions are present in the c
library and they are predefined.

For example sqrt() is a mathematical library function which is used for finding the square root of
any number .The function scanf and printf() are input and output library function similarly we
have strcmp() and strlen() for string manipulations. To use a library function we have to include
some header file using the preprocessor directive #include.

For example to use input and output function like printf() and scanf() we have to include stdio.h,
for math library function we have to include math.h for string library string.h should be included.

(ii). User Defined Functions in C


A user can create their own functions for performing any specific task of program are called user
defined functions. To create and use these function we have to know these 3 elements.
1. Function Declaration
2. Function Definition
3. Function Call

1. Function declaration
The program or a function that calls a function is referred to as the calling program or calling
function. The calling program should declare any function that is to be used later in the
program this is known as the function declaration or function prototype.
2. Function Definition
The function definition consists of the whole description and code of a function. It tells that
what the function is doing and what are the input outputs for that. A function is called by
simply writing the name of the function followed by the argument list inside the parenthesis.
Function definitions have two parts:
Function Header
The first line of code is called Function Header.
int sum( int x, int y)
It has three parts
(i). The name of the function i.e. sum
(ii). The parameters of the function enclosed in
parenthesis (iii). Return value type i.e. int
Function Body
Whatever is written with in { } is the body of the function.
3. Function Call
In order to use the function we need to invoke it at a required place in the program. This is
known as the function call.

2. A. Explain the various categories of user defined functions in C with examples?


Ans: (CO - 2, BT – 2)
A function depending on whether arguments are present or not and whether a value is returned or
not may belong to any one of the following categories:
o Functions with no arguments and no return values.

o Functions with arguments and no return values.

o Functions with arguments and return values.

o Functions with no arguments and return values.

(i) Functions with no arguments and no return values:-

When a function has no arguments, it does not return any data from calling function. When a
function does not return a value, the calling function does not receive any data from the called
function. That is there is no data transfer between the calling function and the called function.

Example
#include <stdio.h>
#include <conio.h>
void printmsg()
{
printf ("Hello ! I Am A Function .");
}

int main()
{
printmsg();
return 0;
}

Output : Hello ! I Am A Function .

(ii) Functions with arguments and no return values:-

When a function has arguments data is transferred from calling function to called function. The
called function receives data from calling function and does not send back any values to calling
function. Because it doesn‟t have return value.

Example

#include<stdio.h>
#include <conio.h>
void add(int,int);

void main()
{
int a, b;

printf(“enter value”); scanf(“%d

%d”,&a,&b);

add(a,b);
}

void add (intx, inty)


{
int z ;
z=x+y;

printf ("The sum =%d",z);


}

output : enter values 2 3

The sum = 5

(iii) Functions with arguments and return values:-

In this data is transferred between calling and called function. That means called function
receives data from calling function and called function also sends the return value to the calling
function.

Example
#include<stdio.h>
#include <conio.h>
int add(int, int);
main()
{
int a,b,c;

printf(“enter value”);

scanf(“%d%d”,&a,&b);

c=add(a,b);
printf ("The sum =%d",c);
}
int add (int x, int y)
{
int z;
z=x+y;

return z;
}
output : enter values 2 3

The sum = 5

(iv) Function with no arguments and return type:-

When function has no arguments data cannot be transferred to called function. But the called
function can send some return value to the calling function.

Example

#include<stdio.h>
#include <conio.h>
int add( );
main()
{
int c;

c=add();
printf ("The sum =%d",c);
}
int add ()
{
int x,y,z;

printf(“enter value”);

scanf(“%d%d”,&a,&b);

z=x+y;

return z;
}
Output: enter values 2 3

The sum = 5

3. A. Explain the Parameter Passing Mechanisms in C-Language with examples.

Ans: ( CO - 2, BT – 2 )

Most programming languages have 2 strategies to pass parameters. They are

(i) call by value

(ii) call by reference

(i) Pass by value (or) call by value :-

In this method calling function sends a copy of actual values to called function, but the changes
in called function does not reflect the original values of calling function.

Example program:

#include<stdio.h>

void fun1(int, int);

void main( )

int a=10, b=15;

fun1(a,b);

printf(“a=%d,b=%d”, a,b);

void fun1(int x, int y)


{ x=x+1

0; y=

y+20;

}
Output: a=10 b=15

The result clearly shown that the called function does not reflect the original values in main
function.

(ii) Pass by reference (or) call by address :-

In this method calling function sends address of actual values as a parameter to called function,
called function performs its task and sends the result back to calling function. Thus, the changes
in called function reflect the original values of calling function. To return multiple values from
called to calling function we use pointer variables.

Calling function needs to pass „&‟ operator along with actual arguments and called function
need to use „*‟ operator along with formal arguments. Changing data through an address
variable is known as indirect access and „*‟ is represented as indirection operator.

Example program:

#include<stdio.h>

void fun1(int,int);

void main( )

int a=10, b=15;

fun1(&a,&b); printf(“a=

%d,b=%d”, a,b);

}
void fun1(int *x, int *y)

*x = *x + 10;
*y = *y + 20;

Output: a=20 b=35

The result clearly shown that the called function reflect the original values in main function. So
that it changes original values.

3.B Differentiate actual parameters and formal parameters.


Ans: (CO - 2, BT – 4 )

Actual parameters Formal parameters


The list of variables in calling function is The list of variables in called function is known as
known as actual parameters. formal parameters.
Actual parameters are variables that Formal parameters are variables that are declared in
are
the header of the function definition.
declared in function call.
Actual parameters are passed without Formal parameters have type preceeding with them.
using type
main( ) return_type function_name(formal
{ parameters)
..… {
..…
function_name (actual parameters);
function body;
…..
…..
}
}
Formal and actual parameters must match exactly in type, order, and number.

Formal and actual parameters need not match for their names.
4. A. What is recursive function? Differentiate between recursion and iteration/ non-
recursion
Ans: (CO - 2, BT – 1 )
Recursion
Recursion is a process by which a function calls itself repeatedly, until some specified condition
has been satisfied.

When a function calls itself, a new set of local variables and parameters are allocated storage on
the stack, and the function code is executed from the top with these new variables. A recursive
call does not make a new copy of the function. Only the values being operated upon are new. As
each recursive call returns, the old local variables and parameters are removed from the stack,
and execution resumes immediately after the recursive call inside the function.

The main advantage of recursive functions is that we can use them to create clearer and simpler
versions of several programs.

Syntax:-

A function is recursive if it can call itself; either directly:

void f( )
{
f( );
}

(or) indirectly:

void f( )
{
g( );
}

void g( )
{
f( );
}
Recursion rule 1: Every recursive method must have a base case -- a condition under which no
recursive call is made -- to prevent infinite recursion.

Recursion rule 2: Every recursive method must make progress toward the base case to prevent
infinite recursion
Recursion:- Recursion is a process by which a function calls itself repeatedly, until some
specified condition has been satisfied.

When a function calls itself, a new set of local variables and parameters are allocated storage on
the stack, and the function code is executed from the top with these new variables. A recursive
call does not make a new copy of the function. Only the values being operated upon are new. As
each recursive call returns, the old local variables and parameters are removed from the stack,
and execution resumes immediately after the recursive call inside the function.

Ex:-

void main( )
{
int n=5;
fact( n);
}
int fact( )
{
if(n==0 || n==1)
return 1;
else
return(n*fact(n-1));
}
Non-Recursion:-

Using looping statements we can handle repeated statements in „C‟. The example of non
recursion is given below.

Syntax:-

void main( )
{
int n=5;
res = fact(n);
printf(“%d”,res);
}
int fact( )
{
for(i=1;i<=n;i++)
{
f=f+1;
}
return f;
}
Differences:

- Recursive version of a program is slower than iterative version of a program due to overhead
of maintaining stack.
- Recursive version of a program uses more memory (for the stack) than iterative version of a
program.
- Sometimes, recursive version of a program is simpler to understand than iterative version of a
program.

4. B Write a program to find factorial of a number using recursion.


Ans: (CO - 2, BT – 3)
#include<stdio.h>
int fact(int);
main()
{
int n,f;
printf(“\n Enter any
number:”); scanf(“%d”,&n);
f=fact(n);
printf(“\n Factorial of %d is %d”,n,f);
}
int fact(int n)
{
int f;
if(n==0||n==1) //base case
f=1;
else
f=n*fact(n-1); //recursive case
return f;
}

Output:- Enter any number: 5

Factorial of 5 is 120
5. A. How to Pass Array Individual Elements to Functions? Explain with example program.
Ans: (CO - 2, BT – 2 )

Arrays with functions:

To process arrays in a large program, we need to pass them to functions. We can pass arrays in
two ways:

1) pass individual elements

2) pass the whole array.

Passing Individual Elements:

One-dimensional Arrays:

We can pass individual elements by either passing their data values or by passing their addresses.
We pass data values i.e; individual array elements just like we pass any data value .As long as the
array element type matches the function parameter type, it can be passed. The called function
cannot tell whether the value it receives comes from an array, a variable or an expression.

Program using call by value

void func1( int a);

void main()

int a[5]={ 1,2,3,4,5};

func1(a[3]);

void func1( int x)

printf(“%d”,x+100);

}
Two-dimensional Arrays:

The individual elements of a 2-D array can be passed in the same way as the 1-D array. We can
pass 2-D array elements either by value or by address.

Ex: Program using call by value

void fun1(int a)

main()

int a[2][2]={1,2,3,4};

fun1(a[0][1]);

void fun1(int x)

printf(“%d”,x+10);

5.b How can we pass the Whole Array to Functions? Explain with example
program. ( CO - 2, BT – 2 )
Ans: Passing an entire array to a function:

One-dimensional array:
To pass the whole array we simply use the array name as the actual parameter. In the called
function, we declare that the corresponding formal parameter is an array. We do not need to
specify the number of elements.

Program :

void fun1(int a[])

void main()

fun1(a);

void fun1( int x[])

int i, sum=0;

for(i=0;i<5;i++)

sum=sum+a[i];

printf(“%d”,sum);

Two-dimensional array:

When we pass a 2-D array to a function, we use the array name as the actual parameter just as we
did with 1-D arrays. The formal parameter in the called function header, however must indicate
that the array has two dimensions.

Rules:

 The function must be called by passing only the array name.


 In the function definition, the formal parameter is a 2-D array with the size of the second
dimension specified.
Program:

void fun1(int a[][2])

void main()

{
int a[2][2]={1,2,3,4};
fun1(a);

void fun1(int x[][2])

int i,j;

for(i=0;i<2;i++)

for(j=0;j<2;j++)

printf(“%d”,x[i][j]);

6. Explain about different types of storage classes in C‘? ( CO - 2, BT – 2 )


Ans: Storage classes in ‗C‘

Variables in C differ in behavior. The behavior depends on the storage class a variable may
assume. From C compiler‟s point of view, a variable name identifies some physical location
within the computer where the string of bits representing the variable‟s value is stored. There are
four storage classes in C:

(a) Automatic storage class


(b) Register storage class
(c) Static storage class
(d) External storage class

(a) Automatic Storage Class:-


The features of a variable defined to have an automatic storage class are as under:

Keyword Auto
Storage Memory.
Default initial value An unpredictable value, which is often called a garbage value.
Scope Local to the block in which the variable is defined.
Life Till the control remains within the block in which the

variable is defined

Following program shows how an automatic storage class variable is declared, and the fact that
if the variable is not initialized it contains a garbage value.
main( )
{
auto int i, j ;
printf ( "\n%d %d", i, j ) ;
}

When you run this program you may get different values, since garbage values are unpredictable.
So always make it a point that you initialize the automatic variables properly, otherwise you are
likely to get unexpected results. Scope and life of an automatic variable is illustrated in the
following program.
main( )

{
auto int i = 1 ;

{
auto int i = 2 ;

{
auto int i = 3 ;

printf ( "\n%d ", i )

}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}

Static Storage Class:-


The features of a variable defined to have a static storage class are as under:
Keyword Static

Storage Memory.

Default initial value Zero.

Scope Local to the block in which the variable is defined.

Life Value of the variable persists between different


function calls
The following program demonstrates the details of static storage class:

main()
{

Increment();
Increment();
Increment();
}

Increment()
{
static int i=1;
printf(“%d”,i);
i++;
}

Output:
1
2
3

Extern Storage Class:-

The features of a variable whose storage class has been defined as external are as follows:

Keyword Extern
Storage Memory
default initial value Zero
Scope Global
Life As long as the program execution does not come
to end

External variables differ from those we have already discussed in that their scope is global, not
local. External variables are declared outside all functions, yet are available to all functions that
care to use them. Here is an example to illustrate this fact.
Ex:
#include<stdio.h>
extern int i;
void main()

{
printf(“i=%d”,i);

Register Storage Class:-


The features of a variable defined to be of register storage class are as under:
Keyword Register

Storage CPU Registers

default initial value An unpredictable value, which is often called a garbage value.

Scope Local to the block in which the variable is defined.

Life Till the control remains within the block in which the variable
is defined.

A value stored in a CPU register can always be accessed faster than the one that is stored in
memory. Therefore, if a variable is used at many places in a program it is better to declare its
storage class as register. A good example of frequently used variables is loop counters. We can
name their storage class as register.
main( )

register int i ;

for ( i = 1 ; i <= 10 ; i++ )

printf ( "\n%d", i ) ;

7. A. Write in detail about pointers to functions? Explain with example program.


(CO - 2, BT – 2 )
Ans: Pointers to functions:-

A function, like a variable has a type and address location in the memory. It is therefore possible
to declare a pointer to a function, which can then be used as an argument in another function.

A pointer to a function can be declared as follows.


type (*fptr)();

This tells the complier that fptr is a pointer to a function which returns type value the parentheses
around *fptr is necessary.

Because type *gptr(); would declare gptr as a function returning a pointer to type.

We can make a function pointer to point to a specific function by simply assigning the name
of the function to the pointer.

Eg: double mul(int,int);

double (*p1)();

p1=mul();

It declares p1 as a pointer to a function and mul as a function and then make p1 to point to the
function mul.

To call the function mul we now use the pointer p1 with the list of parameters.

i,e (*p1)(x,y); //function call equivalent to mul(x,y);

Program:

double mul(int ,int);

void main()

int x,y;

double (*p1)();

double res;

p1=mul;

printf("\n enter two numbers:");

scanf("%d %d",&x,&y);
res=(*p1)(x,y);

printf("\n The Product of X=%d and Y=%d is res=%lf",x,y,res);

}
double mul(int a,int b)

double val;

val=a*b;

return(val);
}

Output:
Enter 2 numbers: 22 7
Res is 154.00000

7.b. Explain Passing structure elements to function (CO - 2, BT – 2 )

We can pass each element of the structure through function but passing individual element is
difficult when number of structure element increases. To overcome this, we use to pass the
whole structure through function instead of passing individual element.

#include<stdio.h>
#include<string.h>
void main()
{

struct student

char name[30];
char branch[25];
int roll;
}struct student s;

printf(“\n enter name=”);


gets(s.name);
printf("\nEnter roll:");
scanf("%d",&s.roll);
printf("\nEnter branch:");
gets(s.branch);
display(name,roll,branch);
}

display(char name, int roll, char branch)


{

printf(“\n name=%s,\n roll=%d, \n branch=%s”, s.name, s.roll. s.branch);

Passing entire structure to function


#include<stdio.h>
#include<string.h>
struct student

char name[30];
int age,roll;
};

void main()
{

struct student s1={”sona”,16,101 }; struct student


s2={”rupa”,17,102 };
display(s1);
display(s2);
}

display(struct student s)

printf(“\n name=%s, \n age=%d ,\n roll=%d”, s.name, s.age, s.roll);

Output: name=sona roll=16

8. A. Differentiate between static and dynamic memory allocation.


Explain about static and dynamic memory allocation
techniques.
(CO - 2, BT – 4 )
Ans: Memory can be reserved for the variables either during the compilation time or during
execution time. Memory can be allocated for variables using two different techniques:

1. Static allocation
2. Dynamic allocation

1) Static allocation: If the memory is allocated during compilation time itself, the allocated
memory space cannot be expanded to accommodate more data or cannot be reduced to
accommodate less data.

In this technique once the size of the memory is allocated it is fixed. It cannot be altered
even during execution time .This method of allocating memory during compilation time is called
static memory allocation.

2) Dynamic allocation: Dynamic memory allocation is the process of allocating memory during
execution time. This allocation technique uses predefined functions to allocate and release
memory for data during execution time.

Static memory allocation Dynamic memory allocation

It is the process of allocating memory at It is the process of allocating memory


compile time. during execution of program.

Fixed number of bytes will be allocated. Memory is allocated as and when it is


needed.

The memory is allocated in memory stack. The memory is allocated from free memory
pool (heap).

Execution is faster Execution slow

Memory is allocated either in stack area or Memory is allocated only in heap area
data area

Ex: Arrays Ex: Dynamic arrays, Linked List, Trees

8. B. Explain about Dynamic memory management functions with an example.


(CO - 2, BT – 2 )

Ans: The function malloc( ) allocates a block of size bytes from the free memory pool (heap).

It allows a program to allocate an exact amount of memory explicitly, as and when needed.

Ptr= (cat_type*)malloc(byte_size);
Ptr is a pointer of type cast_type.The malloc returns a pointer to an area of memory with size
byte_size.The parameter passed to malloc() is of the type byte_size. This type is declared in the
header file alloc.h. byte_size is equivalent to the unsigned int data type. Thus, in compilers
where an int is 16 bits in size, malloc() can allocate a maximum of 64KB at a time, since the
maximum value of an unsigned int is 65535.

Return value:

On success, i.e., if free memory is available, malloc() returns a pointer to the newly allocated
memory. Usually, it is generic pointer. Hence, it should be typecast to appropriate data type
before using it to access the memory allocate.

On failure, i.e., if enough free memory does not exist for block, malloc() returns NULL. The
constant NULL is defined in stdio.h to have a value zero. Hence, it is safe to check the return
value.
Ex: 1) malloc(30); allocates 30 bytes of memory and returns the address of byte0.

2) malloc(sizeof(float)); allocates 4 bytes of memory and returns the address of byte0.

2) calloc( ) — allocates multiple blocks of memory

The function calloc( ) has the following prototype:

Ptr= (cast_type*)calloc(n,ele_size);

calloc( ) provides access to the C memory heap, which is available for dynamic allocation
of variable-sized blocks of memory.

Unlike malloc(), the function calloc( ) accepts two arguments: n and ele_size. The parameter n
specifies the number of items to allocate and ele_size specifies the size of each item.

Return value:

On success, i.e., if free memory is available, calloc( ) returns a pointer to the newly allocated
memory. Usually, it is generic pointer. Hence, it should be typecast to appropriate data type
before using it to access the memory allocated.

On failure, i.e., if enough free memory does not exist for block, calloc( ) returns NULL. The
constant NULL is defined in stdio.h to have a value zero. Hence, it is safe to verify the return
value before using it.
Ex: calloc(3,5); allocates 15 bytes of memory and returns the address of byte0.

malloc(6,sizeof(float)); allocates 24 bytes of memory and returns the address of byte0.

i) realloc( ) — grows or shrinks allocated memory

The function realloc( ) has the following prototype:

Ptr=realloc(ptr,newsize);
The function realloc() allocates new memory space of size newsize to the pointer variable ptr
and returns a pointer to the first byte of the new memoty block.

ptr is the pointer to the memory block that is previously obtained by calling malloc(), calloc() or
realloc(). If ptr is NULL pointer, realloc() works just like malloc().

Return value:

On success, this function returns the address of the reallocated block, which might be different from the
address of the original block.

On failure, i.e., if the block can‟t be reallocated or if the size passed is 0, the function returns NULL.

The function realloc() is more useful when the maximum size of allocated block cann‟t be
decided in advance.

Ex: int *a;

a=(int *) malloc(30); //first 30 bytes of memory is allocated.

a=(int *) realloc(a,15); //later the allocated memory is shrink to 15 bytes.

ii) free( ) — de-allocates memory

The function free( ) has the following prototype:

Free(ptr);

The function free( ) de-allocates a memory block pointed by ptr.

ptr is the pointer that is points to allocated memory by malloc( ), calloc( ) or realloc(). Passing
an uninitialized pointer, or a pointer to a variable not allocated by malloc( ), calloc() or realloc()
could be dangerous and disastrous.

Ex: int *a;

a=(int *) malloc(30); //first 30 bytes of memory is allocated.

9. A. What are Command Line Arguments ? Write an example program for command
line arguments ? (CO - 2, BT – 2 )

It is possible to pass some values from the command line to your C programs when
they are executed. These values are called command line arguments and many times they
are important for your program especially when you want to control your program from
outside instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a pointer array which
points to each argument passed to the program.

#include <stdio.h>

int main( int argc, char *argv[] )


{

if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}

9. B Explain about Preprocessor Directives in C ? ( CO - 2, BT – 2)

The C preprocessor is a macro processor that is used automatically by the C compiler to transform
programmer defined programs before actual compilation takes place. It is called a macro processor
because it allows the user to define macros, which are short abbreviations for longer constructs.
This functionality allows for some very useful and practical tools to design our programs.
 To include header files(Header files are files with pre defined function definitions, user
defined data types, declarations that can be included.)
 To include macro expansions. We can take random fragments of C code and abbreviate them
into smaller definitions namely macros, and once they are defined and included via header files
or directly onto the program itself it(the user defined definition) can be used everywhere in the
program. In other words it works like a blank tile in the game scrabble, where if one player
possesses a blank tile and uses it to state a particular letter for a given word he chose to play
then that blank piece is used as that letter throughout the game. It is pretty similar to that rule.
 Special pre processing directives can be used to, include or exclude parts of the program
according to various condition.
# include preprocessor directive:
Only defined at the top of the program definition and only white space and comments may appear
before preprocessor directive line.This directive includes a copy of the specified file or library. And is
written like so-
#include<filename>
Or #include “file name”
If included inside <> then the compiler looks for the file in an implementation defined manner (or
system directory paths).
If included inside a quote “ ” statement then it searches for the file in the same directory as the program
being written.
So if we include a file named file1 while writing a program name code.c which is being stored in a
folder called test. Then inclusion like so -- #include “file1”
Will tell the compiler to look for the file inside the test folder, It looks at neighboring folders or
subfolders too but it starts its search in the test folder.(This sub search option is compiler dependent).

#define Preprocessor Directive ( Symbolic constant )


Used to create symbolic constants and macros, meaning useful for renaming long named data types and
certain constants or values which is being used throughout the program definition.
Symbolic constant definition-
Written as –
#define identifier replacement-text
When this line appears in a file, all subsequent occurrences of identifier that do not appear in string
literals will be replaced by the replacement text automatically before program compilation takes
place.
For example:
#define PI 3.14159
Replaces all subsequent occurrences of the symbolic constant PI with numeric constant 3.14159.
Symbolic constants enable the programmer to create a name for a constant and use that name
throughout program execution. If this needs to be modified ,it has to be done in the #define directive
statement. After recompilation all definitions get modified accordingly.

#define Preprocessor Directive (Macro)


 Symbolic constants and macros can be discarded by using the #undef preprocessor
directive.
 Directive #undef “undefines” the symbolic constant or macro name.
 The scope of a symbolic constant or macro is from its definitions until it is undefined with
#undef or until the end of the file.
Example Code –

#include<stdio.h> -- Include external source code file


#include “file1” - Include a file which is in the same folder as the parent file #define
BUFFER_SIZE 250

Int maint(){
Char array[BUFFER_SIZE] = [0];
Int I = 9;

Printf(“%d”,i);
Printf(“%s”,array);

Return 0;
}//end main body

Conditional Compilation:

Conditional compilation enables the coder to control the execution of preprocessor directives and
the compilation of program code.
->Conditional preprocessor directives evaluate constant integer expressions.The ones that cannot
be evaluated in preprocessor directives are sizeof expressions and enumeration constants.
Every #if construct ends with #endif

Example –
#if !defined(MY_CONSTANT) #define
MY_CONSTANT 0
#endif

These directives determine if MY_CONSTANT is defined or not.The expression


defined(MY_CONSTANT) evaluates to 1 if MY_CONSTANT is not defined and is defined else it
evaluates to 0.

10 (a) Write the syntax for opening a file and closing a file? (CO 3 BT-1)
Ans) FILE:A file is an external collection of related data treated as a unit. The primary purpose of a file is to keep
a record of data. Files are stored in auxiliary or secondary storage devices .Buffer is a temporary storage area that
holds data while they are being transferred to or from memory.
Declare a file pointer variable.
FILE *file_pointer_name;
Eg: FILE *fp;
Streams
A stream can be associated with a physical device, such as a terminal, or with a file stored in auxiliary
memory.
Text and Binary Streams
C uses two types of streams: text and binary .A text stream consists of characters divided into lines with
each line terminated by a newline(\n).A binary stream consists of data values such as integer, real or
complex.
Creating a Stream
We create a stream when we declare it. The declaration uses the FILE type as shown in the following
example the FILE type is a structure that contains the information needed for reading and writing a file.
FILE *file_pointer_name;
Eg: FILE *fp;
In this example,*fp is a pointer to the stream.
Opening a File
When the file is opened, the stream and the file are associated with each other and the FILE type is filled
with the pertinent file information. The open function returns the address of the file type, which is stored
in the stream pointer variable,*fp .
Using the Stream Name
After we create the stream, wecanusethestreampointerinallfunctionsthatneedtoaccessthecorresponding file
for input and output.
Closing the Stream
When the File processing is complete, we close the file. Closing the association between the stream name
and file name. After the close, the stream is no longer available and any attempt to use it results in an
error.

10. b) Explain The file modes with examples? (CO 3 BT-2)


Ans) The File Modes
Your program must open a file before it can access it. This is done using the fopen function, which returns
the required file pointer. If the file cannot be opened for any reason then the value NULL will be returned.
You will usually use fopen as follows
if ((output_file =fopen("output_file","w"))==NULL)
fprintf (stderr,"Cannot open %s\n", "output_file");
fopen takes two arguments ,both are strings, the first is the name of the file to be opened, the second is an
access character, which is usually one of r, a or w etc. Files may be opened in a number of modes, as
shown in the following table.

File Modes
R Open a text file for reading.
W Create a text file for writing .If the file exists, it is overwritten.
A Open a text file in append mode. Text is added to the end of the file.
Rb Open a binary file for reading.
Wb Create a binary file for writing. If the file exists, it is overwritten.
Ab Any file in append mode. Data is added to the end of the file.
r+ Open a text file for reading and writing.
w+ Create a text file for reading and writing. If the file exists, it is overwritten.
a+ Open a text file for reading and writing at the end.
r+b O
+ pen binary file for reading and writing.
w+b C
+ reate a binary file for reading and writing .If the file exists, it is overwritten.

a+b O
+ pen a text file for reading and writing at the end.

The update modes are used with fseek,fset pos and rewind functions. The fopen function return s a file
pointer, or NULL if an error occurs.
The following example opens a file, tarun.tx tin read-only mode .It is good programming practice to test
the file exists.

if((in=fopen("tarun.txt","r"))== NULL)
{
puts("Unable to open the file");
return0;
}

11a) Explain about files and with it types of file processing? (CO 3 BT-2)
Ans) Files: As we know that Computers are used for storing the information for a Permanent Time or the
Files are used for storing the Data of the users for a Long time Period. And the files can contains any type
of information means they can Store the text, any Images or Pictures or any data in any Format. So that
there must be Some Mechanism those are used for Storing the information, Accessing the information and
also Performing Some Operations on the file There are Many files which have their Owen Type and own
names. When we Store a File in the System, then we must have to specify the Name and the Type of File.
The Name of file will be any valid Name and Type means the application with the file has linked.

So that we can say that Every File also has Some Type Means Every File belongs to Special Type of
Application software‘s. When we Provides a Name to a File then we also specify the Extension of the File
because a System will retrieve the Contents of the File into that Application Software. For Example if
there is a File Which Contains Some Paintings then this will Opened into the Paint Software.
1) Ordinary Files or Simple File: Ordinary File may belong to any type of Application for example
notepad, paint, C Program, Songs etc. So all the Files those are created by a user are Ordinary Files.
Ordinary Files are used for Storing the information about the user Programs. With the help of Ordinary
Files we can store the information which contains text, database, any image or any other type of
information.
2) Directory files: The Files those are Stored into the a Particular Directory or Folder. Then these are
the Directory Files. Because they belongs to a Directory and they are Stored into a Directory or Folder.
For Example a Folder Name Songs which Contains Many Songs So that all the Files of Songs are known
as Directory Files.
3) Special Files: The Special Files are those which are not created by the user. Or The Files those are
necessary to run a System. The Files those are created by the System. Means all the Files of an Operating
System or Window, are refers to Special Files. There are Many Types of Special Files, System Files, or
windows Files, Input output Files. All the System Files are Stored into the System by using. sys Extension.
4) FIFO Files: The First in First Out Files are used by the System for Executing the Processes into
Some Order. Means To Say the Files those are Come first, will be Executed First and the System
Maintains a Order or Sequence Order. When a user Request for a Service from the System, then the
Requests of the users are Arranged into Some Files and all the Requests of the System will be performed
by the System by using Some Sequence Order in which they are Entered or we can say that all the files or
Requests those are Received from the users will be Executed by using Some Order which is also called as
First in First Out or FIFO order
Types of File Operations
Files are not made for just reading the Contents, we can also Perform Some other operations on the Files
those are Explained below As :
1) Read Operation: Meant To Read the information which is Stored into the Files.
2) Write Operation: For inserting some new Contents into a File.
3) Rename or Change the Name of File.
4) Copy the File from one Location to another.
5) Sorting or Arrange the Contents of File.
6) Move or Cut the File from One Place to Another.
7) Delete a File
8) Execute Means to Run Means File Display Output.

11. b) Explain the following file handling functions: (CO 3 BT-2)


a. fseek() b. ftell() c. rewind() d. ferror()
Ans) a.fseek():
This function is used for seeking the pointer position in the file at the specified byte.
Syntax: fseek(file pointer, displacement, pointer position);
File pointer-----It is the pointer which points to the file.
Displacement-----It is positive or negative .This is the number of bytes which are skipped backward (if
negative) or forward (if positive) from the current position. This is attached with because this is a long
integer.
This sets the pointer position in the file.
Value Pointer position
0 Beginning
1 Current position
2 End of file

b. ftell():

This function returns the value of the current pointer position in the file. The value is count from the
beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.

c. rewind():
This function is used to move the file pointer to the beginning of the given file.
Syntax: rewind (fptr);
where fptr is a file pointer.

d. ferror():
The macro ferror() is used for detecting whether an error occur in the file on file pointer or not .It returns
the value nonzero if an error ,otherwise it returns zero.
Syntax: ferror(fptr);
Where fptr is a file pointer.

12. a) Write a C program to read name and marks of n number of students from user and store
them in a file. (CO 3 BT-4)
Ans)
#include<stdio.h>
#include<conio.h>
Int main (){
Char name [50];
Int marks,i,n;
Printf("Enter number of students:");
scanf ("%d" ,&n);
FILE*fptr;
fptr=(fopen("C:\\student.txt","w"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student %d\nEntername:",i+1);
scanf("%s" ,name);
printf("Enter marks:");
scanf("%d",& marks);
fprintf(fptr,"\n Name:%s\n Marks=%d\n" ,name, marks);
}
fclose(fptr);
return0;
}

12.b)Explain about Sequential and Random Access File Handling in C? (CO 3 BT-2)
Ans) Sequential and Random Access File Handling in C
A file handling in C tutorial detailing the use of sequential and random access files in C, along with
examples of using the fseek, ftell and rewind functions.
In computer programming, the two main types of file handling are:
• Sequential;
• Random access.
Sequential files are generally used in cases where the program processes the data in a sequential fashion –
i.e. counting words in a text file – although in some cases, random access can be affected by moving
backwards and forwards over a sequential file.
True random access file handling, however, only accesses the file at the point at which the data should be
read or written, rather than having to process it sequentially. A hybrid approach is also possible whereby a
part of the file is used for sequential access to locate something in the random access portion of the file, in
much the same way that a File Allocation Table (FAT) works.
The three main functions that this article will deal with are:

• rewind() – return the file pointer to the beginning;


• fseek() – position the file pointer;
• ftell() – return the current offset of the file pointer.
Each of these functions operates on the C file pointer, which is just the offset from the start of the file, and
can be positioned at will. All read/write operations take place at the current position of the file pointer.
The rewind() Function
The rewind() function can be used in sequential or random access C file programming, and simply tells the
file system to position the file pointer at the start of the file. Any error flags will also be cleared, and no
value is returned.
While useful, the companion function, fseek(), can also be used to reposition the file pointer at will,
including the same behavior as rewind().
Using fseek() and ftell() to Process Files
The fseek() function is most useful in random access files where either the record (or block) size is known,
or there is an allocation system that denotes the start and end positions of records in an index portion of the
file. The fseek() function takes three parameters:
• FILE * f – the file pointer;
• long offset – the position offset;
• int origin – the point from which the offset is applied. The origin parameter can be one of three
values:
• SEEK_SET – from the start;
• SEEK_CUR – from the current position;
• SEEK_END – from the end of the file. So, the equivalent of rewind() would be:
fseek( f, 0, SEEK_SET);
By a similar token, if the programmer wanted to append a record to the end of the file, the pointer could be
repositioned thus:
fseek( f, 0, SEEK_END);
Since fseek() returns an error code (0 for no error) the stdio library also provides a function that can be
called to find out the current offset within the file:
long offset = ftell( FILE * f )
This enables the programmer to create a simple file marker (before updating a record for example), by
storing the file position in a variable, and then supplying it to a call to fseek: long file_marker = ftell(f);
// … file processing functions
fseek( f, file_marker, SEEK_SET);
Of course, if the programmer knows the size of each record or block, arithmetic can be used. For example,
to rewind to the start of the current record, a function call such as the following would suffice:
fseek( f, 0 – record_size, SEEK_CURR);
With these three functions, the C programmer can manipulate both sequential and random access files, but
should always remember that positioning the file pointer is absolute. In other words, if fseek is used to
position the pointer in a read/write file, then writing will overwrite existing data, permanently.

13 a). Write a C program to copy the contents from one file to another file? (CO 3 BT-4)
Ans)#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr1, *fptr2;
Char ch, fname1[20], fname2[20];
printf("\n\n Copy a file in another name :\n");
printf(" Input the source file name : ");
scanf("%s",fname1);
fptr1=fopen(fname1, "r");
if(fptr1==NULL)
{
printf(" File does not found or error in opening.!!");
exit(1);
}
printf(" Input the new file name : ");
scanf("%s",fname2);
fptr2=fopen(fname2, "w");
if(fptr2==NULL)
{
printf(" File does not found or error in opening.!!");
fclose(fptr1);
exit(2);
}
while(1)
{
ch=fgetc(fptr1);
if(ch==EOF)
{
break;
}
else
{
fputc(ch, fptr2);
}
}
printf(" The file %s copied successfully in the file %s. \n\n",fname1,fname2);
fclose(fptr1);
fclose(fptr2);
getchar();
}
Output:
Copy a file in another name:
Input the source file name: test.txt
Input the new file name: test1.txt
The file test.txt copied successfully in the file test1.txt.

13. b) Write a C program to count number of characters, words of a file. (CO 3 BT-4)
Ans)
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr;
Char ch;
int wrd=1,charctr=1;
char fname[20];
printf("\n\n Count the number of words and characters in a file :\n");
printf(" Input the filename to be opened : ");
scanf("%s",fname);
fptr=fopen(fname,"r");
if(fptr==NULL)
{
printf(" File does not exist or cannot be opened.");
}
else
{
ch=fgetc(fptr);
printf(" The content of the file %s are : ",fname);
while(ch!=EOF)
{
printf("%c", ch);
if(ch==' '||ch=='\n')
{
wrd++;
}
else
{
Char ctr++;
}
ch=fgetc(fptr);
}
printf("\n The number of words in the file %s are : %d\n",fname,wrd-2);
printf(" The number of characters in the file %s are : %d\n\n",fname,charctr-1);
}
fclose(fptr);
}

Output:
Count the number of words and characters in a file :
Input the filename to be opened : test.txt
The content of the file test.txt are :
test line 1
test line 2
test line 3
test line 4
The number of words in the file test.txt are : 12
The number of characters in the file test.txt are : 36
14 a) Write a program in C to append multiple lines at the end of a text file. (CO 3 BT-4)

#include <stdio.h>

int main ()

FILE * fptr;

Int i,n;

Char str[100];

Char fname[20];

char str1;

printf("\n\n Append multiple lines at the end of a text file :\n");

printf(" Input the file name to be opened : ");

scanf("%s", fname);

fptr = fopen(fname, "a");

printf(" Input the number of lines to be written : ");

scanf("%d", &n);

printf(" The lines are : \n");

for(i = 0; i< n+1;i++){

fgets(str, sizeof(str), stdin);

fputs(str, fptr);

fclose (fptr);

fptr = fopen (fname, "r");

printf("\n The content of the file %s is :\n" ,fname);


str1 = fgetc(fptr);

while (str1 != EOF){

printf ("%c", str1);

str1 = fgetc(fptr);

printf("\n\n");

fclose (fptr);

return 0;

Output:

Append multiple lines at the end of a text file :

Input the file name to be opened : test.txt

Input the number of lines to be written : 3

The lines are :

test line 5

test line 6

test line 7

The content of the file test.txt is :

test line 1

test line 2

test line 3

test line 4

test line 5

test line 6

test line 7
14 b) Write short notes on
i.fgets() ii. fputs() iii. fprintf () iv.fscanf() (CO 3 BT-3)
i) fgets (): The C library function char *fgets (char *str, int n, FILE *stream) reads a line from the
specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are
read, the newline character is read, or the end-of-file is reached, whichever comes first.
char*fgets(char*str, int n, FILE *stream)

 str − This is the pointer to an array of chars where the string read is stored.
 n − This is the maximum number of characters to be read (including the final null-character).
Usually, the length of the array passed as str is used.

ii) fputs():
The C library function int fputs (const char *str, FILE *stream) writes a string to the specified stream
up to but not including the null character.
Declaration: intfputs(const char*str, FILE *stream)
 str − This is an array containing the null-terminated sequence of characters to be written.
 stream − This is the pointer to a FILE object that identifies the stream where the string is to be
written.

iii. fprintf ()&fscanf():


The fprintf & fscanf functions:

The fprintf and fscanf functions are identical to printf and scanf functions except that they work on files.
The first argument of these functions is a file pointer which specifies the file to be used. The general form
of fprintf is
fprintf(fp,”control string”, list);
Where fp id a file pointer associated with a file that has been opened for writing. The control string is file
output specifications list may include variable, constant and string.
fprintf(f1,%s%d%f”,name,age,7.5);
Here name is an array variable of type char and age is an int variable The general format of fscanf is
fscanf(fp,”control string” ,list);
This statement would cause the reading of items in the control string.
Example:
#include <stdio.h>
Int main()
{
FILE*fp;
file = fopen("file.txt","w");
fprintf(fp,"%s", "This is just an example:)");
fclose(fp);
return0;
}

Variables
Variables defined in the stdio.h header include:
Name Notes
Stdin A pointer to a FILE which refers to the standard input stream, usually a keyboard.
A pointer to a FILE which refers to the standard output stream, usually a display
Stdout
terminal.
a pointer to a FILE which refers to the standard error stream, often a display terminal.
Stderr

15) Explain how to create a binary file and store structures in a binary with an example program?
(CO 3 BT-2)
Ans)
Program to store structure data into a binary file and display on the output screen

#include<stdio.h>
struct Employee
{
char name[40];
int age;
float bs;
};
int main( )
{
FILE *fp = fopen("employee.dat", "wb");
char ch = 'Y';
struct Employee e;

//reading employee detail from user and storing them in a binary file
while (ch == 'Y')
{
printf("Enter name, age and basic salary: ");
scanf("%s %d %f", e.name, &e.age, &e.bs);
fwrite(&e, sizeof(struct Employee), 1, fp);
printf("Add another record (Y/N) ");
fflush(stdin);
ch=getchar();
}
fclose(fp);

//To display the content of binary file


FILE *fp2 = fopen("employee.dat", "rb");

if(fp2 == NULL)
{
puts("Cannot open file");
return 0;
}
printf("\nFile content:\n");
while(fread(&e, sizeof(e), 1, fp2) == 1)
{
printf ("%s %d %.2f\n", e.name, e.age, e.bs);
}
fclose(fp2);

Output:
Enter name, age and basic salary: Ram 45 65000
Add another record (Y/N) Y
Enter name, age and basic salary: Shyam 28 48000
Add another record (Y/N) Y
Enter name, age and basic salary: Sita 30 52000
Add another record (Y/N) N

File content:
Ram 45 65000.00
Shyam 28 48000.00
Sita 30 52000.00

You might also like