0% found this document useful (0 votes)
88 views95 pages

PPS Mid 2 Complete Notes

The document discusses functions in C programming. It defines what a function is and describes the advantages of using functions. It also explains the different types of functions including built-in functions, user-defined functions, and the different categories of functions based on arguments and return types. The document concludes by covering parameter passing mechanisms including call by value and call by reference.
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)
88 views95 pages

PPS Mid 2 Complete Notes

The document discusses functions in C programming. It defines what a function is and describes the advantages of using functions. It also explains the different types of functions including built-in functions, user-defined functions, and the different categories of functions based on arguments and return types. The document concludes by covering parameter passing mechanisms including call by value and call by reference.
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/ 95

PPS Mid-II Complete Notes

Functions

Definition: 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 the calling program.
 All executable code resides within a function. It takes input, does something
with it, then gives the answer. 
 A C program consists of one or more functions.
 A computer program cannot handle all the tasks by itself. It requests other
programs like entities called functions in C.
 We pass information to the function using arguments. 
 A function either can return a value or returns nothing. Function is a subprogram
that helps reduce coding.

Advantages of Functions:

 Function makes the lengthy and complex programs easy and in short forms.
 By using functions, memory space can be properly utilized and less memory is
required to run the program.
 It allows more than one person to work on one program.
 Function increases the execution speed of the program and makes the
programming simple.
 By using the function, portability of the program is very easy.
 It removes the redundancy.
 Debugging (removing error) becomes very easier and fast using the function
sub-programming
 Functions are more flexible than library functions.
 Testing (verification and validation) is very easy by using functions.

Types of Functions:

There are two types of functions, which are

1. Built in functions (Pre defined functions or library functions)


2. User defined functions.
Dr. G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET
Built-in functions (library functions): 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 functions similarly we
have strcmp() and strlen() for string manipulations.

Note: To use a library function, we have to include the corresponding header file using
the preprocessor directive #include.

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

User Defined Functions in C

A user can create their own functions for performing any specific task of a program
called user defined functions.

To create and use these functions we have to know these 3 elements.

1. Function Declaration
2. Function Definition
3. Function Call

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.

Syntax:

return_type function_name(arg_type1, ……,arg_typen);

Function call:

When we wish to use a function, we can "call" it by name, then control is sent to the
block of code with that name.

Any values that the function needs to perform its job are listed in the parentheses that
immediately follow the name are called arguments.

Dr. G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


The computer will retrieve the values held by the variables and hand them off to the
function for its use.

The number of arguments (or values) must match the variables in the definition by
type and number.

A semicolon must be present, when the function is called within the main() function.

Syntax:

function_name (actual parameters);

The following figure illustrates function prototype, function call and function definition.

Function definition:

The function definition consists of the whole description and code of a function. It tells
what the function is doing and what are the inputs and 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:

1. Function Header

Dr. G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


2. Function body

Function Header- The first line of code is called Function Header.

E.g; 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.

Categories of functions:

The functions are categorized into 4 types based on the arguments and return
type. They are

1. Functions with no arguments and no return value.


2. Functions with arguments and no return value.
3. Functions with no arguments but return value.
4. Functions with arguments and return value.

Functions with no arguments and no return type:

Here, the called function does not receive any data from the calling function and it
does not return any data back to the calling function. Hence, there is no data transfer
between the calling function and the called function.

Functions with arguments and no return value

Here, the called function receives the data from the calling function. The arguments
should match in number, data type and order. But, the called function does not return

Dr. G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


any value back to the calling function. Instead, it prints the data or results in its scope
only. It is one-way data communication between the calling function and the called
function.

Functions with no arguments but return value

Here, the called function does not receive any data from the calling function. It
manages with its local data to carry out the specified task. However, after the specified
processing the called function returns the computed data to the calling function. It is
also a one-way data communication between the calling function and the called
function.

Functions with arguments and return value.

Here, the called function receives data from the calling function and it can compute
the task using these arguments. After computing the task, the called function returns
the results to the calling function. In this way the main() function will have control over

Dr. G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


the function. It is the two-way communication between the calling function and the
called function.

Parameter Passing Mechanism

A method of information interchange between the calling function and called function is
known as parameter passing. There are two methods of parameter passing:

1. Call by Value

2. Call by Reference

Call by Value: The call-by-value method copies the value of an argument into the formal
parameter of the function. Therefore, changes made by the function to the parameters have
no effect on the variables used to call it.

Call by Reference:

Call by reference method copies the address of an argument into the formal parameter. Inside
the function, this address is used to access the argument used in the call. In this way, changes
made to the parameter affect the variable used in the call to the function.

Call by reference is achieved by passing a pointer as the argument. Of course, in this case, the
parameters must be declared as pointer types.

Dr. G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


Differences between call by value and call by reference

Call By Value Call By Reference


While calling a function, we pass values of While calling a function, instead of passing
variables to it. Such functions are known as the values of variables, we pass address of
“Call By Values”. variables (location of variables) to the
function known as “Call By References”.
In this method, the value of each variable in In this method, the address of actual
calling function is copied into corresponding variables in the calling function are copied
dummy variables of the called function. into the dummy variables of the called
function.
With this method, the changes made to the With this method, using addresses we would
dummy variables in the called function have have access to the actual variables and
no effect on the values of actual variables in hence we would be able to manipulate
the calling function. them.
// call by value // Call by Reference
void swapx(int x, int y); // Main function #include<stdio.h> // Function Prototype
int main() void swapx(int*, int*);
{ int a = 10, b = 20; int main()
swapx(a, b);
{ int a = 10, b = 20;
printf("a=%d b=%d\n", a, b);
return 0; swapx(&a, &b);
} printf("a=%d b=%d\n", a, b);
return 0;
void swapx(int x, int y)
}
{ int t;
void swapx(int* x, int* y)
t = x;
{ int t;
x = y;
t = *x;
y = t;
*x = *y;
printf("x=%d y=%d\n", x, y);
*y = t;
}
printf("x=%d y=%d\n", *x, *y);
Output: x=20 y=10
}
a=10 b=20
Output: x=20 y=10
a=20 b=10

Dr. G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


The actual values of a and b remain The actual values of a and b get changed
unchanged even after exchanging the values after exchanging values of x and y.
of x and y.
In call by value, we cannot alter the values In call by reference, we can alter the values
of actual variables through function calls. of variables through function calls.
Values of variables are passes by Simple Pointer variables are necessary to define to
technique. store the address values of variables.

Passing Arrays to functions

Array can be passed to function by two ways:

1. Pass Entire array

2. Pass Array element by element.

1. Pass Entire array (Formal Parameters as a pointer, sized array, sized unsized 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 is “Pass by Address”

Note: We must pass array length to the function.

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 do not affect the original value.
 Function doesn’t get complete access to the original array element.

Function passing method is “Pass by Value”.

Dr. G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


Disadvantages of Pass Array element by element

1. In which we are calling the function again and again but with different array element
is too much time consuming.

2. It is better to pass complete array to the function so that we can save some system
time required for pushing (insertion) and popping (remove).

3. We can also pass the address of the individual array element to function so that
function can modify the original copy of the parameter directly.

Passing 2D arrays to functions

Like one dimensional array, we can also pass multidimensional arrays to the functions. The
approach is similar to the passing one-dimensional arrays.

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

2. In the function definition, we must indicate that the array has two dimensions by
including two sets of brackets.

3. The size of the second dimension must be specified.

4. The prototype declaration should be like the function header.

Passing Strings to functions

The strings are treated as character arrays in C and therefore the rules for passing strings to
functions are very similar to those for passing arrays to functions.

Basic rules are.

1. The string to be passed must be declared as formal argument of the function when it
is defined.

 Example

void display (char item names[ ])

……………….

Dr. G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


}

2. The function prototype must show that the argument is a string. For the above function
definition, the function prototype can be written as

 void display (char str[ ]);

3. A call to the function must have a string array name without subscripts as its actual
argument.

 Example display(name)
 Write a c program to find length of the string using functions.
Recursion

Definition: A function called itself is called recursion.

Advantages of recursion

1. The code may be easier to write if the problem is in recursive nature.


2. Reduce unnecessary calling of function.
3. Extremely useful when applying the same solution.
4. Recursions reduce the length of code.
5. It is very useful in solving the data structure problems like infix, prefix, postfix
evaluations.

Disadvantages of recursion

1. Recursive functions are generally slower than non-recursive function.


2. It may require a lot of memory space to hold intermediate results on the system stacks.
3. Hard to analyze or understand the code.
4. It is not more efficient in terms of space and time complexity.
5. The computer may run out of memory if the recursive calls are not properly checked.

A recursive algorithm uses itself to solve one or more smaller identical problems.

Recursive Methods Must Eventually Terminate:

 A recursive method must have at least one base or stopping case.


 A base case does not execute a recursive call stops the recursion.
Each successive call to itself must be a "smaller version of itself.”

 An argument that describes a smaller problem

 A base case is eventually reached.

Dr. G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


Example: Finding factorial of a given number N

N! = (N-1)! * N [for N > 1]

= 1 [for N= 1]

= 3!
= 2! * 3
= (1! * 2) * 3
=1*2*3
C Program to find factorial of a given number.

#include <stdio.h>
#include <stdlib.h>
int fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=fact(n);
printf("\n Factorial of a given number %d is %d",n,f);
return 0;
}
int fact(int n)
{
if(n==1||n==0)
{
return 1;
}
else
{
return n*fact(n-1);
}

Dr. G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


}
C program to find GCD of two number using recursion

#include <stdio.h>
#include <stdlib.h>
int gcd(int,int);
int main(int argc, char *argv[]) {
int a,b,f;
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b);
f=gcd(a,b);
printf("\n GCD of %d and %d is %d",a,b,f);
return 0;
}
int gcd(int n1,int n2)
{
if(n2==0)
{
return n1;
}
else
{
return gcd(n2,n1%n2);
}
}
C program to display fibonacci series using recursion

Fib(n) = fib(n-1)+fib(n-2)

Fib(0) = 0 fib(1)=1

Dr. G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


Program

#include <stdio.h>
#include <stdlib.h>
int fib(int);
int main(int argc, char *argv[]) {
int i,n;
printf("\n Enter no of elements in the series:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n%d",fib(i));
}
return 0;
}
int fib(int n)
{
if(n==0)
{
return 0;
}
else if(n==1)
{
return 1;
}
else
{
return fib(n-1)+fib(n-2);
}
}

Dr. G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


C Program to implement Ackermann function

#include <stdio.h>
#include <stdlib.h>
int ack(int,int);
int main(int argc, char *argv[]) {
int a,b;
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b);
printf("\n ack(%d,%d) = %d",a,b,ack(a,b));
return 0;
}
int ack(int x,int y)
{
if(x==0)
{
return y+1;
}
else if(y==0)
{
return ack(x-1,1);
}
else
{
return ack(x-1,ack(x,y-1));
}
}

Dr. G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


POINTERS
Pointer is a derived data type.

Definition: Pointer is a variable which contains the address in memory of another variable.

Benefits of Pointers

1. Pointers are more efficient in handling arrays and data tables.


