Programming in C - CS3251 - Question Bank
Programming in C - CS3251 - Question Bank
CS8251 - PROGRAMMING IN C
UNIT-I
PART A
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 1
www.Poriyaan.in
- Used to translate one high level language statement into another high level
language statement.
- Used to instruct the preprocessor that how it performs the translation before
compilation.
- Used to perform conditional compilation.
- Used to include other C files or library files.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 2
www.Poriyaan.in
PART B
1.Explain the storage classes in c with example programs.
A storage class represents the visibility and a location of a variable. It tells from what part of code
we can access a variable. A storage class is used to describe the following things:
The variable scope.
The location where the variable will be stored.
The initialized value of a variable.
A lifetime of a variable.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 3
www.Poriyaan.in
The variables defined using auto storage class are called as local variables. Auto stands for
automatic storage class. A variable is in auto storage class by default if it is not explicitly specified.
The scope of an auto variable is limited with the particular block only. Once the control goes out of
the block, the access is destroyed. This means only the block in which the auto variable is declared
can access it.
A keyword auto is used to define an auto storage class. By default, an auto variable contains a
garbage value.
Example, auto int age;
The program below defines a function with has two local variables
int add(void) {
int a=13;
auto int b=48;
return a+b;}
We take another program which shows the scope level "visibility level" for auto variables in each
block code which are independently to each other:
#include <stdio.h>
int main( )
{
auto int j = 1;
{
auto int j= 2;
{
auto int j = 3;
printf ( " %d ", j);
}
printf ( "\t %d ",j);
}
printf( "%d\n", j);}
OUTPUT:
321
Extern stands for external storage class. Extern storage class is used when we have global functions
or variables which are shared between two or more files.
Keyword extern is used to declaring a global variable or function in another file to provide the
reference of variable or function which have been already defined in the original file.
The variables defined using an extern keyword are called as global variables. These variables are
accessible throughout the program. Notice that the extern variable cannot be initialized it has
already been defined in the original file
Example, extern void display();
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 4
www.Poriyaan.in
The static variables are used within function/ file as local static variables. They can also be used as
a global variable
Static local variable is a local variable that retains and stores its value between function calls
or block and remains visible only to the function or block in which it is defined.
Static global variables are global variables visible only to the file in which it is declared.
Example: static int count = 10;
Keep in mind that static variable has a default initial value zero and is initialized only once in its
lifetime.
#include <stdio.h> /* function declaration */
void next(void);
static int counter = 7; /* global variable */
main() {
while(counter<10) {
next();
counter++; }
return 0;}
void next( void ) { /* function definition */
static int iteration = 13; /* local static variable */
iteration ++;
printf("iteration=%d and counter= %d\n", iteration, counter);}
Result:
iteration=14 and counter= 7
iteration=15 and counter= 8
iteration=16 and counter= 9
Global variables are accessible throughout the file whereas static variables are accessible only to the
particular part of a code.
The lifespan of a static variable is in the entire program code. A variable which is declared or
initialized using static keyword always contains zero as a default value.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 5
www.Poriyaan.in
You can use the register storage class when you want to store local variables within functions or
blocks in CPU registers instead of RAM to have quick access to these variables. For example,
"counters" are a good candidate to be stored in the register.
Example: register int age;
The keyword register is used to declare a register storage class. The variables declared using
register storage class has lifespan throughout the program.
It is similar to the auto storage class. The variable is limited to the particular block. The only
difference is that the variables declared using register storage class are stored inside CPU registers
instead of a memory. Register has faster access than that of the main memory.
The variables declared using register storage class has no default value. These variables are often
declared at the beginning of a program.
#include <stdio.h> /* function declaration */
main() {
{register int weight;
int *ptr=&weight ;/*it produces an error when the compilation occurs ,we cannot get a memory
location when dealing with CPU register*/}
}
OUTPUT:
error: address of register variable 'weight' requested
The next table summarizes the principal features of each storage class which are commonly used in
C programming
Extern Outside all Memory Zero Entire the file and other files program runtime
functions where the variable is
declared as extern
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 6
www.Poriyaan.in
DECISION STATEMENTS
It checks the given condition and then executes its sub-block. The decision statement decides the
statement to be executed after the success or failure of a given condition.
Types:
Decision making is about deciding the order of execution of statements based on certain conditions
or repeat a group of statements until certain specified conditions are met. C language handles
decision-making by supporting the following statements,
if statement
switch statement
goto statement
The if statement may be implemented in different forms depending on the complexity of conditions
to be tested. The different forms are,
1. Simple if statement
2. if....else statement
Simple if statement
The general form of a simple if statement is,
if(expression)
statement inside;
statement outside;
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 7
www.Poriyaan.in
If the expression returns true, then the statement-inside will be executed, otherwise statement-
inside is skipped and only the statement-outside is executed.
Example:
#include <stdio.h>
void main( )
int x, y;
x = 15;
y = 13;
if (x > y )
x is greater than y
if...else statement
The general form of a simple if...else statement is,
if(expression)
statement block1;
else
statement block2;
}
If the expression is true, the statement-block1 is executed, else statement-block1 is skipped
and statement-block2 is executed.
Example:
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 8
www.Poriyaan.in
#include <stdio.h>
void main( )
int x, y;
x = 15;
y = 18;
if (x > y )
else
y is greater than x
if( expression )
if( expression1 )
statement block1;
else
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 9
www.Poriyaan.in
statement block2;
else
statement block3;
}
if expression is false then statement-block3 will be executed, otherwise the execution continues
and enters inside the first if to perform the check for the next if block, where if expression 1 is true
the statement-block1 is executed otherwise statement-block2 is executed.
Example:
#include <stdio.h>
void main( )
int a, b, c;
printf("Enter 3 numbers...");
if(a > b)
if(a > c)
else
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 10
www.Poriyaan.in
else
if(b > c)
else
else if ladder
The general form of else-if ladder is,
if(expression1)
statement block1;
else if(expression2)
statement block2;
else if(expression3 )
statement block3;
else
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 11
www.Poriyaan.in
default statement;
The expression is tested from the top(of the ladder) downwards. As soon as a true condition is
found, the statement associated with it is executed.
Example :
#include <stdio.h>
void main( )
int a;
printf("Enter a number...");
scanf("%d", &a);
else if(a%8 == 0)
printf("Divisible by 8");
else if(a%5 == 0)
printf("Divisible by 5");
else
printf("Divisible by none");
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 12
www.Poriyaan.in
Loop is a block of statements which are repeatedly executed for certain number of times. Types
1. For loop
2. Nested for loops
3. While loop
4. do while loop
5. do-while statement with while loop
While Loop
A while loop is the most straightforward looping structure. The basic format of while loop is as
follows:
while (condition) {
statements;
}
It is an entry-controlled loop. In while loop, a condition is evaluated before processing a body of the
loop. If a condition is true then and only then the body of a loop is executed. After the body of a
loop is executed then control again goes back at the beginning, and the condition is checked if it is
true, the same process is executed until the condition becomes false. Once the condition becomes
false, the control goes out of the loop.
After exiting the loop, the control goes to the statements which are immediately after the loop. The
body of a loop can contain more than one statement. If it contains only one statement, then the curly
braces are not compulsory. It is a good practice though to use the curly braces even we have a single
statement in the body.
In while loop, if the condition is not true, then the body of a loop will not be executed, not even
once. It is different in do while loop which we will see shortly.
#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
printf("%d\n",num);
num++; //incrementing operation
}
return 0;
}
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 13
www.Poriyaan.in
Output:
1
2
3
4
5
6
7
8
9
10
The above program illustrates the use of while loop. In the above program, we have printed series
of numbers from 1 to 10 using a while loop.
1. We have initialized a variable called num with value 1. We are going to print from 1 to 10
hence the variable is initialized with value 1. If you want to print from 0, then assign the
value 0 during initialization.
2. In a while loop, we have provided a condition (num<=10), which means the loop will
execute the body until the value of num becomes 10. After that, the loop will be terminated,
and control will fall outside the loop.
3. In the body of a loop, we have a print function to print our number and an increment
operation to increment the value per execution of a loop. An initial value of num is 1, after
the execution, it will become 2, and during the next execution, it will become 3. This
process will continue until the value becomes 10 and then it will print the series on console
and terminate the loop.
\n is used for formatting purposes which means the value will be printed on a new line.
Do-While loop
A do-while loop is similar to the while loop except that the condition is always executed after the
body of a loop. It is also called an exit-controlled loop.
The basic format of while loop is as follows:
do {
statements
} while (expression);
As we saw in a while loop, the body is executed if and only if the condition is true. In some cases,
we have to execute a body of the loop at least once even if the condition is false. This type of
operation can be achieved by using a do-while loop.
In the do-while loop, the body of a loop is always executed at least once. After the body is executed,
then it checks the condition. If the condition is true, then it will again execute the body of a loop
otherwise control is transferred out of the loop.
Similar to the while loop, once the control goes out of the loop the statements which are
immediately after the loop is executed.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 14
www.Poriyaan.in
The critical difference between the while and do-while loop is that in while loop the while is written
at the beginning. In do-while loop, the while condition is written at the end and terminates with a
semi-colon (;)
The following program illustrates the working of a do-while loop:
We are going to print a table of number 2 using do while loop.
#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
do //do-while loop
{
printf("%d\n",2*num);
num++; //incrementing operation
}while(num<=10);
return 0;
}
Output:
2
4
6
8
10
12
14
16
18
20
In the above example, we have printed multiplication table of 2 using a do-while loop. Let's see
how the program was able to print the series.
1. First, we have initialized a variable 'num' with value 1. Then we have written a do-while
loop.
2. In a loop, we have a print function that will print the series by multiplying the value of num
with 2.
3. After each increment, the value of num will increase by 1, and it will be printed on the
screen.
4. Initially, the value of num is 1. In a body of a loop, the print function will be executed in this
way: 2*num where num=1, then 2*1=2 hence the value two will be printed. This will go on
until the value of num becomes 10. After that loop will be terminated and a statement which
is immediately after the loop will be executed. In this case return 0.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 15
www.Poriyaan.in
For loop
A for loop is a more efficient loop structure in 'C' programming. The general structure of for loop is
as follows:
for (initial value; condition; incrementation or decrementation )
{
statements;
}
The initial value of the for loop is performed only once.
The condition is a Boolean expression that tests and compares the counter to a fixed value
after each iteration, stopping the for loop when false is returned.
The incrementation/decrementation increases (or decreases) the counter by a set value.
Following program illustrates the use of a simple for loop:
#include<stdio.h>
int main()
{
int number;
for(number=1;number<=10;number++) //for loop to print 1-10 numbers
{
printf("%d\n",number); //to print the number
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
The above program prints the number series from 1-10 using for loop.
1. We have declared a variable of an int data type to store values.
2. In for loop, in the initialization part, we have assigned value 1 to the variable number. In the
condition part, we have specified our condition and then the increment part.
3. In the body of a loop, we have a print function to print the numbers on a new line in the
console. We have the value one stored in number, after the first iteration the value will be
incremented, and it will become 2. Now the variable number has the value 2. The condition
will be rechecked and since the condition is true loop will be executed, and it will print two
on the screen. This loop will keep on executing until the value of the variable becomes 10.
After that, the loop will be terminated, and a series of 1-10 will be printed on the screen.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 16
www.Poriyaan.in
In C, the for loop can have multiple expressions separated by commas in each part.
For example:
for (x = 0, y = num; x < y; i++, y--) {
statements;
}
Also, we can skip the initial value expression, condition and/or increment by adding a semicolon.
For example:
int i=0;
int max = 10;
for (; i < max; i++) {
printf("%d\n", i);
}
Notice that loops can also be nested where there is an outer loop and an inner loop. For each
iteration of the outer loop, the inner loop repeats its entire cycle.
Consider the following example, that uses nested for loops output a multiplication table:
#include <stdio.h>
int main() {
int i, j;
int table = 2;
int max = 5;
for (i = 1; i <= table; i++) { // outer loop
for (j = 0; j <= max; j++) { // inner loop
printf("%d x %d = %d\n", i, j, i*j);
}
printf("\n"); /* blank line between tables */
}}
Output:
1x0=0
1x1=1
1x2=2
1x3=3
1x4=4
1x5=5
2x0=0
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
The nesting of for loops can be done up-to any level. The nested loops should be adequately
indented to make code readable. In some versions of 'C,' the nesting is limited up to 15 loops, but
some provide more.
4.Explain operators inC
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 17
www.Poriyaan.in
C language supports a rich set of built-in operators. An operator is a symbol that tells the compiler
to perform a certain mathematical or logical manipulation. Operators are used in programs to
manipulate data and variables.
C operators can be classified into following types:
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Special operators
ARITHMETIC OPERATORS
C supports all the basic arithmetic operators. The following table shows all the basic arithmetic
operators.
Operator Description
% remainder of division
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 18
www.Poriyaan.in
Relational operators
The following table shows all relation operators supported by C.
Operator Description
Logical operators
|| Logical OR (a || b) is true
Bitwise operators
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 19
www.Poriyaan.in
Bitwise operators perform manipulations of data at bit level. These operators also perform shifting
of bits from right to left. Bitwise operators are not applied to float or double(These are datatypes,
we will learn about them in the next tutorial).
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operator, shifts the bit value. The left operand specifies the value to be shifted and
the right operand specifies the number of positions that the bits in the value have to be shifted
Assignment Operators
Assignment operators supported by C language are as follows.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 20
www.Poriyaan.in
Conditional operator
1. Ternary Operator
2. ? : Operator
It is actually the if condition that we use in C language decision making, but using conditional
operator, we turn the if condition statement into a short and simple operator.
The syntax of a conditional operator is :
The first expression (expression 1) generally returns either true or false, based on which it is
decided whether (expression 2) will be executed or (expression 3)
If (expression 1) returns true then the expression on the left side of " : " i.e (expression 2) is
executed.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 21
www.Poriyaan.in
If (expression 1) returns false then the expression on the right side of " : " i.e (expression 3)
is executed.
Special operator
Introduction
A program which processes the source code before it passes through the compiler is known
as preprocessor.
The commands of the preprocessor are known as preprocessor directives.
It is placed before the main().
It begins with a # symbol.
They are never terminated with a semicolon.
Preprocessor Directives
The preprocessor directives are divided into four different categories which are as follows:
1. Macro expansion
There are two types of macros - one which takes the argument and another which does not
take any argument.
Values are passed so that we can use the same macro for a wide range of values.
Syntax:
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 22
www.Poriyaan.in
Where,
name – it is known as the micro template.
replacement text – it is known as the macro expansion.
#define LOWER 30
void main()
{
int i;
for (i=1;i<=LOWER; i++)
{
printf("\n%d", i);
}
}
Some of the predefined macros which are readily available are as follows:
Macro Description
___LINE___ It contains a current line number as a decimal constant.
___FILE___ It contains the current filename as a string literal.
___DATE___ It shows the current date as a character literal in the ―MMM DD YYYY‖ format.
___TIME___ It shows the current time as a character literal in ―HH:MM:SS‖ format.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 23
www.Poriyaan.in
___STDC___ It is defined as 1 when the compiler complies with the ANSI standard.
___TIMESTAMP___ It is a sing literal in the form of ―DDD MM YYYY Date HH:MM:SS‖. It is used to speci
and time of the last modification of the current source file.
2. File inclusion
The file inclusion uses the #include.
Syntax:
#include filename
The content that is included in the filename will be replaced at the point where the directive
is written.
By using the file inclusive directive, we can include the header files in the programs.
Macros, function declarations, declaration of the external variables can all be combined in
the header file instead of repeating them in each of the program.
The stdio.h header file contains the function declarations and all the information regarding
the input and output.
If the first way is used, the file and then the filename in the current working directory and
the specified list of directories would be searched.
If the second way, is used the file and then the filename in the specified list of directories
would be searched.
3. Conditional compilation
The conditional compilation is used when we want certain lines of code to be compiled or
not.
It uses directives like #if, #elif, #else, #endif
Syntax
If there are a number of conditions to be checked we can use the #elif instead of #else and #if.
4. Miscellaneous directive
There are some directives which do not fall in any of the above mentioned categories.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 24
www.Poriyaan.in
i) #undef : This directive is used in relation to the #define directive. It is used to undefine a defined
macro.
ii) #pragma : It is a specialized and rarely used directive. They are used for turning on and off
certain features.
Following table will show you various directives that we have studied in this chapter:
Directives Description
#define It substitutes a preprocessor macro.
#include It inserts a particular header file from another file.
#undef A preprocessor macro is undefined.
#ifdef It returns true if the macro is defined.
#ifndef It returns true if the macro is not defined.
#if It tests if the compile time condition is true.
#else It is an alternative for #if.
#elif It has #else and #if in one statement.
#endif The conditional preprocessor is ended.
#error It prints the error message on stderr.
#pragma It issues special commands to the compiler by using a standardized method.
UNIT- II
PART A
1. Define Array
Array is a collection of similar type of values
All values are stored in continuous memory locations
All values share a common name
Linear data structure. The elements are organized in a sequential order.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 25
www.Poriyaan.in
9. Define Sorting
Sorting is a process of arranging the elements either in ascending order or descending order.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 26
www.Poriyaan.in
10. Sort the following elements using selection sort method. 23,55,16,78,2
Step1:Find smallest element in the list & exchange the element with first element of the list
2,55,16,78,23
Step2: Find second smallest value & exchange it with the second element of the list
2,16,55,78,23
Step 3: Continue the process until all the elements are arranged in the order
2,16,23,78,55
Step 4: 2,16,23,55,78
PART B
1.Write a c program to multiply two matrices (2D array) which will be entered by a user.
Ans:
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
if (n != p)
printf("The multiplication isn't possible.\n");
else
{
printf("Enter elements of second matrix\n");
multiply[c][d] = sum;
sum = 0;
}
}
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 27
www.Poriyaan.in
printf("\n");
}
}
return 0;
}
2.Write a c program to find scaling of two matrices (2D array) which will be entered by a user.(5)
Ans:
#include<stdio.h>
int main(){
/* 2D array declaration*/
int disp[2][3];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf(―enter the value to be scaled‖);
scanf(―%d‖,&z);
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &z*disp[i][j]);
}
}
3.Write a c program to find determinant of two matrices (2D array) which will be entered by a user.
#include <stdio.h>
void main()
{
int arr1[10][10],i,j,n;
int det=0;
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 28
www.Poriyaan.in
}
}
printf("The matrix is :\n");
for(i=0;i<3;i++)
{
for(j=0;j<3 ;j++)
printf("% 4d",arr1[i][j]);
printf("\n");
}
for(i=0;i<3;i++)
det = det + (arr1[0][i]*(arr1[1][(i+1)%3]*arr1[2][(i+2)%3] -
arr1[1][(i+2)%3]*arr1[2][(i+1)%3]));
#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 29
www.Poriyaan.in
if (j == c - 1) {
printf("\n\n");
}
}
return 0;
}
#include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c, i, j;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
selection Sort in C
Selection sort is another algorithm that is used for sorting. This sorting algorithm, iterates through
the array and finds the smallest number in the array and swaps it with the first element if it is
smaller than the first element. Next, it goes on to the second element and so on until all elements are
sorted.
Example of Selection Sort
Consider the array:
[10,5,2,1]
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 30
www.Poriyaan.in
The first element is 10. The next part we must find the smallest number from the remaining array.
The smallest number from 5 2 and 1 is 1. So, we replace 10 by 1.
The new array is [1,5,2,10] Again, this process is repeated.
Finally, we get the sorted array as [1,2,5,10].
Let us continue with this article on Selection Sort in C and see how the algorithm works,
Algorithm for Selection Sort:
Step 1 − Set min to the first location
Step 2 − Search the minimum element in the array
Step 3 – swap the first location with the minimum value in the array
Step 4 – assign the second element as min.
Step 5 − Repeat the process until we get a sorted array.
Let us take a look at the code for the the programmatic implementation,
Code for Selection Sort:
1 #include <stdio.h>
2 int main()
3 {
4 int a[100], n, i, j, position, swap;
5 printf("Enter number of elementsn");
6 scanf("%d", &n);
7 printf("Enter %d Numbersn", n);
8 for (i = 0; i < n; i++)
9 scanf("%d", &a[i]);
10 for(i = 0; i < n - 1; i++)
11 {
12 position=i;
13 for(j = i + 1; j < n; j++)
14 {
15 if(a[position] > a[j])
16 position=j;
17 }
18 if(position != i)
19 {
20 swap=a[i];
21 a[i]=a[position];
22 a[position=swap;
23 }
24 }
25 printf("Sorted Array:n");
26 for(i = 0; i < n; i++)
27 printf("%dn", a[i]);
28 return 0;
29 }
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 31
www.Poriyaan.in
A linear search, also known as a sequential search, is a method of finding an element within a list. It
checks each element of the list sequentially until a match is found or the whole list has been
searched.
If x does not match with any of the elements then return -1.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 32
www.Poriyaan.in
Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an
interval covering the whole array. If the value of the search key is less than the item in the middle of the
interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check
until the value is found or the interval is empty.
Example :
The idea of binary search is to use the information that the array is sorted and reduce the time
complexity to O(Log n).
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 33
www.Poriyaan.in
Output :
Element is present at index 3
Iterative implementation of Binary Search
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 34
www.Poriyaan.in
Output :
Element is present at index 3
Time Complexity:
The time complexity of Binary Search can be written as
T(n) = T(n/2) + c
The above recurrence can be solved either using Recurrence T ree method or Master method. It falls in
case II of Master Method and solution of the recurrence is .
Auxiliary Space: O(1) in case of iterative implementation. In case of recursive implementation, O(Logn)
recursion call stack space.
Unit III Functions and pointers
PART A
1. What is a function?
Function is a set of instructions
Self contained block
Performs a specific task
Used to avoid redundancy of code
2. What is the need for functions?
To reduce the complexity of large programs
To increase the readability
To achieve reusability
To avoid redundancy of code
To save Memory
3. What are the uses of pointer?
Saves Memory Space
Used for dynamic memory allocation
Faster execution
Used to pass array of values to a function as a single argument
4. Define typedef .
The typedef keyword enables the programmer to create a new data type name by
using an existing data type.
By using typedef, no new data is created, rather an alternate name is given to a
known data type.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 35
www.Poriyaan.in
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 36
www.Poriyaan.in
printf(―%d‖,*(p));
Formal argument: Specified in the function definition statement. It takes either copy
or address of the actual arguments
Valid operation
The pointer holds the address 2000. This value is added with 1.
The data type size of the constant is added with the address. p=
2000+(2*1)=2002
8. List out any 4 math functions
pow(x,y) : used to find power of value of xy .Returns a double value log10(x)
: used to find natural logarithmic value of x
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 37
www.Poriyaan.in
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 38
www.Poriyaan.in
char datatype1;
int datatype2;
float datatype3;
};
more memory and are generally slow. Instead, you can use loop.
Example:
void recursion()
int main()
recursion();
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 39
www.Poriyaan.in
function. However, macros are generally small and cannot handle large, complex
coding constructs.
In cases where large, complex constructs are to handled, functions are more suited,
additionally; macros are expanded inline, which means that the code is replicated
for each occurrence of a macro.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 40
www.Poriyaan.in
PART B
1. What is a function in C? Explain the steps in writing a function in C program with Example.
Ans: A function is a block of statements that performs a specific task.
Syntax:
return_type function_name (argument list)
{
Set of statements – Block of code
}
#include <stdio.h>
int addition(int num1, int num2)
{
int sum;
sum = num1+num2;
return sum;
}
int main()
{
int var1, var2;
printf("Enter number 1: ");
scanf("%d",&var1);
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 41
www.Poriyaan.in
return 0;
}
Prototype Syntax
function-prototype-declaration:
declaration-specifiers(opt) declarator;
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 42
www.Poriyaan.in
The declarator includes a parameter type list, which can consist of a single parameter of type void . In
its simplest form, a function prototype declaration might have the following format:
storage_class(opt) return_type(opt) function_name (
type(1) parameter(1), ..., type(n) parameter(n) );
Consider the following function definition:
char function_name( int lower, int *upper, char (*func)(), double y )
{}
The corresponding prototype declaration for this function is:
char function_name( int lower, int *upper, char (*func)(), double y );
A prototype is identical to the header of its corresponding function definition specified in the prototype
style, with the addition of a terminating semicolon (;) or comma (,), as appropriate (depending on
whether the prototype is declared alone or in a multiple declaration).
Function prototypes need not use the same parameter identifiers as in the corresponding function
definition because identifiers in a prototype have scope only within the identifier list. Moreover, the
identifiers themselves need not be specified in the prototype declaration; only the types are required.
For example, the following prototype declarations are equivalent:
char function_name( int lower, int *upper, char (*func)(), double y );
char function_name( int a, int *b, char (*c)(), double d );
char function_name( int, int *, char (*)(), double );
Though not required, identifiers should be included in prototypes to improve program clarity and
increase the type-checking capability of the compiler.
Variable-length argument lists are specified in function prototypes with ellipses. At least one parameter
must precede the ellipses. For example:
char function_name( int lower, ... );
Data-type specifications cannot be omitted from a function prototype.
3. What is recursion? Write a C program to find the sum of the digits, to find the factorial of a
number and binary search using recursion.
Ans: The process in which a function calls itself directly or indirectly is called recursion and
the corresponding function is called as recursive function.
Factorial:
#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 43
www.Poriyaan.in
Binary search:
#include <stdio.h>
void binary_search(int [], int, int, int);
void bubble_sort(int [], int);
int main()
{
int key, size, i;
int list[25];
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 44
www.Poriyaan.in
}
}
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 45
www.Poriyaan.in
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 46
www.Poriyaan.in
}
float cosineh(float x)
{
return (sinh(x));
}
float tangenth(float x)
{
return (sinh(x));
}
float logten(float x)
{
return (log10(x));
}
float squareroot(float x)
{
return (sqrt(x));
}
float exponent(float x)
{
return(exp(x));
}
float power(float x, float y)
{
return (pow(x,y));
}
5. Explain about pointers and write the use of pointers in arrays with suitable example.
Ans: Pointers in C language is a variable that stores/points the address of another variable. A Pointer in
C is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to
any of the data type such as int, float, char, double, short etc.
Pointer Syntax : data_type *var_name; Example : int *p; char *p;
Where, * is used to denote that ―p‖ is pointer variable and not a normal variable.
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 47
www.Poriyaan.in
return 0;
}
6. Explain the concept of pass by value and pass by reference. Write a C program to
swap the content of two variables using pass by reference.
` Pass by value: In this approach we pass copy of actual variables in function as a parameter.
Hence any modification on parameters inside the function will not reflect in the actual variable. For
example:
#include<stdio.h>
int main(){
int a=5,b=10;
swap(a,b);
printf("%d %d",a,b);
return 0;
}
void swap(int a,int b){
int temp;
temp =a;
a=b;
b=temp;
}
Output: 5 10
(b)Pass by reference: In this approach we pass memory address actual variables in function as a
parameter. Hence any modification on parameters inside the function will reflect in the actual variable.
For example:
#incude<stdio.h>
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 48
www.Poriyaan.in
int main(){
int a=5,b=10;
swap(&a,&b);
printf("%d %d",a,b);
return 0;
}
void swap(int *a,int *b){
int *temp;
*temp =*a;
*a=*b;
*b=*temp;
}
Output: 10 5
UNIT IV
STRUCTRES
Structure Union
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 49
www.Poriyaan.in
Every member has its own memory. All members use the same memory.
The keyword used is struct. The keyword used is union.
All members occupy separate memory location, Different interpretations for the same memory
hence different interpretations of the same location are possible. Conservation of memory
memory is
location are not possible. Consumes more space possible
compared to union.
3. Define Structure in C.
C Structure is a collection of different data types which are grouped together and
each element in a C structure is called member.
If you want to access structure members in C, structure variable should be declared.
Many structure variables can be declared for same structure and memory will
be allocated for each separately.
It is a best practice to initialize a structure to null while declaring, if we don‘t
assign any values to structure members.
4. What you meant by structure definition?
A structure type is usually defined near to the start of a file using a typedef
statement. typedef defines and names a new type, allowing its use throughout the
program. typedefs usually occur just after the #define and #include statements in a
file.
Here is an example structure
definition. typedef struct {
char
name[64];
char
course[1
28]; int
age;
int year;
} student;
This defines a new type student variables of type student can be declared as
follows. student st_rec;
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 50
www.Poriyaan.in
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 51
www.Poriyaan.in
RAM. This means that the variable has a maximum size equal to the register size
(usually one word) and cant have the unary '&' operator applied to it (as it does not
have a memory location).
{
register int Miles;
}
{
int Count; auto int Month;
}
The example above defines two variables with the same storage class. auto can only
be used within functions, i.e. local variables.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 52
www.Poriyaan.in
code files as well as the file name that we want that appears when an error
takes place. Its format is:
#line number "filename"
Where number is the new line number that will be assigned to the next code line.
The line numbers of successive lines will be increased one by one from this point on.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 53
www.Poriyaan.in
Struct S
{
char datatype1; int
datatype2; float
datatype3;
};
struct name {
member 1;
member 2;
...
};
The above illustrated structure prototype describes one node that comprises of two
logical segments. One of them stores data/information and the other one is a
pointer indicating where the next component can be found. .Several such inter-
connected nodes create a chain of structures.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 54
www.Poriyaan.in
A linear linked list is a chain of structures where each node points to the next
node to create a list. To keep track of the starting node's address a dedicated pointer
(referred as startpointer) is used. The end of the list is indicated by a NULLpointer.
In order to create a linked list of integers, we define each of its element (referred as
node) using the following declaration.
struct node_type {
int data;
};
This statement creates the starting node of list. A block of memory whose
size is equal to the sizeof(node) is allocated to the node pointer start. Typecasting
is used because otherwise malloc will return pointer to character.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 55
www.Poriyaan.in
PART-B
Structure
declaration- struct
tagname
Data type
member1; Data
type member2;
Data type
member3;
………
………
struct
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 56
www.Poriyaan.in
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 57
www.Poriyaan.in
………
………
struct tagname
struct element 1;
struct element 2;
struct element 3;
………
………
struct element n;
};
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 58
www.Poriyaan.in
struct student
char branch[20];
}; struct student s;
Like primary variables structure variables can also be initialized when they are
declared. Structure templates can be defined locally or globally. If it is local it can be used
within that function. If it is global it can be used by all other functions of the program.
struct student
int age=20;
char
name[20]=‖sona‖;
}s1;
A structure can be
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 59
www.Poriyaan.in
int age,roll;
char name[20];
} struct student
s2={17,102,‖rupa‖};
If initialiser is less than no.of structure variable, automatically rest values are taken as zero.
Dot operator is used to access the structure elements. Its associativety is from left to right.
s1.roll; s1.age;
Elements of structure are stored in contiguous memory locations. Value of structure variable can be
assigned to another structure variable of same type using assignment operator.
Example:
} s1,s2;
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 60
www.Poriyaan.in
Unary, relational, arithmetic, bitwise operators are not allowed within structure variables.
2. Write a C program to store the employee information using structure and
search a particular employee using Employee number.
/*C program to read and print employee's record using structure*/
#include <stdio.h>
/*structure declaration*/
struct employee{
char name[30];
int empId;
float salary;
};
int main()
{
/*declare structure variable*/
struct employee emp;
struct time
int hr,min;
};
struct day
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 61
www.Poriyaan.in
};
struct student
char nm[20];
struct day d;
4. Explain about array of structures and pointers in structures with example program.
Array of structures
When database of any element is used in huge amount, we prefer Array of structures.
Example: suppose we want to maintain data base of 200 students, Array of structures is used.
#include<stdio.h>
#include<string.h>
struct student
};
void main()
s[i].roll=i+1;
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 62
www.Poriyaan.in
for(i=0;i<200;i++)
scanf("%s",s[i].branch); printf("\n");
for(i=0;i<200;i++)
printf("\nName:");
puts(s[i].name);
printf("\nBranch:");
puts(s[i].branch);
struct student
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 63
www.Poriyaan.in
char name[30];
int roll,age,marks[5];
5. Write a C program to create mark sheet for students using self referential structure.
#include<stdio.h>
#include<conio.h>
struct mark_sheet{
char name[20];
int marks[10];
int total;
float average;
char rem[10];
char cl[20];
}students[100];
int main(){
int a,b,n,flag=1;
char ch;
clrscr();
scanf("%d",&n);
for(a=1;a<=n;++a){
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 64
www.Poriyaan.in
clrscr();
scanf("%s", students[a].name);
scanf("%ld", &students[a].rollno);
students[a].total=0;
for(b=1;b<=5;++b){
scanf("%d", &students[a].marks[b]);
students[a].total += students[a].marks[b];
if(students[a].marks[b]<40)
flag=0;
students[a].average = (float)(students[a].total)/5.0;
if((students[a].average>=75)&&(flag==1))
strcpy(students[a].cl,"Distinction");
else
if((students[a].average>=60)&&(flag==1))
strcpy(students[a].cl,"First Class");
else
if((students[a].average>=50)&&(flag==1))
strcpy(students[a].cl,"Second Class");
else
if((students[a].average>=40)&&(flag==1))
strcpy(students[a].cl,"Third Class");
if(flag==1)
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 65
www.Poriyaan.in
strcpy(students[a].rem,"Pass");
else
strcpy(students[a].rem,"Fail");
flag=1;
for(a=1;a<=n;++a){
clrscr();
printf("\n\n\t\t\t\tMark Sheet\n");
printf("\n------------------------------------------------------------------------");
for(b=1;b<=5;b++){
printf("\n\n------------------------------------------------------------------------\n");
ch = getche();
if((ch=="y")||(ch=="Y"))
continue;
return(0);
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 66
www.Poriyaan.in
The process of allocating memory at the time of execution or at the runtime, is called dynamic
memory location.
Two types of problem may occur in static memory allocation.
If number of values to be stored is less than the size of memory, there would be wastage of
memory.
If we would want to store more values by increase in size during the execution on assigned size
then it fails.
Allocation and release of memory space can be done with the help of some library function called
dynamic memory allocation function. These library function are called as dynamic memory
allocation function. These library function prototype are found in the header file, ―alloc.h‖ where
it has defined.
Function take memory from memory area is called heap and release when not required.
Pointer has important role in the dynamic memory allocation to allocate memory.
malloc():
This function use to allocate memory during run time, its declaration is void*malloc(size);
malloc ()
returns the pointer to the 1st byte and allocate memory, and its return type is void, which can be
type cast such as:
int *p=(datatype*)malloc(size)
If memory location is successful, it returns the address of the memory chunk that was allocated
and it returns null on unsuccessful and from the above declaration a pointer of type(datatype) and
size in byte.
And datatype pointer used to typecast the pointer returned by malloc and this typecasting is
necessary since, malloc() by default returns a pointer to void.
Example int*p=(int*)malloc(10);
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 67
www.Poriyaan.in
So, from the above pointer p, allocated IO contigious memory space address of 1st byte and is
stored in the variable.
We can also use, the size of operator to specify the the size, such as
Moreover , it returns null, if no sufficient memory available , we should always check the malloc
return such as, if(p==null)
Example:
main()
int n , avg,i,*p,sum=0;
scanf(―%d‖,&n);
p=(int *)malloc(n*size(int));
if(p==null)
for(i=0;i<n;i++)
scanf(―%d‖,(p+i));
for(i=0;i<n;i++)
Printf(―%d‖,*(p+i));
sum=sum+*p;
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 68
www.Poriyaan.in
avg=sum/n;
printf(―avg=%d‖,avg);
A linked list is made up of many nodes which are connected in nature. Every node is mainly
divided into two parts, one part holds the data and the other part is connected to a different node. It
is similar to the picture given below.
include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct test_struct
{
int val;
struct test_struct *next;
};
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 69
www.Poriyaan.in
return ptr;
}
if(add_to_end)
printf("\n Adding node to end of list with value [%d]\n",val);
else
printf("\n Adding node to beginning of list with value [%d]\n",val);
if(add_to_end)
{
curr->next = ptr;
curr = ptr;
}
else
{
ptr->next = head;
head = ptr;
}
return ptr;
}
while(ptr != NULL)
{
if(ptr->val == val)
{
found = true;
break;
}
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 70
www.Poriyaan.in
else
{
tmp = ptr;
ptr = ptr->next;
}
}
if(true == found)
{
if(prev)
*prev = tmp;
return ptr;
}
else
{
return NULL;
}
}
del = search_in_list(val,&prev);
if(del == NULL)
{
return -1;
}
else
{
if(prev != NULL)
prev->next = del->next;
if(del == curr)
{
curr = prev;
}
else if(del == head)
{
head = del->next;
}
}
free(del);
del = NULL;
return 0;
}
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 71
www.Poriyaan.in
void print_list(void)
{
struct test_struct *ptr = head;
return;
}
int main(void)
{
int i = 0, ret = 0;
struct test_struct *ptr = NULL;
print_list();
print_list();
print_list();
for(i = 1; i<10; i += 4)
{
ptr = search_in_list(i, NULL);
if(NULL == ptr)
{
printf("\n Search [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n Search passed [val = %d]\n",ptr->val);
}
print_list();
ret = delete_from_list(i);
if(ret != 0)
{
printf("\n delete [val = %d] failed, no such element found\n",i);
}
else
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 72
www.Poriyaan.in
{
printf("\n delete [val = %d] passed \n",i);
}
print_list();
}
return 0;
}
UNIT V
FILE PROCESSING
1. Why files are needed?
When a program is terminated, the entire data is lost. Storing in a file will preserve
your data even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents
of the file using few commands in C.
You can easily move your data from one computer to another without any changes.
2. Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
Text files
Text files are the normal .txt files that you can easily create using Notepad or any simple text
editors.
When you open those files, you'll see all the contents within the file as plain text. You can
easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide least security and
takes bigger storage space.
Binary files
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 73
www.Poriyaan.in
They can hold higher amount of data, are not readable easily and provides a better security
than text files.
FILE *fptr;
ptr = fopen("fileopen","mode")
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 74
www.Poriyaan.in
r+ Open for both reading and writing. If the file does not exist, fopen() returns
NULL.
Open for both reading and
rb+ If the file does not exist, fopen() returns
writing in binary mode.
NULL.
If the file exists, its contents are
w+ Open for both reading and writing.
overwritten. If the file does not exist, it
will be created.
Open for both reading and If the file exists, its contents are
wb+
writing in binary mode. overwritten. If the file does not exist, it
will be created.
a+ Open for both reading and If the file does not exists, it will be created.
appending.
Open for both reading and
ab+ If the file does not exists, it will be created.
appending in binary mode.
6. How to close a file?
The file (both text and binary) should be closed after reading/writing.
Closing a file is performed using library function fclose().
fclose(fptr); //fptr is the file pointer associated with file to be closed.
Reading and writing to a text file
For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is that, fprint and
fscanf expects a pointer to the structure FILE.
8. What is file?
A file is a semi-permanent, named collection of data. A File is usually stored on
magnetic media, such as a hard disk or magnetic tape.
Semi-permanent means that data saved in files stays safe until it is deleted or
modified.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 75
www.Poriyaan.in
A very common data processing operation is report generation. This is when the
data in a file (or files) is processed by a program to generate a report of some kind. The report
might be a summary of the financial state of a corporation, or a series of bills for its
customers, or a series of checks to be mailed to its employees.
Large corporations have very large databases kept on many high capacity disks and
processed by programs running on large computers called mainframe
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 76
www.Poriyaan.in
The picture shows the main file and the transaction file as input to a program. The
output is a new, updated main file. The previous version of the file can be kept as backup.
Management information science is the field that studies how to organize and
manage the information of a corporation using computers and files. Usually the business
school of a university has a management information science department.
1. Sequential Access — The data are placed in the file in a sequence like beads on a
string. Data are processed in sequence, one after another. To reach a particular item of
data, all the data that proceeds it first must be read.
2. Random Access — The data are placed into the file by going directly to the location
in the file assigned to each data item. Data are processed in any order. A particular
item of data can be reached by going directly to it, without looking at any other data.
A sequential file works like a reel of tape. (In fact, sequential files are often stored on reels of
magnetic tape.) Data in a sequential file are processed in order, starting with the first item, the
processing the second, then the third and so on. To reach data in the middle of the file you
must go through all the data that preceeds it.
A random access file works like a sampler box of chocolate. You can access a particular item
by going directly to it. Data in a random acess file may be accessed in any order. To read data
in the middle of the file you can go directly to it. Random access files are sometimes
called direct access files.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 77
www.Poriyaan.in
You might think that all files should be random access. But random access files are much
more difficult to imp.
important for your program especially when you want to control your program from outside
instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a pointer array which
points to each argument passed to the program.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 78
www.Poriyaan.in
This function is used for seeking the pointer position in the file at the specified byte.
Syntax: fseek( file pointer, displacement, pointer position);
Where
file pointer -----It is the pointer which points to the file.
displacement ---- It is positive or negative.This is the number of bytes which are
skipped backward (if negative) or forward( if positive) from the current position.This is
attached with L because this is a long integer.
Pointer position:
This sets the pointer position in the file.
Value pointer position
0 Beginning o
1 Current position
2 End of file
16. Give an example for fseek().
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file,from this statement pointer
position is skipped 10 bytes from the beginning of the file.
2) fseek( p,5L,1)
1 means current position of the pointer position.From this statement pointer position
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 79
www.Poriyaan.in
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 80
www.Poriyaan.in
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 81
www.Poriyaan.in
Syntax: ferror(fptr);
Where fptr is a file pointer.
PART-B
Files: As we know that Computers are used for storing the information for a
Permanent Time or the Files are used for storing the Data of the users for a Long time
Period. And the files can contains any type of information means they can Store the text,
any Images or Pictures or any data in any Format. So that there must be Some
Mechanism those are used for Storing the information, Accessing the information and
also Performing Some Operations on the files
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 82
www.Poriyaan.in
There are Many files which have their Owen Type and own names. When we Store a
File in the System, then we must have to specify the Name and the Type of File. The
Name of file will be any valid Name and Type means the application with the file has
linked.
So that we can say that Every File also has Some Type Means Every File belongs to
Special Type of Application software‘s. When we Provides a Name to a File then we
also specify the Extension of the File because a System will retrieve the Contents of the
File into that Application Software. For Example if there is a File Which Contains Some
Paintings then this will Opened into the Paint Software.
1) Ordinary Files or Simple File: Ordinary File may belong to any type of Application
for example notepad, paint, C Program, Songs etc. So all the Files those are created by a
user are Ordinary Files. Ordinary Files are used for Storing the information about the
user Programs. With the help of Ordinary Files we can store the information which
contains text, database, any image or any other type of information.
2) Directory files: The Files those are Stored into the a Particular Directory or Folder.
Then these are the Directory Files. Because they belongs to a Directory and they are
Stored into a Directory or Folder. For Example a Folder Name Songs which Contains
Many Songs So that all the Files of Songs are known as Directory Files.
3) Special Files: The Special Files are those which are not created by the user. Or The
Files those are necessary to run a System. The Files those are created by the System.
Means all the Files of an Operating System or Window, are refers to Special Files. There
are Many Types of Special Files, System Files, or windows Files, Input output Files. All
the System Files are Stored into the System by using. sys Extension.
4) FIFO Files: The First in First Out Files are used by the System for Executing the
Processes into Some Order. Means To Say the Files those are Come first, will be
Executed First and the System Maintains a Order or Sequence Order. When a user
Request for a Service from the System, then the Requests of the users are Arranged into
Some Files and all the Requests of the System will be performed by the System by using
Some Sequence Order in which they are Entered or we can say that all the files or
Requests those are Received from the users will be Executed by using Some Order
which is also called as First in First Out or FIFO order.
Files are not made for just reading the Contents, we can also Perform Some other
operations on the Files those are Explained below As :
1) Read Operation: Meant To Read the information which is Stored into the Files.
2) Write Operation: For inserting some new Contents into a File.
3) Rename or Change the Name of File.
4) Copy the File from one Location to another.
5) Sorting or Arrange the Contents of File.
6) Move or Cut the File from One Place to Another.
7) Delete a File
8) Execute Means to Run Means File Display Output.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 83
www.Poriyaan.in
On the other hand, Random Access to a file means that the computer system can read or
write information anywhere in the data file. This type of operation is also called ―Direct
Access‖ because the computer system knows where the data is stored (using Indexing)
and hence goes ―directly‖ and reads the data.
Sequential access has advantages when you access information in the same order all the
time. Also is faster than random access.
On the other hand, random access file has the advantage that you can search through it
and find the data you need more easily (using indexing for example). Random Access
Memory (RAM) in computers works like that.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 84
www.Poriyaan.in
int main(){
char name[50];
int marks,i,n;
clrscr();
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","a"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
getch();
return 0;
}
5. Write a C program to write all the members of an array of strcures to a
file using fwrite(). Read the array from the file and display on the screen.
#include<stdio.h>
#include<conio.h>
struct s
{
char name[50];
int height;
};
int main(){
struct s a[5],b[5];
FILE *fptr;
int i;
clrscr();
fptr=fopen("file.txt","wb");
for(i=0;i<5;++i)
{
fflush(stdin);
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 85
www.Poriyaan.in
argv [ ] (ARGument Vector) denotes to a pointer array that is pointing to every argument
that has been passed to your program.
#include <stdio.h>
if( argc == 2 )
{
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 86
www.Poriyaan.in
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 87
Programming in C
Physics
Basic for Engineering
Electrical and Data Structure
Problem Solving and Science Engineering
Electronics
Python Programming Object Oriented
Programming in C
Programming
Elective-Management
Professional Elective II
Professional Elective IV