2. Pointers can be used to return multiple values from a function.
3. Pointers permit references to functions and thereby facilitating passing of functions as
arguments to other functions
4. The use of pointer arrays to character strings results in saving of data storage space in
memory.
5. Pointers support dynamic memory management
6. Pointers provide an efficient tool for manipulating dynamic data structures such as
structures, linked lists, queues, stacks and trees.
7. Pointers reduce length and complexity of programs
8. They increase execution speed and thus reduce the program execution time.

Whenever we declare a variable the system allocates memory to hold the value of the variable.
Consider the following statement.

int quantity = 179;

This statement instructs the system to find a location for the integer variable quantity and puts
the value 179 in that location. Let us assume that the system has chosen the address location
5000 for quantity.

Quantity Variable

179 Value

5000 Address

During execution of the program the system always associates the name quantity with the
address 5000. We may have access to the value 179 by using either name quantity or the address
5000. Since memory address are simply numbers they can be assigned to some variables that can
be stored in some memory. Such variables that hold memory addresses are called pointer
variables.

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


A pointer variable is a variable that contains an address which is a location of another variable in
memory.

Variable Value Address

Quantity 179 5000

P 5000 5048

The value of the variable P is the address of the variable quantity, we may access the value of
quantity by using the value of p and therefore, we say that the variable p points to the variable
quantity. Thus P gets the name pointer.

Underlying pointer concepts

Pointers are built on the three underlying concepts. They are

1. Pointer constants 2. Pointer value 3. Pointer variable

Pointer Constants:- Memory address within a system are referred to as pointer constants. We
cannot change them, we can only use them to store data values.

Pointer Value: – We cannot save the value of a memory address directly. We can only obtain the
value through the variable stored there using the address operator (&) . The value thus obtained
is known as pointer value. The pointer value may change during execution of the program.

Pointer variable :- once we have a pointer value, it can be stored into another variable. The
variable that contains a pointer value is called a pointer variable.

Accessing the address of a variable

The address of operator (&) returns the address of the variable associated with it.

e.g: p = &quantity;

would assign the address 5000 to the variable P.

The & operator can be used only with a simple variable or an array element.

The following are illegal use of address operator.

1. &125 (pointing at constant)

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


2. int x[10];

&x (pointing at array name)

3. &(x+y) (pointing at expression).

If x is an array, then expressions such as &x[0] and &x[i+3] are valid and represent the address
of 0th and (i+3)th elements of x.

C program to print the address of a variable along with its value.

Declaring Pointer Variables

Syntax

data_type *pt_name;

This tells three things about the variable pt_name

1. the asterisk (*) tells that the variable pt_name is a pointer variable.

2. pt_name needs a memory location

3. pt_name points to a variable of type data_type.

e.g: int *p; //p is a pointer variable that points to an integer data type.

p ? ?

contains garbabe points to unknown location

Initialization of Pointer variables

The process of assigning address of a variable to a pointer variable is known as initialization.


Once pointer variable has been declared we can use the assignment operator to initialize the
variable.

Example: int quantity;

int *p;

p = &quantity;

or

we can also combine the initialization with the declaration.

int *p = &quantity;

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


Note:

1. We must ensure that the pointer variable always point to the corresponding type of the data.

It is possible to combine the declaration of data variable, the declaration of pointer variable and
the initialization of the pointer variable in one step.

e.g: int x,*p = &x; //valid

int *p = &x, x; //invalid

we could also define a pointer variable with an initial value of NULL or 0.

int *p = NULL;

Accesssing a Variable Through its Pointer:

The indirection operator (*), dereferencing operator id used to access the value of the variable
using the pointer.

e.g:

int quantity, *p,n;

quantity = 179;

p = &quantity;

n = *p;

The first line declares quantity and n as integer variables and p as a pointer variable pointing to an
integer. The second line assigns the value 179 to quantity and the third line assigns the address of
quantity to the pointer variable p. the fourth line contain the indirection operator * . When the
operator * is placed before a pointer variable in an expression, the pointer returns the value of the
variable of which the pointer value is the address. So *p returns the value of the variable quantity.

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


C Program to accessing a variable through its pointer
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
int *ptr;
x=10;
ptr = &x;
y = *ptr;
printf(“\n value of x is %d \n”,x);
printf(“\n %d is stored at address %u \n”,x, &x);
printf(“\n %d is stored at address %u \n”,*&x, &x);
printf(“\n %d is stored at address %u \n”,*ptr, ptr);
printf(“\n %d is stored at address %u \n”,ptr,&ptr);
printf(“\n %d is stored at address %u \n”,y,&y);
}

Chain of Pointers

It is possible to make a pointer to point to another pointer, thus creating a chain of pointers.

p2 p1 variable
Address 2 Address 1 Value

here the pointer p2 contains the address of the pointer variable p1, which points to the location
that contains the desired value. This is known as multiple indirections.

int **p2;

This declaration tells the computer that p2 is a pointer to a pointer of int type. The pointer p2 is
not a pointer to an integer, but rather a pointer to an integer pointer.

void main()
{
int x, *p1, **p2;
x = 100;
p1 = &x;
p2 = &p;
printf(“%d”,**p2);
}
This code will display the value 100. Here p1 is declared as a pointer to an integer and p2 as a
pointer to a pointer to an integer.

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


Pointer Expressions
The following statements are valid
y = *p1 * *p2;
sum = sum + *p1;
z = 5 * - *p2/ *p1;
*p2 = *p2 + 10;
The following is wrong
Z = 5 * - *p2 /*p1;

The symbol /* is considered as the beginning of a comment and therefore the statement fails.
Note:
1. C allows us to add to or subtract integers from the pointer.
2. If p1 and p2 are the pointers point to the same array, then p2-p1 gives the number of
elements between p1 and p2.
3. Pointers can be compared using the relational operators.
4. We may not use pointers in division or multiplication.
5. Two pointers cannot be added.

Pointer Increments and scaling factor

An expression like
p1++;
will cause the pointer p1 to point to the next value of its type. For example, if p1 is an integer
pointer with an initial value, say 2800, then after the operation p1 = p1 + 1, the value of p1 will
be 2802, and not 2801. That is, when we increment a pointer, its value is increased by the length
of the data type that it points to, this is called the scale factor.

Data Type Scale factor


Characters 1 byte
Integers 2 bytes
Float 4 bytes
long integers 4 bytes
Double 8 bytes

Important Points on pointers


1. A pointer variable can be assigned the address of another variable
2. A pointer variable can be assigned the value of another pointer variable
3. A pointer variable can be initialized with NULL or zero value
4. A pointer variable can be prefixed or post fixed with increment or decrement operators
5. An integer value may be added or subtracted from a pointer variable
6. When two pointers point to the same array, one pointer variable can be subtracted from
another

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


7. When two pointers point to the objects of the same data types, they can be compared
using relational operators
8. A pointer variable cannot be multiplied by a constant
9. Two pointer variables cannot be added
10. A value cannot be assigned to an arbitrary address (i.e. &x = 10; is illeagal).

Pointers and Arrays


When an array is declared, the compiler allocates a base address and sufficient amount of storage
to contain all the elements of the array in contiguous memory locations. The base address is the
location of the first element of the array. The compiler also defines the array name as a constant
pointer to the first element. Suppose we declare an array x as follows:

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


Suppose the base address of x is 1000 and assuming that each integer requires two bytes, the five
elements will be stored as follows:

X[0] x[1] x[2] x[3] x[4] x[5]


Elements
Value
1 2 3 4 5 6

Address 1000 1002 1004 1006 1008 1010

Write a C program to find sum of array elements using pointers

#include<stdio.h>
#include<conio.h>
void main()
{
int *p,a[5],sum=0,i;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);
p++;
}
p=a;
for(i=0;i<5;i++,p++)
{
sum=sum+*p;

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


}
printf("\n Sum of array = %d",sum);
getch();
}
Write a C program to find largest element from the given array elements using pointers.

#include<stdio.h>
#include<conio.h>
void main()
{
int *p,a[5],max,i;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);
p++;
}
p=a;
max=*p;
p++;
for(i=1;i<5;i++,p++)
{
if(max < *p)
{
max=*p;
}
}
printf("\n largest value = %d\n",max);
getch();
}

Write a C program to find smallest element from the given array elements using pointers.

#include<stdio.h>
#include<conio.h>
void main()
{
int *p,a[5],min,i;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


p++;
}
p=a;
min=*p;
p++;
for(i=1;i<5;i++,p++)
{
if(min > *p)
{
min=*p;
}
}
printf("\n Smalest value = %d\n",min);
getch();
}

Write a C program to sort array elements using pointers.

#include<stdio.h>
#include<conio.h>
void main()
{
int *p,a[5],min,i,j,*temp;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);
p++;
}
p=a;
for(i=0;i<4;i++)
{
for(j=0;j<(5-i-1);j++)
{
if(*(p+j) > *(p+j+1))
{

*temp = *(p+j);
*(p+j) = *(p+j+1);
*(p+j+1) = *temp;
}
}
}

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


printf("\n After sotring array elements are\n");
for(i=0;i<5;i++,p++)
{
printf("%d\n",*p);
}
getch();
}

Pointers and character strings

String initialization and declaration


char str[5] = “good”;
The compiler automatically inserts the null character ‘\0’ at the end of the string. C supports an
alternative method to create strings using pointer variable of type char.
e.g: char *str = “good”;
This creates a string for the literal and then stores its address in the pointer variable str. The
pointer str now points to the first character of the string “good”.
We can also use the run time assignment for giving values to a string pointer.
e.g: char *str;
str = “good”;
The assignment
str1 = “good”;
Is not a string copy, because the variable str1 is a pointer, not a string.
We can print the content of the string str1 using either printf or puts functions as follows

printf(“%s”,str1);
puts(str1);

Although str1 is a pointer to the string, it is also the name of the string. Therefore we do not need
to use indirection operator *.

C program to count the string length using pointers.

#include<stdio.h>
#include<conio.h>
void main()
{
char *s;
int len=0;
clrscr();
printf("\n Enter a string \n");

scanf("%s",s);

while(*s!='\0')

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


{
len++;
s++;
}
printf("Length = %d",len);
}

Write a c program to concatenate two strings using pointers.

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char *s1,*s2,*s3;
int i=0,j;
clrscr();
printf("\n Enter first string\n");
scanf("%s",s1);
printf("\n Enter second string\n");
scanf("%s",s2);

for(i=0,s3=s1;*s3!='\0';s3++,i++);
for(j=0;*s2!='\0';j++)
{
*(s3+j) = *(s2+j);
}
*(s3+j)='\0';
printf("\n concatenated string = %s\n",s1);
getch();
}

In C, a constant character string always represents a pointer to that string. And therefore, the
following statements are valid.
char *name;
name = “delhi”;

These statements will declare name as a pointer to character and assign to name the constant
character string “delhi”. We might remember that this type of assignment does not apply to
character arrays.
The statements like
char name[20];
name = “Delhi”;
do not work.

Array of Pointers

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


Consider the following array of string
char name[3][25];
this says that the name is a table containing three names, each with a maximum length of 25
characters. The total storage requirements for the name table are 75 bytes.

We know that rarely the individual strings will be equal lengths. Therefore, instead of making
each row a fixed number of characters, we can make it a pointer to a string of varying length.
For example:
Char *name[3] = {
“New Zealand”;
“Australia”,
“India”
};
Declares name to be an array of three pointers to characters, each pointer pointing to a particular
name as:
This declaration allocates only 28 bytes, sufficient to hold all the characters as shown.

The following statements would print out all the three names:
for(i=0;i<3;i++)
{
Printf(“%s\n”,name[i]);
}
To access the jth character in the ith name, we may write as
*(name[i]+j)
Note:
1. The character arrays with the rows of varying length are called ‘ragged arrays’ and are
better handled by pointers.
2. *p[3] declares p as an array of three pointers.
3. (*p)[3] declares p as a pointer to an array of three elements.

C program to display city names using array of pointers.

#include<stdio.h>
#include<conio.h>
void main()
{
int i;

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


char *name[3];
clrscr();
for(i=0;i<3;i++)
{
printf("\n Enter %d th city name\n",i+1);
fflush(stdin);
scanf("%s",name[i]);
}
for(i=0;i<3;i++)
{
printf("\n %d city is %s\n",i+1,name[i]);
}
getch();
}
Write a c program to sort city names using pointers.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* run this program using the console pauser or add your own getch, system("pause") or input
loop */
int main(int argc, char *argv[]) {
char (*p)[10],name[5][10],temp[10];
int i,j,k;
p=name;
printf("\n Enter 5 city names\n");
for(i=0;i<5;i++)
{
fflush(stdin);
scanf("%s",p[i]);
}
for(i=1;i<5;i++)
{
for(j=0;j<=(5-i-1);j++)
{
if(strcmp(p[j],p[j+1])>0)
{
strcpy(temp,p[j]);
strcpy(p[j],p[j+1]);
strcpy(p[j+1],temp);
}
}
}
printf("\n After sorting city names are\n");

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


for(i=0;i<5;i++)
{
printf("\n%s",p[i]);
}

return 0;
}

Pointers as Function Arguments


When we pass address to a c=function, the parameters receiving the address should be pointers.
The process of calling a function using pointers to pass the addresses of variables is known as
call by reference.
The function which is called by reference can change the value of the variable used in the call.

C program to swap two numbers using call by reference.

#include<stdio.h>
#include<conio.h>
void swap(int *a,int *b);
void main()
{
int x,y,z;
clrscr();
printf("Enter two numbers\n");
scanf("%d%d",&x,&y);
printf("\n Before swaping numbers are \n");
printf("%d\t%d\n",x,y);
swap(&x,&y);
printf("\n After swapping numbers are \n");
printf("%d\t%d\n",x,y);
getch();
}
void swap(int *p,int *q)
{
int *t;
*t = *p;
*p = *q;
*q = *t;
}

Output:
Enter two numbers
10
20

Before swaping numbers are

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


10 20

After swapping numbers are


20 10

Functions returning pointers

A function can return a single value by its name or return multiple values through pointer
parameters. Since pointers are a data type in C, we can also force a function to return a pointer to
the calling function.
C program to illustrate function returns a pointer

#include<stdio.h>
#include<conio.h>
int *large(int *p, int *q);
void main()
{
Int a=10, b=20, *p;
clrscr();
p=large(&a,&b);
printf(“%d”,*p);
getch();
}
int *large(int *c,int *d)
{
if(*c > *d)
return c;
else
return d
}

The function larger receives the addresses of the variable a and b, decides which one is larger
using the pointers x and y and then returns the address of its location. The returned value is then
assigned to the pointer variable p in the calling function. In this case, the address of b is returned
and assigned to p and therefore the output will be the value of b., b namely 20.

Pointers to functions
A function like a variable, has a type and an 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 is declared as follows
type (*fptr) ( );
this tells the compiler that fptr is a pointer to a function, which returns type value. The
parenthesis around *fptr are necessary.

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


We can make a function pointer to point to a specific function by simply assigning the name of
the function to the pointer. For example
double mul(int, int);
double (*p1) ( );
P1 = mul;
Declare 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 may now use the pointer p1 with the list of
paremeters.
(*p1) (x, y);
is equivalent to
mul(x,y);

C Program to illustrate a pointer to functions

#include<stdio.h>
#include<conio.h>
int fun(int,int);
int (*f)();
void main()
{
int a,b,c,*p,*q,r;
clrscr();
printf("Enter a & b Values\n");
scanf("%d%d",&a,&b);
//p=&a;
//q=&b;
f=fun;
r=(*f)(a,b);
printf("\nSum=%d",r);
}
int fun(int x,int y)
{
int z;
z = x +y;
return z;
}

Compatibility and Casting


Compatibility – a variable declared as a pointer is not just a pointer type variable. It is also a
pointer to a specific fundamental data type, such as a character. A pointer therefore always has a
type associated with it. We cannot assign a pointer of one type to a pointer of another type,
although both of them have memory addresses as their values. This is known as incompatibility.

Casting

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


All the pointer variables store memory addresses. Which are compatible, but what is not
compatible is the underlying data type to which they point to. We cannot use the assignment
operator with the pointers of different types. We can however make explicit assignment between
incompatible pointer types by using cast operator, as we do with the fundamental types.
Example
int x;
char *p;
p = (char *) &x;

Void Pointer (Generic Pointer)


It represents any pointer type. All pointer types can be assigned to a void pointer and a void
pointer can be assigned to any pointer without casting.
Syntax:
void *ptr;
Note:
1. A void pointer has no object type. It cannot be dereferenced.

Pointers and structures


Suppose product is an array variable of struct type. The name product represents the address of
its zeroth element.
struct inventory
{
char name[30];
int number;
int price;
}product[2],*ptr;
This statement declares product as an array of two elements, each of the type struct inventory
and ptr as a pointer to data objects of the type struct inventory.
The following assignment
ptr = product;
would assign the address of the zeroth element of product to ptr. That is the pointer ptr will now
point to product[0]. Its members can be accessed using the following statement.
ptr  name
ptr  number
ptr  price
the symbol  is called the arrow operator (member selection operator) and is made up of a
minus sign and a greater than sign. Ptr is simply another way of writing product[0].
When ptr is incremented by one, it is made to point to the next record i.e. product[1].
Also we can access the members using the following statement.
(*ptr).name

C Program to illustrate pointer to structures


#include<stdio.h>
#include<conio.h>
struct inventory
{

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


char name[10];
int number;
int price;
};
void main()
{
int i;
struct inventory product[3],*ptr;
clrscr();
ptr=product;
for(i=0;i<3;i++,ptr++)
{
printf("Enter name \n");
fflush(stdin);
scanf("%s",ptr->name);
printf("Enter number\n");
scanf("%d",&ptr->number);
printf("Enter price\n");
scanf("%d",&ptr->price);
}
printf("Structure details are\n");
for(i=0,ptr=product;i<3;i++,ptr++)
{

printf("\n %d th name = %s \t number - %d \t price - %d \n",i+1,ptr->name, ptr->number, ptr-


>price);
}
getch();
}

Dynamic memory Allocation:


The process of allocating memory at runtime is known as dynamic memory allocation.
C doesn.t have inherently have this facility, there are four library functions known as library
management functions that can be used for allocating and freeing memory during program
execution.
Memory allocation functions are

Function Task
malloc Allocate required size of bytes and returns a pointer to the first byte of the
allocated space
calloc Allocates space for an array of elements initializes them to 0 and then returns a
pointer to the memory
free Frees previously allocated memory
realloc Modifies the size of previously allocated space.

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


Memory Allocation Process

Local Variables Stack


Free Memory Heap
Global Variables
Permanent
C Programming Instructions
Storage Area

Program instructions and global variables are stored in a region known as permanent storage area
and the local variables are stored in another area known as stack. The area between these two
regions is available for dynamic memory allocation during execution of a program. This free
memory is called heap. The size of the heap changes when program is executed due to creation
and death of variables that are local to functions and block. Therefore it is possible to encounter a
overflow during dynamic memory allocation process. In such situations the memory allocation
functions mentioned above return a NULL pointer.

Malloc:
A block of memory may be allocated using the function malloc. The malloc function reserves a
block of memory of specified size and returns a pointer of type void. This means we can assign it
to any type of pointer.

ptr = ( cast-type *)malloc(byte-size);

ptr is a pointer of type cast-type. The malloc returns a pointer to an area of memory with size

x = (int *)malloc(100*sizeof(int));

Note:
1. The storage space allocated dynamically has no name and therefore its contents can be
accessed only through pointer.
2. malloc allocates a block of contiguous bytes. The allocation can fail if the space in the heap is
not sufficient to satisfy the request. If it fails it returns a NULL.

Calloc:
Calloc is used to allocating memory space at run time for storing derived data types such as
arrays and structures. While malloc allocates a single block of storage space, calloc allocates
multiple blocks of storage, each of the same size, and then sets all bytes to 0.

ptr = (cast-type*)calloc(n, elem-size);

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


The above statement allocates contiguous space for n blocks, each of size elem_size bytes. All
bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If
there is not enough space it returns NULL.

realloc():
realloc is used to allocate or reduce memory size during execution of a program.
ptr= malloc(size);
Then reallocation of space may be done by the statement.
ptr = realloc( ptr, new size);
This function allocates a new memory space of size new size to the pointer variable and returns a
pointer to the first byte of the new memory block.
If the function is unsuccessful in locating additional space it returns a NULL pointer and the
original block is lost.

free():
Compile time storage of a variable is allocated and released by the system in accordance with its
storage class. With the dynamic run-time allocation, it is our responsibility to release the space
when it is not required
Free is used release the memory is created by malloc or calloc function.
Syntax:
free(ptr);
Note:
1. It is not the pointer that is being released but rather what it points to.
2. To release an array of memory that was allocated by calloc we need only to release the
pointer once. It is an error to attempt to release elements individually.

Write a program that uses a table of integers whose size will be specified interactively at
runtime.

Self-referential Structure:

Self-referential structure is a structure in which one member is a pointer which points to the same
type of structure is called self-referential structure.

Example1: Single Linked list node

struct node
{
int data;
struct node *next;
}

Visual representation

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


In the above example, each node has two fields, they are data and next. Here next is a pointer
which points to the same type structure. Hence it is called as a self-referential structure.

Example2: Double linked list node

Struct node
{
Int data;
Struct node *prev;
Struct node *next;
}

In the above example, each node has three fields, they are data, previous and next. Here prev and
next are the pointers which points to the same type structure. Hence it is also called as a self-
referential structure.

G. Nagaraju, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET


Dear Students, Execute the following pointer programs and then write these programs in the
record.

Pointer Programs

1. Write a c program to read and display array elements.


2. Write a c program to find sum of array elements using pointers.
3. Write a c program to find largest value from array elements using pointers.
4. Write a c program to find smallest value from array elements using pointers.
5. Write a c program to sort array elements using pointers.
6. Write a c program to find matrix multiplication using pointers.
7. Write a c program to find matrix addition using pointers.
8. Write a c program to find trace of a matrix using pointers.
9. Write a c program to find string length using pointers.
10. Write a c program to concatenate two stings using pointers.
11. Write a c program to sort city names using pointers.
12. Write a c program to find largest of two numbers using function returns a pointer.
13. Write a c program to illustrate pointer to a function.
14. Write a c program to illustrate pointers and structures.
UNIT-IV

STRUCTURES AND UNIONS

Definition1: A structure is a collection of data items of different types using a single


name.
Definition2: Structure is a convenient tool for handling a group of logically related
data items
Examples:
Time : seconds, minutes, hours
Date : day, month, year
Book : author, title, price, year
City : name, country, population
Address : name, door-number, street, city
Customer : name, telephone, city, category
Structures must be defined first for their format that may be used later to declare
structure variables.
Example: Book database
Defining a Structure
Book database consisting of book name, author, number of pages, and price. We
define a structure to hold this information as follows.
struct book_bank
{
char title[10];
char author[10];
int pages;
float price;
};
The keyword struct declares a structure to hold the details of four data fields, namely
title, author, pages and price. These fields are called structure elements or members.
Each member may belong to a different type of data.
book_bank is the name of the structure and is called the structure tag.
The tag name may be used subsequently to declare variables that have the tags
structure.
General format of a structure definition is as follows.
Struct tag_name
{
Data type member1;
Data type member2;

};

Remember:

1. The template is terminated with a semicolon.


2. While the entire definition is considered as a statement, each member is
declared independently for its name and type in a separate statement inside
the template.
3. The tag_name such as book_bank can be used to declare structure variables
of its type, later in the program.

Differences between arrays and structures

1. An array is a collection of related data elements of same type whereas


structures can have elements of different types.
2. An array is derived data type, where as a structure is a programmer-defined
one.
3. Any array behaves like a built-in-data type. All we have to do is to declare an
array variable and use it. But in the case of a structure, first we have to design
and declare a data structure before the variables of that type are declared and
used.

Declaring structure variables

After defining a structure we can declare variables of that type. It includes the
following elements.
1. The keyword struct.
2. The structure tag name
3. List of structure variables (separated by commas)
4. A terminating semi colon.
Example:
Struct book_bank book1,book2,book3;
Declares book1, book2 and book3 as variables of type struct book_bank;
The use of tag is optional
struct
{
char title[10];
char author[10];
int pages;
float price;
}book1,book2,book3;

Declares book1,book2 and book3 as structure variables representing three books,


but does not include a tag name. This approach is not recommended for the
following reason.
Without a tag name, we cannot use it for future declarations.

Accessing Structure Members

Three ways to access structure members, they are


“.” (dot operator) – n.x ( structure variable)
Using indirection notation – (*ptr).x
Using selection notation - ptr->x (arrow operator) –A pointer points to the structure

Structure Initialization

There are two ways to initialize structure members.


1. Compile time initialization
2. Runtime initialization

Compile time initialization

Example:
struct book_bank
{
char title[20];
char author[20];
int pages;
int price;
}book1={“Cprogramming”,”balaguruswamy”,100,200};
(OR)
Struct book_bank book1 ={“Cprogramming”,”balaguruswamy”,100,200};

This assigns the value “Cprogramming” to book1.title, “balaguruswamy” to


book1.author, 100 to book1.pages and 200 to book1.price.
The compile time initialization of a structure variable must have the following
elements.
1. The keyword struct.
2. The structure tag name.
3. The name of the variable to be declared.
4. The assignment operator =.
5. A set of values for the members of the structure variable, separated by
commas and enclosed in braces.
6. A terminating semicolon.

Copying and Comparing Structure Members

Two variables of the same structure type can be copied the same way as ordinary
variables. If book1 and book2 belong to the same structure, then the following
statements are valid.
book2=book1
how ever the statement such as
book1 == book2 is invalid.
Note:
C does not permit any logical operations on structure variables. In case we need to
compare them, we may do so by comparing members individually.

Array of structures

For example in analyzing the marks obtained by a class of students, we may use a
template to describe student name and marks obtained in various subjects and then
declare all the students as structure variables.
In such cases, we may declare an array of structures, each element of the array
representing a structure variable.
e.g: struct class student[100];
defines an array called student, that consists of 100 students. Each element is
defined to be of the type struct class.
Consider the following declaration.
struct marks
{
int subject1;
int subject2;
int subject3;
};

struct marks student[3] = {{1,2,3},{4,5,6},{7,8,9}};


This declares the student as an array of three elements student[0], student[1] and
student[2] and initializes their members as follows.
student[0].subject1 = 1
student[0].subject2 = 2
student[0].subject3 = 3
student[1].subject1 = 4
student[1].subject2 = 5
student[1].subject3 = 6
student[2].subject1 = 7
student[2].subject2 = 8
student[2].subject3 = 9

Arrays within structures

C permits the use of arrays as structure members.


e.g
struct marks
{
int number;
float subject[3];
}student[2];

Here the member subject contains three elements, subject[0], subject[1] and
subject[2]. These elements can be accessed using appropriate subscripts.
For example the name
Student[1].subject[2];
Would refer to the marks obtained in the third subject by the second student.

Structures within structures

Structures within a structure means nesting of structures. Nesting of structures is


permitted in C.
e.g:
struct salary
{
char name[10];
char department;
int basic_pay;
int dearness_allowance;
int house_rent_allowance;
int city_allowance;
}employee;

This structure defines name, department, basic pay and three kinds of allowances.
We can group all the items related to allowance together and declare them under a
substructure as shown below.
struct salary
{
char name[10];
char department;
struct
{
int dearness_allowance;
int house_rent_allowance;
int city_allowance;
}allowance;
}employee;
The salary structure contains a member named allowance, which itself is a structure
with three members. The members contained in the inner structure namely
dearness, house_rent, and city can be referred to as
Employee.allowance.dearness
Employee.allowance.house_rent
Employee.allowance.city
Note:
1. An inner-most member in a nested structure can be accessed by chaining all
the concerned structure variables with the member using dot operator.

Structures and functions

There are three methods by which the values of a structure can be transferred from
one function to another.
1. The first method is to pass each member of the structure as an actual
argument of the function call. The actual arguments are then treated
independently like ordinary variables. This is the most elementary method and
becomes unmanageable and inefficient when the structure size is large.
2. The second method involves passing of a copy of the entire structure to the
called function. Since the function is working on a copy of the structure, any
changes to structure members within the function are not reflected in the
original structure. It is therefore necessary for the function to return the entire
structure back to the calling function, all compilers may not support this
method of passing the entire structure as a parameter.
3. The third approach employs a concept called pointers to pass the structure as
an argument. In this case, the address location of the structure is passed to
the called function. The function can access indirectly the entire structure and
work on it. This is similar to the way arrays are passed to function. This
method is more efficient as compared to the second one.

Structures and functions - Important Points

1. The called function must be declared for its type, appropriate to the data type
it is expected to return. For example if it is returning a copy of the entire
structure, then it must be declared as a struct with an appropriate tag name.
2. The structure variable used as the actual argument and the corresponding
formal argument in the called function must be of the same struct type.
3. The return statement is necessary only when the function is returning some
data back to the calling function. The expression may be any simple variable
or structure variable or an expression using simple variables.
4. When a function returns a structure, it must be assigned to a structure of
identical type in the calling function.
5. The called functions must be declared in the calling function appropriately.

UNIONS

A union is a collection of different data types, in union all members share the same
memory location.
Union is a derived datatype.
Union is similar to structure, but the difference is in structure each member has its
own storage location, whereas all the members of a union use the same location.
Like structures, a union can be declared using the keyword union as follows.
union item
{
int m;
float x;
char c;
}code;

This declares a variable code of type union item. The union contains three members,
each with a different data type. However, we can use only one of them at a time.
This is due to the fact that only one location is allocated for a union variable,
irrespective of its size.

The compiler allocates a piece of storage that is large enough to hold the largest
variable type in the union.
In the declaration above the member x requires 4 bytes which is the largest among
the members. The above figure shows how all the three variables share the same
address. This assumes that a float variable requires 4 bytes of storage.
Dot (.) operator is used to access a union member. Like
code.m
code.x
code.c
all are valid member variables. During accessing, we should make sure that we are
accessing the member whose value is currently stored.
e.g:
code.m = 379;
code.x=12.35;
printf(“%d”,code.m);
would produce erroneous output.
A union creates a storage location that can be used by any of its members at a time.
When a different member is assigned a new value, the new value supersedes the
previous member’s value.
Unions may be initialized when the variable is declared. But unlike structures, it can
be initialized only with a value of the same type as the first union member.
e.g:
union item abc = {100} is valid
union item abc = {10.5} is invalid, because the type of the first member is int. other
members can be initialized by either assigning values or reading from the keyboard.
sizeof()
sizeof operator tells the size of a structure or union.
Syntax: sizeof(union x);
Will evaluate the number of bytes required for union x.

Structure Programs

1. Write a c program to create a structure named as Book, initialize structure


members at run time and display structure members.

#include <stdio.h>
#include <stdlib.h>
struct book_bank
{
char author[10];
char title[10];
float price;
int pages;
};
int main(int argc, char *argv[]) {

struct book_bank book1;


printf("\n Enter author:");
scanf("%s",book1.author);
printf("\n Enter title:");
scanf("%s",book1.title);
printf("\n Enter price:");
scanf("%f",&book1.price);
printf("\n Enter pages");
scanf("%d",&book1.pages);*/
printf("\n Structure members are:\n");
printf("Author: %s\n",book1.author);
printf("Title: %s\n",book1.title);
printf("Price: %f\n",book1.price);
printf("Pages: %d\n",book1.pages);
return 0;
}

2. Write a c program to create a structure named as Book, initialize structure


members at compile time and display structure members.

#include <stdio.h>
#include <stdlib.h>

struct book_bank
{
char author[10];
char title[10];
float price;
int pages;
};
int main(int argc, char *argv[]) {

struct book_bank book1={"Balaguruswamy","CProgramming",199.50,300};


printf("\n Structure members are:");
printf("Author: %s\n",book1.author);
printf("Title: %s\n",book1.title);
printf("Price: %f\n",book1.price);
printf("Pages: %d\n",book1.pages);
return 0;
}

3. Write a c program to illustrate copy and comparison of two structures


variables.
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

struct book_bank
{
char author[20];
char title[20];
float price;
int pages;
};
int main(int argc, char *argv[]) {
struct book_bank book1,book2;
printf("\n Enter author:");
scanf("%s",book1.author);
printf("\n Enter title:");
scanf("%s",book1.title);
printf("\n Enter price:");
scanf("%f",&book1.price);
printf("\n Enter pages");
scanf("%d",&book1.pages);
book2=book1;
if(!strcmp(book1.author,book2.author)&& !strcmp(book1.title,book2.title) &&
(book1.price==book2.price) && (book1.pages==book2.pages))
{
printf("\n Book1 and Book2 fileds are same");
}
else
{
printf("\n Book1 and Book2 fileds are not equal");
}

return 0;
}
4. Write a c program to illustrate array of structures

#include <stdio.h>
#include <stdlib.h>

struct student
{
int marks1;
int marks2;
int marks3;
};
int main(int argc, char *argv[]) {

struct student std[3];


int i;
for(i=0;i<3;i++)
{
printf("\n Enter student- %d marks:",i+1);
scanf("%d%d%d",&std[i].marks1,&std[i].marks2,&std[i].marks3);
}
printf("\n Structure members are:");
for(i=0;i<3;i++)
{
printf("\n %d student Marks are:",i+1);
printf("\t%d\t%d\t%d",std[i].marks1,std[i].marks2,std[i].marks3);
}
return 0;
}

5. Write a c program to calculate student total marks, subject’s total marks and
total marks using array of structures.

#include <stdio.h>
#include <stdlib.h>

struct student
{
int sub1;
int sub2;
int sub3;
int total;
};
int main(int argc, char *argv[]) {

struct student std[3];


int sub1_total,sub2_total,sub3_total;
int total_marks;
int i;
for(i=0;i<3;i++)
{
printf("\n Enter student- %d marks:",i+1);
scanf("%d%d%d",&std[i].sub1,&std[i].sub2,&std[i].sub3);
}

sub1_total=0;
sub2_total=0;
sub3_total=0;

for(i=0;i<3;i++)
{
std[i].total = std[i].sub1+std[i].sub2+std[i].sub3;
sub1_total=sub1_total+std[i].sub1;
sub2_total=sub2_total+std[i].sub2;
sub3_total=sub3_total+std[i].sub3;
}
total_marks = sub1_total + sub2_total + sub3_total;

printf("\n Student marks are:");


for(i=0;i<3;i++)
{
printf("\nstudent Marks are =
%d\t%d\t%d",std[i].sub1,std[i].sub2,std[i].sub3);
}
printf("\n Student marks are:");
for(i=0;i<3;i++)
{
printf("\n student[%d] total marks = %d",i+1,std[i].total);
}
printf("\n Subject total marks are:");
printf("\n%d\n%d\n%d",sub1_total,sub2_total,sub3_total);
printf("\n Grand total marks are:");
printf("\n%d",total_marks);
return 0;
}

6. Write a c program to calculate student total marks, subject’s total marks and
total marks using array with in the structures
#include <stdio.h>
#include <stdlib.h>

struct student
{
int sub[3];
int total;
};
int main(int argc, char *argv[]) {

struct student std[3];


int sub1_total,sub2_total,sub3_total;
int total_marks;
int i,j;
for(i=0;i<3;i++)
{
printf("\n Enter student- %d marks:",i+1);
for(j=0;j<3;j++)
{
scanf("%d",&std[i].sub[j]);
}
}
sub1_total=0;
sub2_total=0;
sub3_total=0;

for(i=0;i<3;i++)
{
std[i].total=0;
for(j=0;j<3;j++)
{
std[i].total=std[i].total+std[i].sub[j];
}
sub1_total+= std[i].sub[0];
sub2_total+= std[i].sub[1];
sub3_total+= std[i].sub[2];
}
total_marks = sub1_total + sub2_total + sub3_total;

printf("\n Student marks are:");


for(i=0;i<3;i++)
{
printf("\nstudent- %d Marks are:",i+1);
for(j=0;j<3;j++)
{
printf("\t %d",std[i].sub[j]);
}
printf("\nstudent %d total marks are: %d ",i+1,std[i].total);
}
printf("\n Subject total marks are:");
printf("\n%d\n%d\n%d",sub1_total,sub2_total,sub3_total);
printf("\n Grand total marks are:");
printf("\n%d",total_marks);
return 0;
}

7. Write a c program to calculate total salary of an employee using nested


structure.

#include <stdio.h>
#include <stdlib.h>

struct salary
{
char name[10];
char department[10];
int basicpay;
struct
{
int DA;
int HRA;
int CA;
}allowance;
}employee;

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

struct salary emp;


int total_salary;
printf("\n Enter employee name:");
scanf("%s",emp.name);
printf("\n Enter employee department:");
scanf("%s",emp.department);
printf("\n Enter employee basic pay:");
scanf("%d",&emp.basicpay);
printf("\n Enter DA:");
scanf("%d",&emp.allowance.DA);
printf("\n Enter HRA:");
scanf("%d",&emp.allowance.HRA);
printf("\n Enter City Allowance:");
scanf("%d",&emp.allowance.CA);

total_salary=emp.basicpay+emp.allowance.DA+emp.allowance.HRA+emp.allowanc
e.CA;
printf("\n\n \t Emploee salary is:%d",total_salary);

}
8. Write a c program to pass a student structure to function and display structure
members in the function.

#include <stdio.h>
#include <stdlib.h>

struct student
{
char name[10];
int age;
};
void display(struct student);
int main(int argc, char *argv[]) {
struct student s1;
printf("\n Enter name and age:");
scanf("%s%d",s1.name,&s1.age);
display(s1);
return 0;
}
void display(struct student s2)
{
printf("\n Name = %s\n Age=%d\n",s2.name,s2.age);
}

9. Write a c program to add to complex numbers by passing complex numbers to


functions.

#include <stdio.h>
#include <stdlib.h>

struct complex
{
int real;
int img;
};
void sum(struct complex,struct complex,struct complex*);
int main(int argc, char *argv[]) {
struct complex c1,c2,c3;
printf("\n Enter C1 real part and imaginary part:");
scanf("%d%d",&c1.real,&c1.img);
printf("\n Enter C2 real part and imaginary part:");
scanf("%d%d",&c2.real,&c2.img);
sum(c1,c2,&c3);
printf("\n result = %d+i%d",c3.real,c3.img);
return 0;
}
void sum(struct complex c4,struct complex c5,struct complex *c6)
{
c6->real=c4.real+c5.real;
c6->img = c4.img + c5.img;
}

10. Write a c program to illustrate union.

#include <stdio.h>
#include <stdlib.h>

union number
{
int n1;
float n2;
};
int main(int argc, char *argv[]) {
union number x;

printf("Enter the value of n1: ");


scanf("%d", &x.n1);
printf("Value of n1 = %d", x.n1);
printf("\nEnter the value of n2: ");
scanf("%f", &x.n2);
printf("Value of n2 = %f\n", x.n2);
printf("\n sizeof union = %d",sizeof(x));
return 0;
}
List of Programs:

Programs

1. Write a c program to find factorial of a given number using functions with no


arguments and no return type.
#include <stdio.h>
#include <stdlib.h>

void fact();
int main(int argc, char *argv[]) {

fact();

return 0;
}
void fact()
{
int i,f=1,n;
printf("\n Enter a number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n fact(%d)=%d",n,f);
}
2. Write a c program to find factorial of a given number using functions with arguments
and no return type.
#include <stdio.h>
#include <stdlib.h>

void fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter two numbers:");
scanf("%d",&n);
fact(n);

return 0;
}
void fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n fact(%d)=%d",n,f);
}
3. Write a c program to find factorial of a given number using functions with no
arguments and return type.
#include <stdio.h>
#include <stdlib.h>

int fact();
int main(int argc, char *argv[]) {

int f;
f=fact();
printf("\n fact=%d",f);
return 0;
}
int fact()
{
int i,f=1,n;
printf("\n Enter a number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
4. Write a c program to find factorial of a given number using functions with arguments
and return type.
#include <stdio.h>
#include <stdlib.h>

int fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter two numbers:");
scanf("%d",&n);
f=fact(n);
printf("\n fact(%d)=%d",n,f);
return 0;
}
int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
5. Write a c program to sort array elements using functions.
#include <stdio.h>
#include <stdlib.h>

void sort(int[],int);
int main(int argc, char *argv[]) {
int a[10],n,i;
printf("\n Enter array lenth:");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Before sorting array elements are:");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
sort(a,n);
printf("\n After sorting array elements are:");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
return 0;
}
void sort(int a[],int n)
{
int i,j,temp;
for(i=1;i<n;i++)
{
for(j=0;j<=(n-i-1);j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
6. Write a c program to check whether given number is prime number or not using
functions.
#include <stdio.h>
#include <stdlib.h>

int prime(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=prime(n);
if(f==2)
{
printf("\n %d is a prime number",n);
}
else
{
printf("\n %d is not a prime number",n);
}
return 0;
}

int prime(int n)
{
int i,count=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
{
count++;
}
}
return count;
}
7. Write a c program to check whether the given number is a palindrome or not.
#include <stdio.h>
#include <stdlib.h>
int palindrome(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a value:");
scanf("%d",&n);
f=palindrome(n);
if(f==1)
{
printf("\n %d is a palindrome",n);
}
else
{
printf("\n %d is not a palindrome",n);
}
return 0;
}
int palindrome(int n)
{
int rev,rem,temp;
temp=n;
while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
if(rev==temp)
{
return 1;
}
else
{
return 0;
}
}
8. Write a c program to swap two integers using call by value.
#include <stdio.h>
#include <stdlib.h>

void swap(int,int);
int main(int argc, char *argv[]) {
int a,b;
printf("\n Enter two values:");
scanf("%d%d",&a,&b);
printf("\n Before swapping a=%d b=%d\n",a,b);
swap(a,b);
return 0;
}
void swap(int m,int n)
{
int temp;
temp=m;
m=n;
n=temp;
printf("\n After swapping a=%d b=%d\n",m,n);
}
9. Write a c program to swap two integers using call by reference.
#include <stdio.h>
#include <stdlib.h>

void swap(int*,int*);
int main(int argc, char *argv[]) {
int a,b;
printf("\n Enter two values:");
scanf("%d%d",&a,&b);
printf("\n Before swapping a=%d b=%d\n",a,b);
swap(&a,&b);
printf("\n After swapping a=%d b=%d\n",a,b);
return 0;
}
void swap(int *m,int *n)
{
int temp;
temp=*m;
*m=*n;
*n=temp;
}
10. Write a c program to find largest value from the given array elements using passing
array to the function.
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause")
or input loop */
void largest(int[],int);
int main(int argc, char *argv[]) {
int a[10],n,b,i;
printf("\n Enter array length:");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
largest(a,n);
return 0;
}
void largest(int a[],int n)
{
int i,max;
max=a[0];
for(i=1;i<n;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
printf("\n largest number = %d",max);
}
11. Write a c program to implement Fibonacci series using functions.
#include <stdio.h>
#include <stdlib.h>

int fib(int);
int main(int argc, char *argv[]) {
int n,f,i;
printf("\n Enter a value:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
f=fib(i);
printf("\n %d",f);
}
return 0;
}
int fib(int n)
{
int i,f0,f1,f2;
if(n==0||n==1)
{
return n;
}
else
{
f0=0;
f1=1;
for(i=2;i<=n;i++)
{
f2=f0+f1;
f0=f1;
f1=f2;
}
return f2;
}
}
12. Write a c program to find sum of matrix elements using functions.
#include <stdio.h>
#include <stdlib.h>

void addition(int[][3],int[][3],int[][3],int,int);
int main(int argc, char *argv[]) {
int a[3][3],b[3][3],c[3][3],i,j;
printf("\n Enter Matrix-A elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}

printf("\n Enter Matrix-B elements:");


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}

addition(a,b,c,3,3);
printf("\n Matrix-C elements are:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t%4d",c[i][j]);
}
printf("\n");
}
return 0;

void addition(int a[3][3],int b[3][3],int c[3][3],int m,int n)


{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
}
13. Write a c program to implement matrix multiplication using functions.
#include <stdio.h>
#include <stdlib.h>

void multiply(int[][3],int[][3],int[][3],int,int);
int main(int argc, char *argv[]) {
int a[3][3],b[3][3],c[3][3],n,i,j;
printf("\n Enter Matrix-A elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}

printf("\n Enter Matrix-B elements:");


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}

multiply(a,b,c,3,3);
printf("\n Enter Matrix-C elements:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t%4d",c[i][j]);
}
printf("\n");
}
return 0;
}

void multiply(int a[3][3],int b[3][3],int c[3][3],int m,int n)


{
int i,j,k;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
for(c[i][j]=0,k=0;k<m;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
}
14. Write a c program to find the length of a string using functions.
#include <stdio.h>
#include <stdlib.h>

int stringlength(char[]);
int main(int argc, char *argv[]) {
char str[10];
int l;
printf("\n Enter a string:");
gets(str);
l=stringlength(str);
printf("\n string length = %d\n",l);

return 0;
}
int stringlength(char str[])
{
int i;
for(i=0;str[i]!='\0';i++);
return i;
}
15. Write a c program to sort city names using functions.
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

void sort_citynames(char[][10],int n);


int main(int argc, char *argv[]) {
char str[10][10];
int n,i;
printf("\n Enter number of cities:");
scanf("%d",&n);
printf("\n Enter city names:");
for(i=0;i<n;i++)
{
scanf("%s",str[i]);
}
sort_citynames(str,n);
printf("\n After sorting city names are:");
for(i=0;i<n;i++)
{
printf("\n %s",str[i]);
}
return 0;
}

void sort_citynames(char str[][10],int n)


{
int i,j;
char temp[10];

for(i=0;i<n-1;i++)
{
for(j=0;j<(n-i-1);j++)
{
if(strcmp(str[j],str[j+1])>0)
{
strcpy(temp,str[j]);
strcpy(str[j],str[j+1]);
strcpy(str[j+1],temp);
}

}
}

}
16. Write a c program to find Fibonacci series using recursion.
#include <stdio.h>
#include <stdlib.h>

int fib(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=fib(n);
printf("\n fib(%d)=%d",n,f);
return 0;
}
int fib(int n)
{
if(n==0||n==1)
{
return n;
}
else
{
return fib(n-1)+fib(n-2);
}
}
17. Write a c program to find factorial of a given number using recursion.
#include <stdio.h>
#include <stdlib.h>

int fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=fact(n);
printf("\n fact(%d)=%d",n,f);
return 0;
}
int fact(int n)
{
if(n==0||n==1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
18. Write a c program to find addition of the two numbers using recursion.
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause")
or input loop */
int addition(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);
f=addition(m,n);
printf("\n add(%d,%d)=%d",m,n,f);
return 0;
}
int addition(int m,int n)
{
if(n==0)
{
return m;
}
else
{
return addition(m,n-1)+1;
}
}
19. Write a c program to find multiplication of two numbers using recursion.
#include <stdio.h>
#include <stdlib.h>

int multiply(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);
f=multiply(m,n);
printf("\n mul(%d,%d)=%d",m,n,f);
return 0;
}
int multiply(int m,int n)
{
if(n==0)
{
return m;
}
else
{
return multiply(m,n-1)+n;
}
}
20. Write a c program to implement binary search using recursion.
#include <stdio.h>
#include <stdlib.h>

void binarysearch(int[],int,int,int);
int main(int argc, char *argv[]) {
int a[10],n,i,key;
printf("\n Enter array length:");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter key:");
scanf("%d",&key);
binarysearch(a,0,n-1,key);
return 0;
}
void binarysearch(int a[],int l,int h,int k)
{
int mid;
if(l<=h)
{
mid=(l+h)/2;
if(a[mid]==k)
{
printf("\n Search is successful");
}
else if(k < a[mid])
{
binarysearch(a,l,mid-1,k);
}
else
{
binarysearch(a,mid+1,h,k);
}

}
else
{
printf("\n Search is unsuccessful");
}
}
21. Write a c program to find GCD of two numbers using recursion.
#include <stdio.h>
#include <stdlib.h>

int gcd(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);
f=gcd(m,n);
printf("\n gcd(%d,%d)=%d",m,n,f);
return 0;
}
int gcd(int m,int n)
{
if(n==0)
{
return m;
}
else
{
return gcd(n,m%n);
}
}
22. Write a c program to implement Ackermann function using recursion.
#include <stdio.h>
#include <stdlib.h>

int ack(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);
f=ack(m,n);
printf("\n ack(%d,%d)=%d",m,n,f);
return 0;
}
int ack(int m,int n)
{
if(m==0)
{
return n+1;
}
else if((m>0)&&(n==0))
{
return ack(m-1,1);
}
else
{
return ack(m-1,ack(m,n-1));
}
}
23. Write a c program to create a structure named as Book, initialize structure members at
run time and display structure members.
#include <stdio.h>
#include <stdlib.h>

struct book_bank
{
char author[10];
char title[10];
float price;
int pages;
};
int main(int argc, char *argv[]) {
struct book_bank book1;
printf("\n Enter author:");
scanf("%s",book1.author);
printf("\n Enter title:");
scanf("%s",book1.title);
printf("\n Enter price:");
scanf("%f",&book1.price);
printf("\n Enter pages");
scanf("%d",&book1.pages);*/
printf("\n Structure members are:\n");
printf("Author: %s\n",book1.author);
printf("Title: %s\n",book1.title);
printf("Price: %f\n",book1.price);
printf("Pages: %d\n",book1.pages);
return 0;
}
24. Write a c program to create a structure named as Book, initialize structure members at
compile time and display structure members.
#include <stdio.h>
#include <stdlib.h>

struct book_bank
{
char author[10];
char title[10];
float price;
int pages;
};
int main(int argc, char *argv[]) {
struct book_bank book1={"Balaguruswamy","CProgramming",199.50,300
};
printf("\n Structure members are:");
printf("Author: %s\n",book1.author);
printf("Title: %s\n",book1.title);
printf("Price: %f\n",book1.price);
printf("Pages: %d\n",book1.pages);
return 0;
}
25. Write a c program to illustrate copy and comparison of two structures variables.
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

struct book_bank
{
char author[20];
char title[20];
float price;
int pages;
};
int main(int argc, char *argv[]) {
struct book_bank book1,book2;
printf("\n Enter author:");
scanf("%s",book1.author);
printf("\n Enter title:");
scanf("%s",book1.title);
printf("\n Enter price:");
scanf("%f",&book1.price);
printf("\n Enter pages");
scanf("%d",&book1.pages);
book2=book1;
if(!strcmp(book1.author,book2.author)&&
!strcmp(book1.title,book2.title)&&(book1.price==book2.price)&&(book1.pages==bo
ok2.pages))
{
printf("\n Book1 and Book2 fileds are same");
}
else
{
printf("\n Book1 and Book2 fileds are not equal");
}

return 0;
}
26. Write a c program to illustrate array of structures
#include <stdio.h>
#include <stdlib.h>

struct student
{
int marks1;
int marks2;
int marks3;
};
int main(int argc, char *argv[]) {
struct student std[3];
int i;
for(i=0;i<3;i++)
{
printf("\n Enter student- %d marks:",i+1);
scanf("%d%d%d",&std[i].marks1,&std[i].marks2,&std[i].marks3);
}
printf("\n Structure members are:");
for(i=0;i<3;i++)
{
printf("\n %d student Marks are:",i+1);
printf("\t%d\t%d\t%d",std[i].marks1,std[i].marks2,std[i].marks3);
}
return 0;
}
27. Write a c program to calculate student total marks, subject’s total marks and total
marks using array of structures.
#include <stdio.h>
#include <stdlib.h>

struct student
{
int sub1;
int sub2;
int sub3;
int total;
};
int main(int argc, char *argv[]) {
struct student std[3];
int sub1_total,sub2_total,sub3_total;
int total_marks;
int i;
for(i=0;i<3;i++)
{
printf("\n Enter student- %d marks:",i+1);
scanf("%d%d%d",&std[i].sub1,&std[i].sub2,&std[i].sub3);
}

sub1_total=0;
sub2_total=0;
sub3_total=0;

for(i=0;i<3;i++)
{
std[i].total = std[i].sub1+std[i].sub2+std[i].sub3;
sub1_total=sub1_total+std[i].sub1;
sub2_total=sub2_total+std[i].sub2;
sub3_total=sub3_total+std[i].sub3;
}
total_marks = sub1_total + sub2_total + sub3_total;

printf("\n Student marks are:");


for(i=0;i<3;i++)
{
printf("\nstudent Marks are =
%d\t%d\t%d",std[i].sub1,std[i].sub2,std[i].sub3);
}
printf("\n Student marks are:");
for(i=0;i<3;i++)
{
printf("\n student[%d] total marks = %d",i+1,std[i].total);
}
printf("\n Subject total marks are:");
printf("\n%d\n%d\n%d",sub1_total,sub2_total,sub3_total);
printf("\n Grand total marks are:");
printf("\n%d",total_marks);
return 0;
}

28. Write a c program to calculate student total marks, subject’s total marks and total
marks using array with in the structures
#include <stdio.h>
#include <stdlib.h>

struct student
{
int sub[3];
int total;
};
int main(int argc, char *argv[]) {
struct student std[3];
int sub1_total,sub2_total,sub3_total;
int total_marks;
int i,j;
for(i=0;i<3;i++)
{
printf("\n Enter student- %d marks:",i+1);
for(j=0;j<3;j++)
{
scanf("%d",&std[i].sub[j]);
}
}
sub1_total=0;
sub2_total=0;
sub3_total=0;
for(i=0;i<3;i++)
{
std[i].total=0;
for(j=0;j<3;j++)
{
std[i].total=std[i].total+std[i].sub[j];
}
sub1_total+= std[i].sub[0];
sub2_total+= std[i].sub[1];
sub3_total+= std[i].sub[2];
}
total_marks = sub1_total + sub2_total + sub3_total;

printf("\n Student marks are:");


for(i=0;i<3;i++)
{
printf("\nstudent- %d Marks are:",i+1);
for(j=0;j<3;j++)
{
printf("\t %d",std[i].sub[j]);
}
printf("\nstudent %d total marks are: %d ",i+1,std[i].total);
}

printf("\n Subject total marks are:");


printf("\n%d\n%d\n%d",sub1_total,sub2_total,sub3_total);
printf("\n Grand total marks are:");
printf("\n%d",total_marks);
return 0;
}
29. Write a c program to calculate total salary of an employee using nested structure.
#include <stdio.h>
#include <stdlib.h>

struct salary
{
char name[10];
char department[10];
int basicpay;
struct
{
int DA;
int HRA;
int CA;
}allowance;
}employee;

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


struct salary emp;
int total_salary;
printf("\n Enter employee name:");
scanf("%s",emp.name);
printf("\n Enter employee department:");
scanf("%s",emp.department);
printf("\n Enter employee basic pay:");
scanf("%d",&emp.basicpay);
printf("\n Enter DA:");
scanf("%d",&emp.allowance.DA);
printf("\n Enter HRA:");
scanf("%d",&emp.allowance.HRA);
printf("\n Enter City Allowance:");
scanf("%d",&emp.allowance.CA);

total_salary=emp.basicpay+emp.allowance.DA+emp.allowance.HRA+emp.allowance.
CA;
printf("\n\n \t Emploee salary is:%d",total_salary);

}
30. Write a c program to pass a student structure to function and display structure
members in the function.
#include <stdio.h>
#include <stdlib.h>

struct student
{
char name[10];
int age;
};
void display(struct student);
int main(int argc, char *argv[]) {
struct student s1;
printf("\n Enter name and age:");
scanf("%s%d",s1.name,&s1.age);
display(s1);
return 0;
}
void display(struct student s2)
{
printf("\n Name = %s\n Age=%d\n",s2.name,s2.age);
}

31. Write a c program to add to complex numbers by passing complex numbers to


functions.
#include <stdio.h>
#include <stdlib.h>

struct complex
{
int real;
int img;
};
void sum(struct complex,struct complex,struct complex*);
int main(int argc, char *argv[]) {
struct complex c1,c2,c3;
printf("\n Enter C1 real part and imaginary part:");
scanf("%d%d",&c1.real,&c1.img);
printf("\n Enter C2 real part and imaginary part:");
scanf("%d%d",&c2.real,&c2.img);
sum(c1,c2,&c3);
printf("\n result = %d+i%d",c3.real,c3.img);
return 0;
}
void sum(struct complex c4,struct complex c5,struct complex *c6)
{
c6->real=c4.real+c5.real;
c6->img = c4.img + c5.img;
}

32. Write a c program to illustrate union.


#include <stdio.h>
#include <stdlib.h>

union number
{
int n1;
float n2;
};
int main(int argc, char *argv[]) {
union number x;

printf("Enter the value of n1: ");


scanf("%d", &x.n1);
printf("Value of n1 = %d", x.n1);
printf("\nEnter the value of n2: ");
scanf("%f", &x.n2);
printf("Value of n2 = %f\n", x.n2);
printf("\n sizeof union = %d",sizeof(x));
return 0;
}
33. Write a c program to illustrates typedef
#include <stdio.h>
#include <stdlib.h>

struct student
{
char name[10];
int age;
};

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


typedef struct student s;
s s1;
printf("\n Enter name and age:");
scanf("%s%d",s1.name,&s1.age);
printf("\n Name = %s\n Age=%d\n",s1.name,s1.age);
return 0;
}
34. Write a c program to illustrates bitfields
#include<stdio.h>
#include<conio.h>
void main()
{
struct person
{
unsigned gender : 1;
unsigned age : 7;
unsigned m_status : 1;
unsigned children : 3;
unsigned : 4;
}emp = { 1, 30,1,5};
printf("\n gender value = %d\n",emp.gender);
printf("\n age = %d\n",emp.age);
printf("\n m_status = %d",emp.m_status);
printf("\n children = %d",emp.children);
}
35. Write a c program to read and display array elements using pointers.
36. Write a c program to find sum of array elements using pointers.
37. Write a c program to find largest value from array elements using pointers
38. Write a c program to find smallest value from array elements using pointers
39. Write a c program to sort array elements using pointers
40. Write a c program to find matrix multiplication using pointers.
41. Write a c program to find matrix addition using pointers.
42. Write a c program to find trace of a matrix using pointers.
43. Write a c program to find string length using pointers.
44. Write a c program to concatenate two stings using pointers.
45. Write a c program to sort city names using pointers.
46. Write a c program to find largest of two numbers using function returns a pointer.
47. Write a c program to illustrate pointer to a function.
48. Write a c program to illustrate pointers and structures.
UNIT- 5 File

Console I/O – it uses scanf() and printf() to read and write data. These functions always use
terminal (keyboard and screen) as the target place.

Advantages: It works better as long as the data is small

Drawbacks

1. It becomes cumbersome and time consuming to handle large volume of data through terminal.

2. The entire data is lost when either the program is terminated or the computer is turned off.

To overcome the above drawbacks we use files.

File – a file is a place on the disk where a group of related data is stored.

Types of Files:

There are two types of files, they are 1. Text files 2. Binary files

1. Text file:

 Text file stores information in the form of alphabets, numbers, special symbols etc…
 It requires conversion from text to binary format
 This format is human understandable
 C source files are text files

2. Binary File:

 Binary file stores information in the binary form.


 It doesn’t require conversion from text to binary format
 This format is machine understandable
 Every executable file generated by the C compiler is a binary file

File Operations

 Naming a file
 Opening a file
 Reading data from a file
 Writing data to a file
 Closing a file

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


Defining and Opening a file:

If we want to store data in a file in the secondary memory we must specify three things to the
operating system. They are

 File name
 Data structure
 Purpose

File name is a sequence of characters that make up a valid filename. It may contain two parts, a
primary name and an optional period with file extension.

Data structure of a file is defined as FILE, therefore all files should be declared as type FILE
before they are used.

For what purpose we open a file, whether the file is open for reading, writing or appending.

Syntax for declaring and opening a file

FILE *fp;
fp = fopen (“filename”,”mode”);

In the first statement fp as a “pointer to the data type FILE”, the second statement opens a file
named filename and assigns an identifier to the FILE type pointer fp.

Opening a file in one of the three modes. They are

1. r - open the file for reading only


2. w – open the file for writing only
3. a - open the file for appending (adding) data to it.

1. When the mode is “writing”


 A file with the specified name is created, if the file doesn’t exist
 The file contents are deleted, if the file already exist.
2. When the mode is “reading”
 If the file exist then it is opened and current contents safe
 If the file doesn’t exist it returns NULL
3. When the mode is “appending”
 If the file exists then it is opened with current contents safe.
 If the file doesn’t exist then a file with the specified name is created.

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


Recent compilers include additional modes of operations.
 r+ -- If the file doesn’t exist it return NULL otherwise the file is opened to the
beginning for both reading and writing
 w+ -- If the file already exist then it erases the previous contents and open the file
for reading and writing. If the file doesn’t exist then it creates a new file for
writing.
 a+ -- same as a except both for reading and writing

CLOSING A FILE
A file must be closed after all operations have been completed.
Syntax:
fclose(file_pointer);

This would close the file associated with the FILE pointer file_pointer.

INPUT-OUTPUT OPERATIONS ON FILES

getc() and putc() functions


getc()
 it is used to read a character from a file.
 The file must be opened in read in mode.
 Syntax

c= getc(fp1);
Read a character from the file whose file pointer is fp1 and store the character in c.
Putc():
 It is used to write a character to a file.
 The file must be opened in write mode.
 Syntax
Putc(c,fp1);
Write the character contained in the character variable c to the file associated with FILE
pointer fp1.c and putc
Note:
1. The file pointer moves by one character position for every operation of getc and putc
2. getc will return and end-of-file marker EOF when end of the file has been reached.

1. Write a c program to write data to the input file after that read input file contents and
display on the screen.
#include <stdio.h>
#include <stdlib.h>

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


FILE *fp;
char c;
fp=fopen("inputfile.txt","w");

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


while((c=getchar())!= EOF)
{
putc(c,fp);
}
fclose(fp);
fp=fopen("inputfile.txt","r");
while((c=getc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
return 0;
}

2. Write a c program to write characters to the input file, then read input file contents and
check if it is vowel then store it in VOWEL file, or it is a consonant then store it in
CONSONANT file. Display VOWEL files contents and CONSONANTS file contents.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

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


FILE *fp,*fp1,*fp2;
char c;
fp=fopen("inputfile.txt","w");
while((c=getchar())!= EOF)
{
putc(c,fp);
}
fclose(fp);
fp=fopen("inputfile.txt","r");
fp1=fopen("vowel.txt","w");
fp2=fopen("consonant.txt","w");

while((c=getc(fp))!=EOF)
{
if(isalpha(c))
{

if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U')
{
putc(c,fp1);
}
else
{
putc(c,fp2);

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


}
}
}
fclose(fp);
fclose(fp1);
fclose(fp2);

fp1=fopen("vowel.txt","r");
printf("\n Vowe file contents are:");
while((c=getc(fp1))!=EOF)
{
printf("%c",c);
}
fclose(fp1);

fp2=fopen("consonant.txt","r");
printf("\n Consonant file contents are:");
while((c=getc(fp2))!=EOF)
{
printf("%c",c);
}
fclose(fp2);
return 0;
}

getw():
 It is used to read an integer from a file.
 The file must be opened in read mode.
 Syntax
c= getw(fp);

putw():
 It is used to write an integer to a file.
 The file must be opened in write mode.
 Syntax
putw(c,fp);

The variable c contains an integer that value writes into a file pointed by a file pointer fp.

3. Write a c program to write integers to NUMBER file. Read an integer value from
NUMBER file and display integers on the screen.
#include <stdio.h>
#include <stdlib.h>

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


int main(int argc, char *argv[]) {
FILE *fp;
int n;
fp=fopen("number.txt","w");
while(1)
{
printf("\n Enter a number:");
scanf("%d",&n);
if(n<0)
{
break;
}
else
{
putw(n,fp);
}
}
fclose(fp);

fp=fopen("number.txt","r");

while((n=getw(fp))!=EOF)
{
printf("\n%d",n);
}
fclose(fp);
return 0;
}

4. Write a c program to write integers to the NUMBER file. Read numbers from the
NUMBER file check that number if it is even then stores it in EVEN file otherwise store
it in ODD file. Display EVEN file contents and ODD file contents on the screen.

#include <stdio.h>
#include <stdlib.h>

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


FILE *fp,*fp1,*fp2;
int n;
fp=fopen("number.txt","w");
while(1)
{
printf("\n Enter a number:");
scanf("%d",&n);
if(n<0)

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


{
break;
}
else
{
putw(n,fp);
}
}
fclose(fp);

fp=fopen("number.txt ","r");
fp1=fopen("even.txt","w");
fp2=fopen("odd.txt","w");

while((n=getw(fp))!=EOF)
{
if(n%2==0)
{
putw(n,fp1);
}
else
{
putw(n,fp2);
}
}
fclose(fp);
fclose(fp1);
fclose(fp2);

fp1=fopen("even.txt","r");
printf("\n Even file contents are:");
while((n=getw(fp1))!=EOF)
{
printf("\n%d",n);
}
fclose(fp1);
fp2=fopen("odd.txt","r");
printf("\n Odd file contents are:");
while((n=getw(fp2))!=EOF)
{
printf("\n%d",n);
}
fclose(fp2);
return 0;
}

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


fscanf():
 It is used to read mixed data from the file
 Syntax
fscanf ( fp, ”control string”, list);

The above statement will read the items in the list from the file specified by fp.
fprintf()
 It is used to write the list of items into a file
 Syntax
fprintf(fp, ”control string “, list);
The above statement would write the items in the list into a file specified by fp.

1. Write a c program to open a file named inventory and store it in following data.
Item name item number price quantity
Aaa 111 10 2
Bbb 222 15 3
Ccc 333 12 5

Extend the program to read this data from the file inventory and display the table with
values of each item.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

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


FILE *fp;
char name[10];
int number,quantity,i,value;
float price,values;

fp=fopen("inventory.txt","w");
i=1;
while(i<=3)
{
printf("\n Enter item name:");
scanf("%s",name);
printf("\n Enter item number:");
scanf("%d",&number);
printf("\n Enter price:");
scanf("%f",&price);
printf("\n Enter quantity:");

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


scanf("%d",&quantity);
fprintf(fp,"\n %s %d %f %d",name,number,price,quantity);
i++;
}
fclose(fp);
fp=fopen("inventory.txt","r");
i=1;
printf("\n Name\t Number\t Price\t Quantity\t Value\n");
while(i<=3)
{
fscanf(fp,"\n %s %d %f %d",name,&number,&price,&quantity);
values=price*quantity;
printf("\n %s\t %d\t %f\t %d\t %f",name,number,price,quantity,values);
i++;
}
fclose(fp);
return 0;
}

Error Handling During I/O Operations:


Errors may occur during the following situations.
1. Trying to read the file beyond the end-of-file mark.
2. Device overflow.
3. Trying to use a file when the file has not been opened.
4. Trying to perform operation on a file, when the file has been opened for another
operation.
5. Opening a file with an invalid filename.
6. Attempting to write to a write protected file.

C provides two library functions to provide file status information. They are feof() and ferror()

1. feof( ): it takes file pointer as the argument and return a nonzero integer if all of the data
from the specified file has been read and returns zero otherwise.
Syntax:
if(feof(fp))
{
Printf(“End-of-data\n”);
}
would display the message “End-of-data” on reaching the end of file condition.

2. ferror( ): It takes the file pointer as an argument and returns a nonzero integer if an error has
been detected up to that point during processing. It returns zero otherwise.
if(ferror(fp) != 0)
printf(“An error has occurred \n”);

3. Clearerr( ) – clears the EOF and error indicator for the given stream.

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


C Program to illustrate fclearerr()

#include<stdio.h>
#include<conio.h>

void main()
{
FILE *fp;
char c;

clrscr();
fp=fopen("ece2.txt","w");

c=getc(fp);
if(ferror(fp))
{
printf("\n error in reading file \n");
}
clearerr(fp);

if(ferror(fp))
{
printf("error in reading from file : file.txt\n");
}
fclose(fp);
}

Random Access Files:


To access any part of the file we use ftell, fseek and rewind functions.
1. ftell( ): It takes file pointer as an argument and returns number that represents the current
position of the file pointer.
Syntax:
n= ftell(fp);
n would give the relative offset of the current position.

2. rewind( ): takes file pointer as an argument and resets the position to the start of the file.
rewind(fp);
n=ftell(fp);
would assign 0 to the n because the file position has been set to the start of the file by rewind.

3. fseek( ): It is used to move the file position to the desired position in the file.
Syntax:

fseek(file_poinger, offset, Position);


file_pointer is a file pointer, offset is a number and position is an integer number.

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


Offset species the number of positions to be moved from the location specified by the position.
Position can take one of the following three values.

Value Meaning
0 Beginning of the file
1 Current position
2 End of file

The offset may be positive meaning move forwards, or negative meaning move backwards.
Statement Meaning
fseek(fp,0L,0) go to the beginning
fseek(fp,0L,1) stay at the current position
fseek(fp,0L,2) go to the end of the file, past the last character of the file
fseek(fp,m,0) move to the (m+1)th byte in the file
fseek(fp,m,1) go forward by m bytes
fseek(fp,-m,1) go backward by m bytes from the current position
fseek(fp,-m,2) go backward by m bytes from the end

Write a C program to print file contents in reverse order.

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
int i,n;
clrscr();

fp=fopen("xyz.txt","w");

while((ch=getchar())!=EOF)
{
putc(ch,fp);
}
fclose(fp);

fp=fopen("xyz.txt","r");

fseek(fp,0L,2);
n=ftell(fp);
printf("\n No of characters are = %d\n",n);
for(i=n;i>=0;i--)
{
fseek(fp,i,0);
ch=getc(fp);

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


printf("%c",ch);
}
fclose(fp);
}

Write a c program to print 6th and 8th character in the file.

#include <stdio.h>
#include <stdlib.h>

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

FILE *fp;
char ch;
int i,n;

fp=fopen("xyz.txt","w");

while((ch=getchar())!=EOF)
{
putc(ch,fp);
}
fclose(fp);

fp=fopen("xyz.txt","r");

fseek(fp,6L,0);
ch=getc(fp);
printf("\n 6th character is = %c\n",ch);
fseek(fp,8L,0);
ch=getc(fp);
printf("\n 8th character is = %c\n",ch);

fclose(fp);

return 0;
}

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


Binary files
Binary files are very similar to arrays of structures, except the structures are in a disk-file rather
than an array in memory.
Binary files have two features that distinguish them from text files:
 We can instantly use any structure in the file.
 We can change the contents of a structure anywhere in the file.
After we have opened the binary file, we can read and write a structure or seek a specific
position in the file. A file position indicator points to record 0 when the file is opened.

A read operation reads the structure where the file position indicator is pointing to. After
reading the structure the pointer is moved to point at the next structure.

A write operation will write to the currently pointed-to structure. After the write operation the
file position indicator is moved to point at the next structure.

The fread and fwrite function takes four parameters:

 A memory address
 Number of bytes to read per block
 Number of blocks to read
 A file variable

fread(&my_record,sizeof(struct rec),1,file_pointer);

This fread statement says to read x bytes (size of rec) from the file file_pointer into memory
address &my_record. Only one block is requested. Changing the one into ten will read in ten
blocks of x bytes at once.

fwrite(&my_record,sizeof(struct rec),1,file_pointer)

This fwrite statement says to write x bytes (size of rec) from the my record into the file
pointed by the file pointer.

Write a C program to write data from the file using binary file concept
#include<stdio.h>
#include<conio.h>
struct rec
{
int x,y,z;
};
void main()
{
struct rec a;

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


FILE *f;
int i;
clrscr();
f=fopen("xyz","rb");
if(!f)
{ printf("\n File was not opened\n");
exit(0);
}
for(i=1;i<=3;i++)
{
fread(&a,sizeof(a),1,f);
printf(" \n %d record contents\n",i);
printf("%d\t%d\t%d\n",a.x,a.y,a.z);
printf("\n\n\n\n");
}
fclose(f);
}

Write a C program to write data to the file using binary file


#include<stdio.h>
#include<conio.h>
struct rec
{
int x,y,z;
};
void main()
{
struct rec a;
FILE *f;
int i;
clrscr();
f=fopen("xyz","wb");
if(!f)
{
printf("\n File was not opened\n");
exit(0);
}
for(i=1;i<=3;i++)
{
a.x=i;
a.y=i+1;
a.z=i+2;
fwrite(&a,sizeof(a),1,f);
}
fclose(f);
}

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


Command Line Arguments:
It is a parameter supplied to a program when a program is invoked. The parameter may represent
a filename the program should process.
If we want to execute a program to copy the contents of a file named X_FILE to another one
named Y_FILE, then we may use a command line like

C:\>PROGRAM X_FILE Y_FILE

Where PROGRAM is the filename where the executable code of the program is stored. This
eliminates the need for the program to request the user to enter the filenames during execution.

Main takes two arguments called argc and argv and the information contained in the command
line is passed on to the program through these arguments, when main is called up by the system.

argc: it counts the number of arguments on the command line.


argv: it is an argument vector and represents an array of character pointers that point to the
command line arguments.

e.g: argc value is three


argv[0] à PROGRAM
argv[1] à X_FILE
argv[2] à Y_FILE
In order to access the command line arguments, we must declare the main function and its
parameters as follows.
main(int argc, char *argv[])
{
…………..
…………..
…………..

Command Line Arguments programs

1. Write a C program to add two numbers using command line arguments.


#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or
input loop */

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


int a,b,c;
a=atoi(argv[1]);
b=atoi(argv[2]);
c=a+b;

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


printf("\n Sum = %d",c);
return 0;
}
2. Write a C program to find factorial of a given number using command line arguments.
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or
input loop */

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


int fact=1,i,n;
n=atoi(argv[1]);
for(i=1;i<=n;i++)
{
fact = fact*i;
}
printf("\n Fact = %d",fact);
return 0;
}
3. Write a C program to find string length using command line arguments.
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or
input loop */

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


int i;
printf("\n str= %s",argv[1]);
for(i=0;argv[1][i]!='\0';i++);
printf("\n string length = %d",i);
return 0;
}

4. Write a C program to copy one file contents into another file using command line
arguments.
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or
input loop */

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


FILE *fp1,*fp2;
char c;

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


fp1=fopen(argv[1],"r");
fp2=fopen(argv[2],"w");

while((c=getc(fp1))!=EOF)
{
putc(c,fp2);
}
fclose(fp1);
fclose(fp2);

fp2=fopen(argv[2],"r");
printf("\n %s file contents are \n",argv[2]);
while((c=getc(fp2))!=EOF)
{
printf("%c",c);
}
fclose(fp2);
return 0;
}

G. NAGARAJU, Assistant Professor, Department of CSE(AIML & IoT), VNRVJIET, Hyderabad


Important Questions
UNIT-3
Short answer questions
1. Define functions?
2. What are the advantages of functions?
3. Define recursion?
4. What are the formal arguments and actual arguments?
5. write the syntax for function definition?
6. Write differences between library functions and user defined functions?
7. What are differences between local and global variables?
8. What is call by value?
Long answer questions:
1. What is call by value and call by reference? Explain with suitable examples?
2. Differentiate between call by value and call by reference?
3. Explain categories of functions with examples?
4. Write a c program to find factorial/ GCD/ Factorial/ Akerman / Fibonacci series using
recursion?
5. Write a c program to find sum of array elements by passing array to the function?
6. Write a c program to perform matrix multiplication using functions.
7. Write a C program to perform bubble sort using functions.
UNIT- 4
Short answer questions
1. Define structure?
2. Differentiate between structure and union? (Most important)
3. Differentiate between array and structure? (Most important)
4. Discuss importance of structure tag?
5. What is nested structure? Give example.
6. What is array of structure? Give example.
7. What is array within the structure? Give example.
8. How to access structure members
9. Define union?
10. Define pointer?
11. Explain the advantages of pointers.
12. Give syntax for malloc, calloc, realloc and free functions?
13. Define self referential structure?
14. Explain pointer arithmetic?
15. Give syntax for pointer to a function?
Long answer questions:
1. Explain array within the structure with example? (Explain with program)
2. Explain array of structure with suitable example? (Explain with program)
3. Explain nested structure with example? (Explain with program)
4. How many ways can we pass a structure to the function among which is the best
method?
5. Explain dynamic memory allocation techniques? (Most important)
6. Write a c program related to pointers to arrays?
7. Write a c program related to pointer to strings?
8. Write a c program related to pointer to array of strings?
9. Write a c program related to pointer to structures?
10. Differences between structure and union. (Most important)
UNIT- 5
Short answer questions
1. Define file?
2. Differentiate between text file and binary file?
3. Differences between sequential file and random-access file?
4. Give syntax for opening a file?
5. Discuss modes of a file?
6. Give syntax for fscanf and fprintf?
7. Explain error handling file functions?
8. Give syntax for fread and fwrite?
9. Give syntax for fseek(). (most important )
10. Explain the arguments used in main function?
11. Discuss random access file functions?
12. What is argc and agrv
13. Give syntax for enum and typedef and explain with an example
14. What is a preprocessor directive.
15. One program on macro.
Long answer questions:
1. Explain preprocessor directives.
2. Explain file handling functions. (Most important)
3. Write a c program to copy one file content to another and display the copied file
content?
4. Write a c program to write integers to a file and read integers from the file and check if
the integer is even or odd and separate them?
5. Write a c program to inventory file?
6. Write a c program on binary file?
7. Write a c program on command line arguments?

You might also like