Program in C Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 82

KINGS ENGINEERING COLLEGE

Chennai-Bangalore Highway, Irungattukottai, Sriperumbudur, Chennai-602


117 (opp.Hyundai motors)

Question and Answer

CS8251 – Programming in C
for I Year II Sem CSE & IT

1
SYLLABUS-

PROGRAMMING IN C Regulation 2017 – CS8251


UNIT I BASICS OF C PROGRAMMING
Introduction to programming paradigms – Structure of C program – C programming: Data Types
– Storage classes – Constants – Enumeration Constants – Keywords – Operators: Precedence and
Associativity – Expressions – Input/Output statements, Assignment statements – Decision making
statements – Switch statement – Looping statements – Pre-processor directives – Compilation process

UNIT II ARRAYS AND STRINGS


Introduction to Arrays: Declaration, Initialization – One dimensional array – Example Program:
Computing Mean, Median and Mode – Two dimensional arrays – Example Program: Matrix
Operations (Addition, Scaling, Determinant and Transpose) – String operations: length, compare,
concatenate, copy – Selection sort, linear and binary search.

UNIT III FUNCTIONS AND POINTERS


Introduction to functions: Function prototype, function definition, function call, Built-in functions
(string functions, math functions) – Recursion – Example Program: Computation of Sine series,
Scientific calculator using built-in functions, Binary Search using recursive functions
– Pointers – Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers –
Example Program: Sorting of names – Parameter passing: Pass by value, Pass by reference – Example
Program: Swapping of two numbers and changing the value of a variable using pass by reference.

UNIT IV STRUCTURES
Structure – Nested structures – Pointer and Structures – Array of structures – Example Program using
structures and pointers – Self referential structures – Dynamic memory allocation – Singly linked list
– typedef.

UNIT V FILE PROCESSING


Files – Types of file processing: Sequential access, Random access – Sequential access file – Example
Program: Finding average of numbers stored in sequential access file – Random access file – Example
Program: Transaction processing using random access files – Command line arguments

2
UNIT I - BASICS OF C PROGRAMMING
Introduction to programming paradigms – Structure of C program – C programming: Data Types – Storage classes –
Constants – Enumeration Constants – Keywords – Operators: Precedence and Associativity – Expressions – Input/Output
statements, Assignment statements – Decision making statements – Switch statement – Looping statements – Pre-processor
directives – Compilation process.
Q1. STRUCTURE OF A C PROGRAM: ( 8 MARKS)

Preprocessor section:
• It contains special instructions that indicate how to prepare the program for compilation.
• Commonly used preprocessor command is “#include”.
• Which tells the compiler that the needed information is in header file to execute the program.
Eg: #include<stdio.h>, #define A 10, ….etc.
Global declaration section:
The variables that are used in more than one function throughout the program are called
global variables and declared outside of all the function i.e., before main().
Functions():
• A C program contains one or more functions.
• Function is defined as a group of C statements that are executed together.
• Every ‘C’ program must have one main() function.
• The execution of a C program begins at this function.
• All functions are divided in to two parts:
1. Declaration part
2. Execution part
Declaration Part:
• Helps to describe the data that will be used in the function.
• The data declared within a function are known as local variables.
• Local variables will be visible only within that function.
• Lifetime of the local variables will be only till the function ends.
Executable part:
• The Executable part in a function contains the code that manipulates the data to perform a specified task.
• It contains atleast one valid ‘C’ statement.
• The execution of a program begins with opening brace ‘{‘and ends with closing brace‘}’.
• All the statements in the program ends with a semicolon(;) except conditional and control statements.
Various elements of ‘C’ program:
//Area of Circle Documentation Section
#include<stdio.h>
Preprocessor Section
#define pi 3.14
float area; Global declaration Section
void main() Main Function Header
Main Function

{ int r;
printf(“Enter the r value:”); Local variable declaration
scanf(“%d”,&r);
area=pi*r*r; Process
printf(“Area=%f”,area);
} Output

3
Q2. C TOKENS: (13 MARKS)
➢ Tokens are the basic building blocks in C language.
➢ This means that a program is constructed using a combination of these tokens.
• Keywords
• Variables
• Constants
• Strings
• Special Characters
• Operators
Keywords:
• The predefined reserved words called keywords.
• That have special meaning to the compiler.
• Keywords are must written in lower case.
• They cannot be used as identifier or variable name.
• The ‘C’ keywords are listed below.

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Identifiers:
• Help us to identify data and other objects in the program.
• Identifiers are the names given to program elements such as variables, arrays and functions.
• Identifiers cannot be a keyword.
Rules:
1. Cannot include special characters.
2. Cannot be two successive underscores.
3. Case sensitive.
4. Must begin with a letter or an underscore.
5. Cannot include white spaces.
Example:
First, first, sum, total etc.
//1st, sum of numbers, int are invalid identifiers.

Data types:
• Data type determines type and size of data associated with variables and functions of the program.
• Data types are broadly classified as,
1. Primary (primitive or Basic) data types - int, char, float, double and void(valueless).
2. Derived data types - Arrays, pointers.
3. User-defined data types - Structures, unions and enum.
4. Empty Data type – void
Storage sizes and value ranges

Type Storage size Value range

char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

4
int 2 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 4 bytes -2,147,483,648 to 2,147,483,647

unsigned long 4 bytes 0 to 4,294,967,295


Variables:
•A variable is a data storage location in computer memory.
•A variable is an entity whose value can vary during the execution of a program.
Rules:
1. Variable names may consist of letters, digits and the underscore (_) character.
2. Variables must begin with a letter.
3. It should not be a keyword.
4. White space is not allowed.
Example
int a;
Here ‘a’ is a variable of integer type.
Initializing variables:
Initialization of variables can be done using the assignment operator ( = ).
Syntax: Datatype Variable = value;
Example: int a=10;
SCOPE OF VARIABLES:
Local variables:
• The variables which are defined inside a main function block or inside a function are called local
variables.
• It is declared within blocks.
Example:
void main()
{
int i,j;
/* body of the function */
}
i, j are local variables, and their lifetime is within the main block.
Global variables:
• The variables that are declared before the function main() are called the global variables.
• Their lifetime is entire program.
Example:
#include<stdio.h>
int a=5,b=2;
void main()
{
fun();
}
void fun()
{
int sum;
sum = a+b;
}
Output: 7
In the above program a, b are global variables, that can be used inside both main() and fun().
5
Q3: CONSTANTS:
• Constants are fixed values whose values do not change during its execution.
• Constants can be declared with the keyword ‘const’.
• These fixed values are also called literals.
• The types of constants are,
1. Integer type
2. Floating point type
3. Character type
4. String type
i) Integer constants:
• An integer constant formed with the sequence of digits.
• An integer literal can also have a suffix U and L, for unsigned and long, respectively.
• Integer literal can be a decimal, octal, or hexadecimal constant.
Syntax: const datatype identifier=value;
Example: const int M = 95;
Rules:
• It must have atleast one value.
• Decimal point is not allowed.
• It can be either positive or negative.
• No commas or blank spaces are allowed
ii) Real constants or Floating point Constant:
• A real constant is made up of a sequence of numeric digits with presence of a decimal point.
• Some real constants are distance, heights, temperatures, etc.
Syntax: const datatype identifier=value;
Example: const float distance =126.5; const float val =314159E-5L;
Rules:
• A real constant must have one digit.
• A real constant must have decimal point.
• No commas or blank spaces are allowed.
iii) Character constants:
• The character constant contains a single character enclosed in single quotes.
• A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character
(e.g., '\u02C0').
Syntax: const datatype identifier= value;
Example: const char c=’s’,gender=’F’;
iv) String constants:
• A string constant is a sequence of characters enclosed in double quotes.
• A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character
(e.g., '\u02C0').
Syntax: const datatype identifier= value;
Example: const char c[10]=”John”;
Defining Constant:
There are two simple ways in C to define constants,
• Using #define preprocessor. EX: #define LENGTH 10
• Using const keyword. EX: const int LENGTH = 10;
Example Program:
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
return 0; Note that it is a good programming practice to define constants in CAPITALS.
}
Output: Value of area : 50

6
Q4. STORAGE CLASS:
A storage class defines the scope and life-time of variables and functions within the program.
There are four types,
1. auto
2. register
3. register
4. extern
1.Auto:
• It is a default storage class for all local variables.
• By default they are assigned a garbage value by the compiler.
• Its lifetime is within the block where the variable is defined.
• auto keyword is optional.
Syntax: auto datatype var1, var2……var n;
Example:
#include<stdio.h>
int main()
{
auto int x,y;
x=10;y=20;
printf(“Sum=%d”,x+y);
}

Output:
Sum=30
2.Register:
• These variables will be stored in CPU registers instead of RAM.
• By default they are assigned a garbage value by the compiler.
• Its lifetime is local to the function in which it is declared.
• Register variables has faster access than normal variables.
Syntax: register datatype var1, var2……var n;
Example:
#include<stdio.h>
int main()
{
register int x,y;
x=10;y=20;
printf(“Sum=%d”,x+y);
}

Output:
Sum=30
3.Static:
• Static modifier may also be applied to global variables.
• Initial value of static variable is zero.
• Static variables have a lifetime over the entire program.
• Static variables maintains its value between any number of calls of the function in which it is declared.
Syntax: static datatype var1, var2,…….varn;
Example: static int a,b;
#include<stdio.h>
void Increment();
int main()
{
Increment();
Increment();
return 0;
}
void Increment()
7
{
static int i=0;
printf(“%d”,i);
i++;
}
Output:
01
4. Extern:
The external variables are declared out of the main() function the availability of these variables are throughout
the program and that is both in main program and inside the user defined functions.
Syntax: Storage_class_type data_type var1, var2,……var n;
Example: extern int a, b;

Q5: OPERATORS: (16 Marks or 8 Marks)


An operator is as symbol that specifies the mathematical, logical or relational operation to be performed on
the operands. The data items are called operands.
Example: a+b
‘+’ operator and a, b are the operands.

Types of operators:
1) Arithmetic Operator (+, -,*,/,%,)
2) Relational Operator (<,>,<=,>=)
3) Equality Operators (==,!=)
4) Logical Operators (&&.||,!)
5) Unary Operators (-, ++, --)
6) Conditional (or) Ternary Operator (?: )
7) Bitwise Operator (&,!,|,^,<<,>>)
8) Assignment Operators (=, +=, -=, *=, /=, %=)
9) Comma Operator (,)
10) sizeof Operator (sizeof()))
1) Arithmetic operators:
Arithmetic operator are, +(Addition), -(Subtraction), *(Multiplication), /(Division) and %(Modulo). It can be applied
to any integer or floating point number.
int a=10,b=5,Add,Sub,Mul,Div,Mod;
Operator Operation Syntax Example Result
+ Addition a+b Add=a+b; 15
- Subtraction a-b Sub=a-b; 5
* Multiplication a*b Mul=a*b; 50
/ Division a/b Div=a/b; 2
% Modulo a%b Mod=a%b; 0

Example:
//Arithmetic Operators
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,Add,Sub,Mul,Div,Mod;
clrscr();
printf("Arithmetic Operators");
printf("\nEnter the A & B Value:");
scanf("%d%d",&a,&b);
8
printf("A=%d\nB=%d",a,b)
Add=a+b;
printf("\nAddition = %d",Add);
Sub=a-b;
printf("\nSubtraction = %d",Sub);
Mul=a*b;
printf("\nMultiplication = %d",Mul);
Div=a/b;
printf("\nDivision = %d",Div);
Mod=a%b;
printf("\nModulo = %d",Mod);
getch();
}

2) Relational operators:
• Relational operators are also known as comparison operators, to compare two or more operands.
• Operands may be variables, constants or expression.
• The value of relational expression is either one(true) or zero(false).
• Relational operators are used in decision making process.

int a=10,b=20;
Operator Operation Syntax Example Result
> Greater than a>b if(a>b) 0
< Less than a<b if(a<b) 1
Greater than
>= a>=b if(a>=b) 0
Equal to
Less than
<= a<=b if(a<=b) 1
Equal to
Example:
//Biggest among two numbers using Relational Operators
#include<stdio.h>
#include<conio.h>
int main()
{
int a,b,c;
clrscr();
printf("Relational Operators");
printf("\nEnter the A & B Value:");
scanf("%d%d",&a,&b);
if(a>b)
printf("\A is big”);
else
printf(“\nB is big”);
return 0;
}
OUTPUT:
Relational Operators
Enter the A & B Value:9
5
A is big

9
3) Equality Operator:
C language supports two kinds of equality operators to compare their operands. They are, Equal to(==) and
Not Equal to (!=).
Assume, int a=10,b=20;
Operator Operation Syntax Example Result
== Equal to a==b If(a==b) 0
!= Not Equal to A!=b If(a!=b) 1

4) Logical operators:
C language supports three logical operators 1) logical AND(&&) 2) logical OR(||) 3) logical Not(!). Logical
operators are used to combine the results of two or more conditions.

Truth Table for Logical AND Truth Table for Logical OR Truth Table for Logical Not
A B A&&B A B A||B A !A
0 0 0 0 0 0 0 1
0 1 0 0 1 1 1 0
1 0 0 1 0 1
1 1 1 1 1 1

Syntax: (exp1)&&(exp2)

Example A=9, B=5, C=12


Operator Operation Syntax Example Result
&& Logical AND (a>b)&&(a>c) If((a>b)&&(a>c)) 0
|| Logical OR (a>b)||(a>c) If((a>b)||(a>c)) 1
! Logical Not !(a>b) If(!(a>b)) 0
Example:
//Biggest among three numbers using Logical Operators
#include<stdio.h>
#include<conio.h>
int main()
{
int a,b,c;
clrscr();
printf(“Logical Operators”);
printf("\nEnter the a,b & c Value:");
scanf("%d%d%d",&a,&b,&c);
if((a>b)&&(a>c))
printf(“A is big”);
else if(b>c)
printf(“B is big”);
else
printf(“C is big”);
return 0;
}
OUTPUT:
Logical Operators
Enter the a,b & c Value:
9
5
2
A is big

10
5)Unary Operator:
Unary minus(-):
When an operand is preceded by a minus sign, the unary operator negates its value.
Example: int a, b=10;
a=-(b);
printf(“%d\”,a); //a produces -10

Increment Operator(++) and Decrement Operator(--):


It increases the value of its operand by 1. Decrement Operator decreases the value of its operand by 1.
Example: int x=10, y;
y=++x;
Now y produces 11.

6) Conditional operator:
It is like as if…else statement. It checks the condition and executes the statement depending on the condition.
Syntax:
Exp1?exp2:exp3;
Example:
int a=5,b=3,big;
big=a>b?a:b;

Program to find min among 2 numbers:


#include<stdio.h>
int main()
{
int a,b,min;
printf(“Enter 2 numebrs:”);
scanf(“%d%d”,&a,&b);
min=(a>b)?a:b;
printf(“Min data is:%d”,min);
return 0;
}

7) Bitwise operators:
It is perform operations at bit level. It operates on integer only. It may not be applied to float or real.

Truth Table for,


Bitwise AND Bitwise OR Bitwise Not Bitwise XOR
A B A&B A B A|B A !A A B A^B
0 0 0 0 0 0 0 1 0 0 0
0 1 0 0 1 1 1 0 0 1 1
1 0 0 1 0 1 1 0 1
1 1 1 1 1 1 1 1 0

a) Bitwise AND(&):
This operator is represented as ‘&’ and operates on two operands of integer type.
Example:
10101010&
01010101
=00000000

b) Bitwise OR(|):
Example:
10101010|
01010101
=11111111

11
c) Bitwise exclusive OR(^):
Example:
10101010^
01010101
=11111111

d) Bitwise Not:
Example: ~101010111
=010101000

e) Shift Operator:
C supports two bitwise shift operators. They are shift-left(<<) and shift right(>>).These operators shifts bits
either left or to the right.
Example:
x=0001 1101
x << 1;
x => 0 0 0 1 1 1 0 1
x<<1 => 0 0 1 1 1 0 1 0

x => 0 0 0 1 1 1 0 1
x << 4 => 1 1 0 1 0 0 0 0

x => 0 0 0 1 1 1 0 1
x >> 1 => 0 0 0 0 1 1 1 0

x => 0 0 0 1 1 1 0 1
x >>4 => 0 0 0 0 0 0 0 1

8) Assignment operators:
Simple Assignment operators are used to assign a value or an expression result to a variable.
Example: x=5;
Compound assignment operators to assign a value to a variable in order to assign a new value to a variable
after performing a specified operation. Compound assignment operators are, +=, -=, *=, /=, %=.
Example: int x=10,y=20;
x+ = y; produces x=30

9) Comma operator(,):
It takes two operands. It is used to separate the statement elements such as variables, constants or expression
etc. It works by evaluating the first and discarding its value and then evaluates the second and returns the value as the
result of the expression.
Example:
int a=2,b=3,x=0;
x=(++a,b+=a); produces x=>6

10. Sizeof() operator:


It is a unary operator, used to calculate the size of the data types or variables. It is a compile time operator.
Syntax:
sizeof(var);
Example:
int main()
{
int a;
printf(“size of variable a is……..%d”, sizeof(a));
return 0;
}
Output:
size of variable a is…………2.

12
Operator Precedence & Associativity:
Precedence Operator Description Associativity
1 ++ -- Suffix/postfix increment and Left-to-right
decrement
() Function call
2 ++ -- Prefix increment and decrement Right-to-left
+- Unary plus and minus
!~ Logical NOT and bitwise NOT
sizeof Size-of[note 1]

3 */% Multiplication, division, and Left-to-right


remainder
4 +- Addition and subtraction
5 << >> Bitwise left shift and right shift

6 == != For relational = and ≠ respectively


7 && Logical AND
8 || Logical OR
9 ?: Ternary conditional[note 3] Right-to-Left
10 =, +=, -= assignment
11 , Comma Left-to-right

Q6: PREPROCESSORS:

The various preprocessor directives available in C language are as follows:


1. Macro replacement directive (#define, #undef)
2. Source file inclusion directive (#include)
3. Line directive (#line)
4. Error directive (#error)
5. Pragma directive (#pragma)
6. Conditional compilation directives (#if, #else, #elif, #endif, #ifdef, #ifndef)
7. Null directive (#new-line)

1. Macro Replacement Directives:


Object-like Macros: (#define)
It is also known as symbolic constant. It is defined as,
#define macro-name replacement-list
Example:
#include<stdio.h>
define pi 3.14
void main()
{
int r;
printf("Enter r:");
scanf("%d",&r);
printf("Area of circle : %f",pi*r*r);
}
Function – like Macro : (#define)
A macro with arguments is called a function-like macro. Its usage is syntactically similar to a function call. It
can be defined as,
#define macro-name(parameter-list) replacement-list
13
Example:
#include<stdio.h>
#define square(x) x*x
void main()
{
int x;
printf("Enter a number:");
scanf("%d",&x);
printf("Square : %d",square(x));
}

2. Source File Inclusion Directive: (#include)


It tells the preprocessor to replace the directive with the content of the file specified in the directive. It can be
written as,
a. #include<filename>
b. #include “filename”
c. #include token-sequence
Example:
// File name areaofcir.c
#include<stdio.h>
void disp()
{
float r,pi;
pi=3.14;
printf("Enter r:");
scanf("%f",&r);
printf("Area of circle : %f",pi*r*r);
}
//Filename areadisp.c
#include "areaofcir.c"
void main()
{
disp();
}

3. Line directive: (#line)


It is used to reset the line number and the file name as reported by __LINE__ and __FILE__ macros. It
defined as,
#line constant
#line constant “filename”
Example:
#include<stdio.h>
void main()
{
printf("Line number is : %d File name is : %s\n", __LINE__,__FILE__);
#line 200
printf("Line number is : %d File name is : %s\n", __LINE__,__FILE__);
}
4. Error directive: (#error)
It causes the preprocessor to generate the customized diagnostic messages and causes the compilation to fail.
It defined as,
#error
#error token-sequence
Example:
#include<stdio.h>
#error User defined error messages
void main() { printf("Compilation Failed:"); }
14
5. Pragma directive: (#pragma)
It is used to specify diverse options to the compiler. The options are specific for the compiler and the platform
used. It is written as,
#pragma token-sequence
#pragma option
Some pragma options available with Turbo C 3.0,
S.No Options Role
1 -C Allows nested comments
2 -C- Doesn’t allows nested comments in fav
3 -r Enables the use of register variables
4 -r- Suppresses the use of register variables

Example:
#include<stdio.h>
void main()
{
/* Program without #pragma
/* To display Welcome msg*/
*/
printf("Welcome");
} Output : Error message

#include<stdio.h>
#pragma option -C
void main()
{
/* Program with #pragma
/* To display Welcome msg*/
*/
printf("Welcome");
}
Output : Welcome

6. Conditional Compilation Directives:


Program is compiled only if a certain condition comes out to be true. The available conditional compilation
directives are as follows,
#if, #ifdef, #ifndef, #else, #elif, #endif
Example:
#include<stdio.h>
#define pi
void main()
{
#ifdef pi
printf("PI - defined");
#else
printf("PI - undefined");
#endif
}

7. Null Directive
It is defined as, #new-line
The null directive has no effect.

15
Q7: INPUT AND OUTPUT STATEMENTS:
Input means to provide the program with some data to be used in the program and Output means to display
data on screen or write the data to a printer or a file.
C programming language provides many built-in functions to read any given input and to display data on
screen when there is a need to output the result.
There are two types of I/O Statements in C,
1. Formatted I/O Statements
2. Unformatted I/O Statements

1. Formatted I/O Statements:


scanf() and printf() functions
The standard input-output header file, named stdio.h contains the definition of the functions printf() and
scanf(), which are used to display output on screen and to take input from user respectively.

Example:
#include<stdio.h>
void main()
{
int i;
printf("Please enter a value...");
scanf("%d", &i);
printf( "\nYou entered: %d", i);
}
When you will compile the above code, it will ask you to enter a value. When you will enter the value, it will
display the value you have entered on screen.
In the above program, %d is known as format string and this informs the scanf() function, what type of input
to expect and in printf() it is used to give a heads up to the compiler, what type of output to expect.
Format String Meaning
%d Scan or print an integer as signed decimal number
%f Scan or print a floating point number
%c To scan or print a character
%s To scan or print a character string. The scanning ends at whitespace.
We can also limit the number of digits or characters that can be input or output, by adding a number with the
format string specifier, like "%1d" or "%3s", the first one means a single numeric digit and the second one means 3
characters, hence if you try to input 42, while scanf() has "%1d", it will take only 4 as input. Same is the case for
output.
In C Language, computer monitor, and files are output devices, same process is followed to write output to
these devices.
NOTE : printf() function returns the number of characters printed by it, and scanf() returns the number of
characters read by it.

int i = printf("Welcome");

In this program printf("Welcome"); will return 7 as result, which will be stored in the variable i, because
“Welcome” has 7 characters.

2. Unformatted I/O Statements:


getchar() & putchar() functions
The getchar() function reads a character from the terminal and returns it as an integer. This function reads
only single character at a time. To read more than one character, loops can be used.
The putchar() function displays the character passed to it on the screen and returns the same character. This
function too displays only a single character at a time. To display more than one characters, use putchar() method in a
loop.

16
#include <stdio.h>
void main( )
{
int c;
printf("Enter a character");
c = getchar();
putchar(c);
}

gets() & puts() functions


The gets() function reads a line from stdin(standard input) into the buffer pointed to by str pointer, until either
a terminating newline or EOF (end of file) occurs. The puts() function writes the string str and a trailing newline to
stdout.
str → This is the pointer to an array of chars where the C string is stored.

#include<stdio.h>
void main()
{
/* character array of length 100 */
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}

Difference between scanf() and gets()


The main difference between these two functions is that scanf() stops reading characters when it encounters a
space, but gets() reads space as character too.

If you enter name as Wel come using scanf() it will only read and store “Wel” and will leave the part after
space. But gets() function will read it completely.

17
UNIT II ARRAYS AND STRINGS
Q1: ARRAYS
Definition
An array is a collection of similar data elements. These data elements have the same data type. The
elements of the array are stored in consecutive memory locations and are referenced by an index.

The syntax for array is:

Syntax:
Datatype name[size];
Example:
int Marks[7];
80 86 85 87 95 94 99
Marks[0] Marks[1] Marks[2] Marks[3] Marks[4] Marks[5] Marks[6]

Classification of array:
Arrays can be classified into major types.
1. One-dimensional Array or single dimensional Array Ex: a[10];
2. Two dimensional Array. Ex: a[2][2];
3. Multi dimensional Array. Ex: a[2][2][2];

Storing Values In Arrays:


Initializing Arrays during Declaration:
Elements of the array can also be initialized at the time of declaration as other variables. When an
array is initialized, we need to provide value for every element in the array. Arrays are initialized by writing,
type array_name[size]={list of values};
Example,
int Marks[7]={99,87,78,89,88,86,95};
99 87 78 89 88 86 95
Marks[0] Marks[1] Marks[2] Marks[3] Marks[4] Marks[5] Marks[6]

Inputting values from the keyboard:


An array can be filled by inputting values from the keyboard. In this method, a while/do-while or a
for loop is executed to input the value for each element of the array.
Example:
int mark[7],i;
for(i=0;i<7;i++)
scanf(%d”,&mark[i]);

Accessing the elements of an array:


int i,marks[10];
for(i=0;i<10;i++)
marks[i]=-1;
Calculating the address of array element:
A[k]=BA(A)+w(k-lower_bound)
Ex: Address of marks[4]=1000+2(4-0)
=1008
Calculating the Length of an Array:
length=upper_bound-lower_bound+1
18
Example 1: //Program to sum of elements in an array.
#include<stdio.h>
int main()
{
int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};
int sum=0;
for (int i=0; i<9; i++) Output:
{ Sum=174
sum=sum+arr[i];
}
printf("Sum=%d ",sum);
}

Example 2: // Program to find average of n numbers using array


#include<stdio.h>
int main()
{
int a[25],n,i;
float sum=0; Output:
printf(“Enter no of inputs:”); Enter 5
scanf(“%d”,&n); elements:
printf("Enter %d elements:",n); 23457
for(i=0;i<n;i++) Average=4.2
scanf("%d",&a[i]);
for(i=0;i<n;i++)
sum=sum+a[i];
printf("Average=%f\n",sum/5);
}

Example 3: Program to find mead, median and mode of an array:


#include<stdio.h>
int main()
{
int a[7]={1,2,2,4,5,2,5},i,j,mid,sum=0,m[7]={0},maxCount=0,modeValue=0;
//Mean
for(i=0;i<7;i++)
sum=sum+a[i];
printf("Mean=%f",(float)sum/7);
//Median
mid=7/2;
printf("\nMedian=%d",a[mid]);
//Mode Output:
for (i = 0; i < 7; i++) Mean = 3
{ Median=4
for(j=i+1;j<7;j++) Mode=2
{
if(a[i]==a[j])
m[i]++;
}
}

19
for (i = 0; i < 7; i++)
{
if (m[i] > maxCount)
{
maxCount = m[i];
modeValue = a[i];
}
}
printf("\nMode value is : %d", modeValue);
}

Q2: Searching for a value in an Array:


Searching means to find whether a particular value is present in an array or not. If the value is
present in the array then searching is said to be successful and the searching process gives the location of
that value in the array.
There are two searching methods,
1. Linear search
2. Binary search

Linear Search:

Program to Search for an element in an Array.


#include <stdio.h>
int main() OUTPUT:
{ Enter the no. of elements in
int a[25],i,j,n,x; the array 4
printf("\nEnter the no. of elements in the array");
scanf("%d",&n); Enter the elements in the
array
printf("\nEnter the elements in the array\n"); 2
for(i=0;i<n;i++) 1
{ 4
scanf("%d",&a[i]); 5
} Enter the element to be
printf("\nEnter the element to be searched in the array"); searched in the array 2
scanf("%d",&x); The element is found in
for(i=0;i<n;i++) position 1.
{
if(a[i]==x)
{
printf("\nThe element is found in position %d.",i+1);
break;
}
}
if(i==n)
{
printf("\nThe element is not found");
}
}

20
Binary Search:
In Binary search, the original list has to be sorted, and then the search for an element takes place
using divide and conquers technique. The list is divided into two halves separated by the middle element as
shown below:
low (low+high)/2 high

Program to search an element in the array using Binary Search:


#include<stdio.h>
int main()
{
int a[10],i,n,x,c=0,low,high,mid;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements in ascending order: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the number to be searched: ");
scanf("%d",&x);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(x==a[mid])
{
c=1;
break;
}
else if(x<a[mid])
high=mid-1;
else
low=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is found at : %d.",a[mid]);
}

Q3: 2D ARRAY:
A two dimensional array is specified using two subscripts where one subscript denotes row and the
other denotes column. It is also called as matrix.
Syntax:
datatype name[rowsize][columnsize];
Example:
int arr[2][3]={{45,34,56},{65,76,87}};
00 01 02

45 34 56
10 11 12

65 76 87

21
Example1: //Sum of two matrices
#include<stdio.h>
int main()
{
int a[3][3],b[3][3],c[3][3],i,j;
printf("Enter 9 elements for first matrix:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]); Output:
} Enter 9 elements for first
} matrix:
printf("Enter 9 elements for second matrix:"); 123
for(i=0;i<3;i++) 234
{ 121
for(j=0;j<3;j++) Enter 9 elements for second
{ matrix:
scanf("%d",&b[i][j]); 235
} 321
} 123
for(i=0;i<3;i++) Resultant matrix:
{ 358
for(j=0;j<3;j++) 555
{ 244
c[i][j]=a[i][j]+b[i][j];
}
}
printf("Resultant matrix:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
}

Example 2: Program to Display transpose of a given matrix.


#include<stdio.h>
int main()
{
int a[3][3],i,j,k; Output:
printf("Enter 9 elements for first matrix:"); Enter 9 elements for first matrix:
for(i=0;i<3;i++) 123
{ 456
for(j=0;j<3;j++) 789
{ Resultant matrix:
scanf("%d",&a[i][j]); 147
} 258
} 369
printf("Resultant matrix:\n");
22
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",a[j][i]);
}
printf("\n");
}
}
Q4: Program to scale a given matrix.
#include<stdio.h>
int main()
{
int a[3][3]={1,1,1,2,2,2,3,3,3},i,j,k;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a[i][j]=a[i][j]+3;
}
}
printf("Resultant matrix:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
}
Q5: Program to find Determinant of 2X2 matrix:
#include<stdio.h>
int main()
{
int a[2][2],i,j;
long determinant;
printf("Enter the 4 elements of matrix: ");
Output:
for(i=0;i<2;i++)
Enter the 4 elements of matrix: 4
for(j=0;j<2;j++)
8
scanf("%d",&a[i][j]);
3
printf("\nThe matrix is\n");
9
for(i=0;i<2;i++)
{
The matrix is
printf("\n");
for(j=0;j<2;j++)
4 8
printf("%d\t",a[i][j]);
3 9
}
determinant = a[0][0]*a[1][1] - a[1][0]*a[0][1];
Determinant of 2X2 matrix: 12
printf("\nDeterminant of 2X2 matrix: %ld",determinant);
return 0; }

23
Q6: Program to multiply two matrices.
#include <stdio.h>
#include <conio.h>
int main()
{
int a[3][3],b[3][3],c[3][3],i,j,k;
clrscr();
printf("\nEnter the elements in the matrix A");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}
printf("\nEnter the elements in the matrix B");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&b[i][j]); OUTPUT:
} Enter the elements in the matrix A
for(i=0;i<3;i++) 1
{ 1
for(j=0;j<3;j++) 1
{ 1
c[i][j]=0; Enter the elements in the matrix B
for(k=0;k<3;k++) 1
{ 1
c[i][j]=c[i][j]+a[i][k]*b[k][j]; 1
} 1
} The Resultant matrix is
} 2 2
printf("\nThe Resultant matrix is\n"); 2 2
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}

24
Q7: STRINGS
A string is a null-terminated character array. All the characters of a string are stored in successive
memory locations.
Syntax: char str[6]="HELLO";

Reading Strings
Then str can be read by the user in three ways:
1. using scanf function,
Syntax:scanf("%s", str);
2. using gets() function
Syntax:gets(str);
3. using getchar()
i=0;
ch = getchar;// Get a character
while(ch != '*')
{
str[i] = ch;// Store the read character in str
i++;
ch = getchar();// Get another character
}
str[i] = '\0';// Terminate str with null character

Writing Strings
Strings can be displayed on the screen using the following three ways:
1. using printf() function,
Syntax: printf("%s", str);
For example,
printf ("%5.3s", str);
The above statement would print only the first three characters in a total field of five characters. Also
these characters would be right justified in the allocated width.
To make the string left justified, we must use a minus sign.
For example, printf ("%–5.3s", str);
2. using puts() function
Syntax: puts(str);

3. using putchar() function


Syntax:
i=0;
while(str[i] != '\0')
{
putchar(str[i]);// Print the character on the screen
i++;
}

25
OPERATIONS ON STRINGS
1. Finding Length of a String
2. Concatenate two strings
3. Appending a String to Another String
4. Comparing two strings
5. Copying one string into another string

Finding Length of a String


The number of characters in a string constitutes the length of the string. For example,
LENGTH("C.PROGRAMMING IS FUN") will return 20. Blank spaces are counted as characters in the
string.

//Write a program to find the length of a string.


#include <stdio.h>
#include <conio.h>
int main()
{
char str[100], i = 0, length;
clrscr();
printf("\n Enter the string : ");
gets(str)
while(str[i] != '\0')
i++;
length = i; Output
printf("\n The length of the string is : %d", length); Enter the string :
return 0; HELLO
} The length of the
string is : 5
Concatenate two strings
If s1 and s2 are two strings then concatenation operation produces a string which contains
characters of s1 followed by characters of s2.

#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char str1[6],str2[6],str3[6],ch;
int i=0,j=0;
printf("enter string");
gets(str1);
gets(str2);
while(str1[i]!='\0')
{
str3[j]=str1[i];
i++;
j++;
}
i=0;
while(str2[i]!='\0')
{
str3[j]=str2[i];
j++;
26
i++;
}
str3[j]='\0';
puts(str3);
return 0;
}

Appending a String to Another String


Appending one string to another string involves copying the contents of the source string at
the end of the destination string.
For example, if S1 and S2 are two strings, then appending S1 to S2 means we have to add the
contents of S2 to S1. So, S1, S2 are the source strings and S1 is the destination string S1 = S1 + S2.
The library function strcat(s1, s2) which is defined in string.h concatenates string s2 to s1.

Program to append a string to another string.


#include <stdio.h>
int main()
{
char Str1[100], Str2[50];
int i=0, j=0;
printf("\n Enter the source string : ");
gets(Str2);
printf("\n Enter the destination string : ");
gets(Str1);
while(Str1[i] != '\0')
{
i++;
}
while(Str2[j] != '\0') Output
{ Enter the source string : How are you?
Str1[i] = Str2[j]; Enter the destination string : Hello,
i++; After appending, the destination string is : Hello,
j++; How are you?
}
Str1[i] = '\0';
printf("\n After appending, the destination string is : ");
puts(Str1);
return 0;
}

Comparing Two Strings


If S1 and S2 are two strings, then comparing the two strings will give either of the following
results:
(a) S1 and S2 are equal
(b) S1>S2, when in dictionary order, S1 will come after S2
(c) S1<S2, when in dictionary order, S1 precedes S2

To compare the two strings, each and every character is compared from both the strings. If all
the characters are the same, then the two strings are said to be equal. Figure 4.6 shows an algorithm that
compares two strings.The library function strcmp(s1, s2) which is defined in string.h compares string s1
with s2.

//Write a program to compare two strings.


27
#include <stdio.h>
#include <string.h>
int main()
{
char Str1[100], Str2[100];
int result, i;

printf("\n Please Enter the First String : ");


gets(Str1);

printf("\n Please Enter the Second String : ");


gets(Str2);

for(i = 0; Str1[i] == Str2[i] && Str1[i] != '\0'; i++);

if(Str1[i] < Str2[i])


{
printf("\n str1 is Less than str2");
}
else if(Str1[i] > Str2[i])
{
printf("\n str2 is Less than str1");
}
else
{
printf("\n str1 is Equal to str2");
}

return 0;
}
Copying one String into another
//C program to copy one string to another string using while loop
#include <stdio.h>
int main()
{
char text1[100];
char text2[100];
int i;
printf("Enter any string: ");
gets(text1);
i=0;
while(text1[i] != '\0')
{
text2[i] = text1[i];
i++;
}
text2[i] = '\0';
printf("First string = %s\n", text1);
printf("Second string = %s\n", text2);
printf("Total characters copied = %d\n", i);
return 0;
}

28
Q8: String Functions

1.strcat
Strcat function appends the string pointed by str2 to end of string pointed to by str1.
Syntax: char *strcart(char *str1,const char *str2)
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "This is ", str2[] = " a C program”;
//concatenates str1 and str2 and resultant string is stored in str1.
strcat(str1,str2);
puts(str1);
puts(str2);
return 0;
}
Output
This is a C program
a C program

2.strcmp
Strcmp function compares the string pointed to by str2.The function returns zero if strings are
equal.Else it returns a value less than zero or greater than zero.
Syntax: int strcmp(const char *str1,const char *str2);
//PROGRAM TO COMPARE TWO STRINGS
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
Output
// comparing strings str1 and str2 strcmp(str1, str2)
result = strcmp(str1, str2); = 32
printf("strcmp(str1, str2) = %d\n", result); strcmp(str1, str3)
=0
// comparing strings str1 and str3
result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);
}

3.strcpy
This function copies string pointed to by str2 to str1 including the null character of str2.It
returns the argument str1.
Syntax:char *strcpy(const char *str1,const char *str2);
#include <stdio.h>
#include <string.h>
int main()
{
char str1[10]= "awesome";
char str2[10];
char str3[10];
strcpy(str2, str1); Output
awe
29
some
strcpy(str3, "well");
puts(str2);
puts(str3);
return 0;
}
4.strlen
The function calculates the length of string str up to not including the null character.
Syntax: size_t strlen(const char *str);
#include <stdio.h>
#include <string.h>
int main()
{
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
char c[20];
printf("Enter string: ");
gets(c);
printf("Length of string a = %d \n",strlen(a));
//calculates the length of string before null charcter.
printf("Length of string b = %d \n",strlen(b));
printf("Length of string c = %d \n",strlen(c));
return 0;
}

Output
Enter string: String
Length of string a = 7
Length of string b = 7
Length of string c = 6

Q9: SELECTION SORT


Selection sort is a sorting algorithm that has a quadratic running time complexity of O(n2),
thereby making it inefficient to be used on large lists. Although selection sort performs worse than insertion
sort algorithm, it is noted for its simplicity and also has performance advantages over more complicated
algorithms in certain situations. Selection sort is generally used for sorting files with very large objects
(records) and small keys.
Technique
Consider an array ARR with N elements. Selection sort works as follows:
First find the smallest value in the array and place it in the first position. Then, find the
second smallest value in the array and place it in the second position. Repeat this procedure until the entire
array is sorted. Therefore,
➢ In Pass 1, find the position POS of the smallest value in the array and then swap ARR[POS] and
ARR[0]. Thus, ARR[0] is sorted.
➢ In Pass 2, find the position POS of the smallest value in sub-array of N–1 elements. Swap
ARR[POS] with ARR[1]. Now, ARR[0] and ARR[1] is sorted.
➢ In Pass N–1, find the position POS of the smaller of the elements ARR[N–2] and ARR[N–1]. Swap
ARR[POS] and ARR[N–2] so that ARR[0], ARR[1], ..., ARR[N–1] is sorted.

30
Complexity of Selection Sort
In Pass 1, selecting the element with the smallest value calls for scanning all n elements;thus,
n–1 comparisons are required in the first pass. Then, the smallest value is swapped with theelement in the
first position. In Pass 2, selecting the second smallest value requires scanning theremaining n – 1 elements
and so on. Therefore,
(n – 1) + (n – 2) + ... + 2 + 1 = n(n – 1) / 2 = O(n2) comparisons

Advantages of Selection Sort


✓ It is simple and easy to implement.
✓ It can be used for small data sets.
✓ It is 60 per cent more efficient than bubble sort.

//Write a program to sort an array using selection sort algorithm.


#include<stdio.h>
int main()
{
int i, j, count, temp, number[25];
printf("How many numbers u are going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
for(i=0;i<count;i++)
{
for(j=i+1;j<count;j++)
{
if(number[i]>number[j])
{
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
printf("Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}

31
Extra:
Q1: Operations on Arrays:
Traversing an Array:
Traversing an array means accessing each and every element of the array for a specific purpose.
Traversing includes,
1. Printing every element.
2. Counting the total number of elements.
3. Finding min, max etc.

Program to find the duplicate numbers in an Array.


#include <stdio.h> OUTPUT:
int main() Enter the no. of elements in
{
the array4
int a[25],i,j,n,sum=0;
printf("\nEnter the no. of elements in the array"); Enter the elements in the
scanf("%d",&n); array
printf("\nEnter the elements in the array\n");
for(i=0;i<n;i++) 4
{ 3
scanf("%d",&a[i]);
2
}
for(i=0;i<n;i++) 1
{ No Duplicate
for(j=i+1;j<n;j++)
{
if(a[i]==a[j]&&i!=j)
{
flag=1;
printf(“Duplicate numbers found at locations %d and %d,i,j);
}
}
}
if(flag==0)
printf("\nNo Duplicate”);
return 0;
}

Program to find the Largest element in an Array.


#include <stdio.h> Output:
#include <conio.h>
int main() Enter the no. of elements in the array4
{ Enter the elements in the array
int a[25],i,n,max;
clrscr(); 6
printf("\nEnter the no. of elements in the array"); 7
scanf("%d",&n);
printf("\nEnter the elements in the array\n"); 50
for(i=0;i<n;i++) 45
{
scanf("%d",&a[i]); The largest element is 50
}
max=a[0];
for(i=1;i<n;i++)
32
{
if(max<a[i])
max=a[i];
}
printf("\nThe largest element is %d",max);
return 0;
}

Inserting an Element in an array:


Inserting an element in an array means, adding a new data element to an already existing array.
If the element has to be inserted at the end of the existing array, then we just have to add 1 to the
upper_bound and assign the value.
To add in mid, a while loop is executed which will move all the elements that have index greater than pos
on position towards right to create space for the new element.

Program to insert an element into an Array.


#include <stdio.h>#include<conio.h>
int main()
{
int a[30],i,n,x,p;
clrscr();
printf("\nEnter the size of the array");
scanf("%d",&n);
printf("\nenter the elements into the array");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the element to be inserted");
scanf("%d",&x);
printf("\nEnter the position in which the element to be inserted");
scanf("%d",&p);
for(i=n-1;i>=p;i--) OUTPUT:
a[i+1]=a[i]; Enter the size of the array 5
a[p]=x; enter the elements into the array
printf("\nThe elements are \n"); 3 4 5 2 1
for(i=0;i<=n;i++) Enter the element to be inserted 6
printf("%d\t",a[i]); Enter the position in which the element to
return 0; be inserted 3
} The elements are 3 4 5 6 2
1

Deleting an Element from an Array:


Deleting an element from an array means removing a data element from an already existing array.
To delete at end, just subtract 1 from upper_bound.
To delete at mid, a while loop is executed which will move all the elements that have index greater
than pos one location towards left to occupy the location vacated by the deleted element.

Program to delete elements:


#include <stdio.h>
int main()
{
int arr[25],i,n,max,pos;
printf("\nEnter the no. of elements in the array");
33
scanf("%d",&n);
printf("\nEnter the elements in the array\n");
Output:
for(i=0;i<n;i++)
{ Enter the no. of elements in the
scanf("%d",&arr[i]);
array4
}
printf(“Enter the pos, that the data to be deleted:”); Enter the elements in the array
scanf(“%d”,&pos
6
for(i=pos;i<n-1;i++)
{ 7
arr[i]=arr[i+1];
50
}
n--; 45
printf("\nThe array is:”);
for(i=0;i<n;i++)
printf(“%d\t”,arr[i]); The largest element is 50
return 0;
}

34
UNIT III FUNCTIONS AND POINTERS
Introduction to functions: Function prototype, function definition, function call, Built-in
functions (string functions, math functions) – Recursion – Example Program: Computation of Sine series,
Scientific calculator using built-in functions, Binary Search using recursive functions – Pointers – Pointer
operators – Pointer arithmetic – Arrays and pointers – Array of pointers – Example Program: Sorting of
names – Parameter passing: Pass by value, Pass by reference – Example Program: Swapping of two
numbers and changing the value of a variable using pass by reference.

Q1: FUNCTIONS

Definition
C enables its programmers to break up a program into segments commonly known as functions.
Every function in the program is supposed to perform a well-defined task. Therefore, the program
code of one function is completely insulated from the other functions.

main() calls a function named func1(). Therefore, main() isknown as the calling function and
func1() is known as the called function.

Need For Functions:


Functions are used because of following reasons –
a) To improve the readability of code.
b) Improves the reusability of the code, same function can be used in any program rather than
writing the same code from scratch.
c) Debugging of the code would be easier if you use functions, as errors are easy to be traced.
d) Reduces the size of the code, duplicate set of statements are replaced by function calls.

Terminologies In Functions
A function f that uses another function g is known as the calling function, and g is known as the
called function.
The inputs that a function takes are known as arguments.
When a called function returns some result back to the calling function, it is said to return
that result.
The calling function may or may not pass parameters to the called function. If the called
function accepts arguments, the calling function will pass parameters, else not.
Function declaration is a declaration statement that identifies a function’s name, a list of
arguments that it accepts, and the type of data it returns.
Function definition consists of a function header that identifies the function, followed by the body
of the function containing the executable code for that function.

35
Function Declaration
The general format for declaring a function that accepts arguments and returns a value as
result can be given as:

return_data_type function_name(data_type variable1, data_type variable2,..);

o function_name - is a valid name for the function. Naming a function follows the same rules
that are followed while naming variables. A function should have a meaningful name that
must specify the task that the function will perform.
o return_data_type - the data type of the value that will be returned to the calling function as
a result of the processing performed by the called function.
o (data_type variable1, data_type variable2, ...) - is a list of variables of specified data types.
These variables are passed from the calling function to the called function. They are also
known as arguments or parameters that the called function accepts to perform its task.

Function Definition
When a function is defined, space is allocated for that function in the memory. A function
definition comprises of two parts:
• Function header
• Function body
The syntax of a function definition can be given as:
return_data_type function_name(data_type variable1, data_type variable2,..)
{
.............
statements
.............
return(variable);
}

return_data_type function_name(data_type variable1, data_type variable2,...) is known as the


function header, the rest of the portion comprising of program statements within the curly brackets { } is the
function body which contains the code to perform the specific task.
The number of arguments and the order of arguments in the function header must be the same as that
given in the function declaration statement.
The function header is same as the function declaration. The only difference between the two is that
a function header is not followed by a semi-colon.

Function Call
The function call statement invokes the function. When a function is invoked, the compiler jumps to
the called function to execute the statements that are a part of that function. Once the called function is
executed, the program control passes back to the calling function. A function call statement has the
following syntax:
function_name(variable1, variable2, ...);

If the return type of the function is not void, then the value returned by the called function
may be assigned to some variable as given below.
variable_name = function_name(variable1, variable2, ...);

36
Eg:// program to find whether a number is even or odd using functions.
#include <stdio.h>
int evenodd(int); //FUNCTION DECLARATION
int main()
{
int num, flag;
printf("\n Enter the number : ");
scanf("%d", &num);
flag = evenodd(num); //FUNCTION CALL
if (flag == 1)
printf("\n %d is EVEN", num);
else
printf("\n %d is ODD", num);
return 0;
}
int evenodd(int a) // FUNCTION HEADER
{
// FUNCTION BODY

if(a%2 == 0)
return 1;
else
retun 0;
}
Output:
Enter the number : 78
78 is EVEN
Q2. PASSING PARAMETERS TO FUNCTIONS

There are two ways in which arguments or parameters can be passed to the called function.
1. Call by value - The values of the variables are passed by the calling function to the called
function.
2. Call by reference - The addresses of the variables are passed by the calling function to the
called function.
1. Call by Value
• In call by value method, the value of the actual parameters is copied into the formal parameters.
• In call by value method, we cannot modify the value of the actual parameter by the formal
parameter.
• In call by value, different memory is allocated for actual and formal parameters.
• The actual parameter is the argument which is used in the function call whereas formal parameter is
the argument which is used in the function definition.

Eg://Program for call by value


#include<stdio.h>
int main()
{
int x,y;
void swap(int,int);
printf("Enter two numbers:");
scanf("%d%d",&x,&y);
printf("\n\nBefore Swapping: x = %d\ty = %d",x,y);
swap(x,y);
printf("\n\nAfter Swapping: x = %d\ty = %d",x,y);
}

37
void swap(int a, int b)
{
a=a+b;
b=a-b;
a=a-b;
printf("\n\nIn swap function: x = %d\ty = %d\n\n",a,b);
}
Output:
Enter two numbers: 2 3
Before Swapping: x=2 y=3
In Swap function: x=3 y=2
After Swapping : x=2 y=3

Pros and cons


The biggest advantage of using the call-by-value technique is that arguments can be passed as
variables, literals, or expressions.
Its main drawback is that copying data consumes additional storage space. In addition, it can take a
lot of time to copy, thereby resulting in performance penalty, especially if the function is called many times.

2. Call By Reference:
• The method of passing arguments by address or reference is also known as call by address or call by
reference. Here, the addresses of the actual arguments are passed to the formal parameters of the
function.
• If the arguments are passed by reference, changes in the formal parameters also make changes on
actual parameters.
Eg//Program for Call by reference
#include<stdio.h>
int main()
{
int x,y;
void swap(int*,int*);
printf("Enter two numbers:");
scanf("%d%d",&x,&y);
printf("\n\nBefore Swapping:\n\nx = %d\ty = %d",x,y);
swap(&x,&y);
printf("\n\nAfter Swapping:\n\nx = %d\ty = %d\n\n",x,y);
}
void swap(int *a, int *b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
printf("\n\nIn swap function: x = %d\ty = %d\n\n",a,b);
}
Output:
Enter two numbers: 2 3
Before Swapping: x=2 y=3
In Swap function: x=3 y=2
After Swapping : x=3 y=2

Advantages
1.Since arguments are not copied into the new variables, it provides greater time and
spaceefficiency.
2.The function can change the value of the argument and the change is reflected in the calling
function.
38
3.A function can return only one value. In case we need to return multiple values, we can pass those
arguments by reference, so that the modified values are visible in the calling function.
Disadvantage:
if inadvertent changes are caused to variables in called function then these changes would be
reflected in calling function as original values would have been overwritten.

Q3: RECURSIVE FUNCTION


Function calls itself again and again is called recursion.
A recursive function is defined as a function that calls itself to solve a smaller version of its task
until a final call is made which does not require a call to itself.
Every recursive solution has two major cases. They are,
➢ Base case - in which the problem is simple enough to be solved directly without making any
further calls to the same function.
➢ Recursive case - in which first the problem at hand is divided into simpler sub-parts. Second, the
function calls itself but with sub-parts of the problem obtained in the first step. Third, the result is
obtained by combining the solutions of simpler sub-parts.

Eg:Write a program to calculate the factorial of a given number.


#include <stdio.h>
int Fact(int); // FUNCTION DECLARATION
int main()
{
int num, val;
printf("\n Enter the number: ");
scanf("%d", &num);
val = Fact(num);
printf("\n Factorial of %d = %d", num, val);
}
int Fact(int n)
{
if(n==1)
return 1;
else
return (n * Fact(n–1));
}
Output
Enter the number : 5
Factorial of 5 = 120

Types of Recursion
1. Direct Recursion
A function is said to be directly recursive if it explicitly calls itself.

39
2. Indirect Recursion
A function is said to be indirectly recursive if it contains a call to another function which
ultimately calls it.

3. Tail Recursion
A recursive function is said to be tail recursive if no operations are pending to be performed when
the recursive function returns to its caller.

4. Non Tail Recursion:


A recursive function is said to be non tail recursive if operations are pending to be performed when
the recursive function returns to its caller.

int Fact(int n)
{
if(n==1)
return 1;
else
return (n * Fact(n–1));
}

Advantages
➢ Recursive solutions often tend to be shorter and simpler than non-recursive ones.
➢ Code is clearer and easier to use.
➢ Recursion works similar to the original formula to solve a problem.
➢ Recursion follows a divide and conquer technique to solve problems.
disadvantages
➢ Recursion is implemented using system stack. If the stack space on the system is limited,
recursion to a deeper level will be difficult to implement.
40
➢ Aborting a recursive program in midstream can be a very slow process.
➢ Using a recursive function takes more memory and time to execute as compared to its
nonrecursivecounterpart.
➢ It is difficult to find bugs, particularly while using global variables.

Q4: PROGRAM TO DO BINARY SEARCH USING RECURSION


#include<stdio.h>
#define size 10
int binsearch(int[], int, int, int);
int main()
{
int num, i, key, position;
int low, high, list[size];
printf("\nEnter the total number of elements");
scanf("%d", &num);
printf("\nEnter the elements of list :");
for (i = 0; i < num; i++)
{
scanf("%d", &list[i]);
}
low = 0;
high = num - 1;
printf("\nEnter element to be searched : ");
scanf("%d", &key);
position = binsearch(list, key, low, high);
if (position != -1)
{
printf("\nNumber present at %d", (position + 1));
}
else
printf("\n The number is not present in the list");
return (0);
}
// Binary Search function
int binsearch(int a[], int x, int low, int high)
{
int mid;
if (low > high)
return -1;
mid = (low + high) / 2;
if (x == a[mid])
{
return (mid);
}
else if (x < a[mid])
{
binsearch(a, x, low, mid - 1);
}
else
{
binsearch(a, x, mid + 1, high);
}
}
41
Output :
Enter the total number of elements : 5
Enter the elements of list : 11 22 33 44 55
Enter element to be searched : 33
Number present at 3

Q5. POINTERS
A pointer is a variable that contains the memory location of another variable.
Declaring Pointer Variables
The general syntax of declaring pointer variables can be given as below.
data_type *ptr_name;

Here, data type is the data type of the value that the pointer will point to. For example,

Eg: int x= 10;


int *ptr;
ptr = &x;
Eg//Program using pointers
:#include <stdio.h>
int main()
{
int num, *pnum;
pnum = &num;
printf("\n Enter the number : ");
scanf("%d", &num);
printf("\n The number that was entered is : %d", *pnum);
return 0;
}
Output
Enter the number : 10
The number that was entered is : 10

The Pointer Operators:


There are two pointer operators :
1. value at address operator ( * )
2. address of operator ( & )

Value at address operator ( * )


The * is a unary operator. It gives the value stored at a particular address. The ‘value at address’
operator is also called ‘indirection’ operator.
q = *m;
if m contains the memory address of the variable count, then preceding assignment statement can
places the value of count into q.
Address of operator ( & )
The & is a unary operator that returns the memory address of its operand.
m = & count;
The preceding assignment statement can be “The memory address of the variable count is places into
m”.

42
Output of the program :
Address of a = 12345
Address of a = 12345
Address of b = 12345
Value of b = 12345
Value of a = 5
Value of a = 5
Value of a = 5

Pointer Arithmetic
There are four arithmetic operators that can be used on pointers: ++, --, +, and –
Valid Pointer Arithmetic Invalid Pointer Arithmetic
Operations Operations
✓ Adding a number to pointer. ➢ Addition of two pointers.
✓ Subtracting a number form a ➢ Division of two pointers.
pointer. ➢ Multiplication of two pointers
✓ Incrementing a pointer.
✓ Decrementing a pointer.
✓ Subtracting two pointers.
✓ Comparison on two pointers
#include <stdio.h>
int main()
{
int m = 5, n = 10, q = 0;
int *p1; OUTPUT:
int *p2; p1 = 2680016
p2 = 2680012
int *p3; *p1+*p2 = 15
p1 = &m; //printing the address of m p1-p2 = 1
p2 = &n; //printing the address of n p1++ = 2680020
printf("p1 = %d\n", p1); p2-- = 2680008

printf("p2 = %d\n", p2);


q = *p1+*p2;
printf("*p1+*p2 = %d\n", q);//point 1
p3 = p1-p2;
printf("p1 - p2 = %d\n", p3); //point 2
p1++;
printf("p1++ = %d\n", p1); //point 3
p2--;
printf("p2-- = %d\n", p2); //point 4
//Below line will give ERROR
printf("p1+p2 = %d\n", p1+p2); //point 5
return 0;
}
43
Q6: NULL POINTER
null pointer which is a special pointer value and does not point to any value. This means that a null
pointer does not point to any valid memory address.
int *ptr = NULL;
The null pointer is used in three ways,
1. To stop indirection in a recursive data structure.
2. As an error value
3. As a sentinel value
#include <stdio.h>
int main()
{
int *ptr = NULL;
printf("The value of ptr is %u",ptr);

return 0;
}
Output :
The value of ptr is 0

Q7: POINTERS AND ARRAYS :

Syntax: int *ptr;


ptr = &arr[0];
Here, ptr is made to point to the first element of the array.

Eg:// program to display an array of given numbers.


#include <stdio.h>
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9};
int *ptr1, *ptr2;
ptr1 = arr;
ptr2 = &arr[8];
while(ptr1<=ptr2)
{
printf("%d", *ptr1);
ptr1++; Output
} 1234567
return 0; 89
}

Q8: ARRAY OF POINTERS:


An array of pointers can be declared as.
datatype *array_name[size];

Eg:int *ptr[10];

The above statement declares an array of 10 pointers where each of the pointer points to an
integer variable.

44
Example 1:
int main()
{
int *ptr[10];
int p = 1, q = 2, r = 3, s = 4, t = 5;
ptr[0] = &p;
ptr[1] = &q; OUTP
ptr[2] = &r; UT:4
ptr[3] = &s;
ptr[4] = &t;
printf("\n %d", *ptr[3]);
return 0;
}

Example 2://Program on Array of Pointers


int main()
{
int arr1[]={1,2,3,4,5};
int arr2[]={0,2,4,6,8};
Output
int arr3[]={1,3,5,7,9};
101
int *parr[3] = {arr1, arr2, arr3};

int i;
for(i = 0;i<3;i++)
printf(«%d», *parr[i]);
return 0;
}
Applications of Pointers
➢ Pointers are used to pass information back and forth between functions.
➢ Pointers enable the programmers to return multiple data items from a function via function
arguments.
➢ Pointers provide an alternate way to access the individual elements of an array.
➢ Pointers are used to pass arrays and strings as function arguments.
➢ Pointers are used to create complex data structures, such as trees, linked lists, linked stacks,linked
queues, and graphs.

Q9: PROGRAM TO SORT NAMES


#include<stdio.h>
#include<string.h>
int main()
{
int i,j,count;
char str[25][25],temp[25];
puts("How many strings u are going to enter?: ");
scanf("%d",&count);
puts("Enter Strings one by one: ");
for(i=0;i<=count;i++)
gets(str[i]);
for(i=0;i<=count;i++)
for(j=i+1;j<=count;j++)
{
if(strcmp(str[i],str[j])>0)
{
45
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("Order of Sorted Strings:");
for(i=0;i<=count;i++)
puts(str[i]);
return 0;
}
Extra:
1. Write a program to calculate the GCD of two numbers using recursive functions.
#include <stdio.h>
int GCD(int, int);
int main()
{
int num1, num2, res;
printf("\n Enter the two numbers: ");
scanf("%d %d", &num1, &num2);
res = GCD(num1, num2);
printf("\n GCD of %d and %d = %d", num1, num2, res);
return 0;
}
int GCD(int x, int y)
{
int rem;
rem = x%y;
if(rem==0)
return y;
else
return (GCD(y, rem));
}
Output
Enter the two numbers : 8 12
GCD of 8 and 12 = 4
2. Write a program to print the Fibonacci series using recursion.
#include <stdio.h>
int Fibonacci(int);
int main()
{
int n, i = 0, res;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("Fibonacci series\n");
for(i = 0; i < n; i++ )
{
res = Fibonacci(i);
Stacks 247
printf("%d\t",res);
}
return 0;
}

46
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n–1) + Fibonacci(n–2) );
}
Output
Enter the number of terms
Fibonacci series
01123
3. Write a program to add two integers using pointers and functions.
#include <stdio.h>
void sum (int*, int*, int*);
int main()
{
int num1, num2, total;
printf("\n Enter the first number : ");
scanf("%d", &num1);
printf("\n Enter the second number : ");
scanf("%d", &num2);
sum(&num1, &num2, &total);
printf("\n Total = %d", total);
return 0;
}
void sum (int *a, int *b, int *t)
{
*t = *a + *b;
}
Output
Enter the first number : 23
Enter the second number : 34
Total = 57

47
UNIT IV
Structure - Nested structures – Pointer and Structures – Array of structures – Example Program
using structures and pointers – Self referential structures – Dynamic memory allocation - Singly linked list – typedef.

Q1: STRUCTURES:
A structure is a user-defined data type that can store related information together. A structure is a
collection of variables under a single name.
The major difference between a structure and an array is that, an array contains related information
of the same data type.
The variables within a structure are of different data types and each has a name that is used to select
it from the structure.
Features of structures
• Structures can store more than one different data type data under a single variable.
• Structure elements are stored in successive memory locations.
• Nesting of structure is possible.
• Structure elements can be passed as argument to the function.
• It is possible to create structure pointers.
Syntax:
//Structure creation
struct structurename
{
Datatype1 variablename;
Datatype2 variablename;
.
.
};

//Object Creation
struct structname objname;

Example :
//Program to display a point
#include<stdio.h>
struct point
{
int x,y;
};
void main()
{ Output:
struct point p1={2,3}; (2,3)
printf(“(%d,%d)”,p1.x,p1.y);
}

Initialization of structures:
Syntax:
struct struct_name
{
datatype membername1;
datatype membername2;
datatype membername3;
}sturct_var={constant1,constant2,constant3,….};
48
Example:
struct student
{
int rno;
char name[20];
char course[20];
float fees;
}stud1={01,”Rahul”,”BCA”,45000};
or
struct student stud2={02,”Rajiv”};

Fig. illustrates how the values will be assigned to individual fields of the structure

Accessing the members of a structure:


A structure member variable is generally accessed using a ‘.’(dot) operator.
Syntax:
struct_var.membername;
Example:
stud1.rno=01;
stud1.name=”Rahul”;
stud1.course=”BCA”;
stud1.fees=45000;

Receiving user input:


scanf(“%d”,&stud1.rno);
scanf(“%s”,stud1.name);

Displaying output:
printf(“Roll No:%d”,stud1.rno);
printf(“Name:%s”,stud1.name);
Q2: TYPEDEF DECLARATION:
The typedef keyword enables the programmer to create a new data type name from an existing data
type.
Syntax:
typedef existingdatatype newdatatype;
Example 1:
typedef int INTEGER;
INTEGER number=5;
Example 2:
typedef struct student
{
int rno;
char name[20];
char course[20];
float fees;
};
student s1; //instead of struct student s1;

49
Q3: COPYING AND COMPARING STRUCTURES:

Values of structure variables


Copy:
We can assign a structure to another structure of the same type.
struct student stud1={01,”Rahul”,”BCA”,45000};
struct student stud2=stud1;

Compare:
if(stud1.fees==stud2.fees)
printf(“Fees of s2 and s1 are equal”);

Q4: STRUCTURES WITHIN STRUCTURES (NESTED STRUCTURES) :


Structures can be placed within another structures ie., a structure may contain another structure as its
member. A structure that contains another structure as its member is called as nested structures.

50
Q5: ARRAYS OF STRUCTURES.
In the above examples, we have seen how to declare a structure and assign values to its data
members.

51
52
Q6: PASSING STRUCTURES THROUGH POINTERS:
Passing large structures to functions using the call by value method is very inefficient. Therefore, it is
preferred to pass structures through pointers. It is possible to create a pointer to almost any type in C,
including the user-defined types.

It is extremely common to create pointers to structures. A pointer to a structure is a variable that holds
the address of a structure. The syntax to declare a pointer to a structure can be given as,

struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
.......................
}*ptr;

Or

struct struct_name *ptr;


For our student structure, we can declare a pointer variable by writing
struct student *ptr_stud, stud;

The next thing to do is to assign the address of stud to the pointer using the address operator
(&), as we would do in case of any other pointer. So to assign the address, we will write
ptr_stud = &stud;
To access the members of a structure, we can write
(*ptr_stud).roll_no;
Write a program to initialize the members of a structure by using a pointer to the structure.
#include <stdio.h>
#include <conio.h>
struct student
{
int r_no;
char name[20];
char course[20];
int fees;
};
int main() Output
{ Enter the
details of the student:
struct student stud1, *ptr_stud1; Enter the Roll
clrscr(); Number = 02
Enter the Name =
ptr_stud1 = &stud1; Aditya
printf("\n Enter the details of the student :"); Enter the Course
= MCA
printf("\n Enter the Roll Number ="); Enter the Fees =
scanf("%d", &ptr_stud1 -> r_no); 60000
DETAILS OF THE
printf("\n Enter the Name = ); STUDENT
gets(ptr_stud1 -> name); ROLL NUMBER = 02
NAME = Aditya
53 COURSE = MCA
FEES = 60000
printf("\n Enter the Course = ");
gets(ptr_stud1 -> course);
printf("\n Enter the Fees = ");
scanf("%d", &ptr_stud1 -> fees);
printf("\n DETAILS OF THE STUDENT");
printf("\n ROLL NUMBER = %d", ptr_stud1 –> r_no);
printf("\n NAME = %s", ptr_stud1 –> name);
printf("\n COURSE = %s", ptr_stud1 –> course);
printf("\n FEES = %d", ptr_stud1 –> fees);
return 0;
}
Q7: SELF-REFERENTIAL STRUCTURES
Self-referential structures are those structures that contain a reference to the data of its same type.
That is, a self-referential structure, in addition to other data, contains a pointer to a data that is of the same
type as that of the structure. For example, consider the structure node given below.
struct node
{
int val;
struct node *next;
};
Here, the structure node will contain two types of data: an integer val and a pointer next. You must
be wondering why we need such a structure. Actually, self-referential structure is the foundation of other
data structures. We will be using them throughout this book and their purpose will be clearer to you when
we discuss linked lists, trees, and graphs.

Q8: LINKED LISTS


Array is a linear collection of data elements in which the elements are stored in consecutive memory
locations. Its size is fixed.
A linked list does not store its elements in consecutive memory locations and the user can add any
number of elements to it.
However, unlike an array, a linked list does not allow random access of data. Elements in a linked list
can be accessed only in a sequential manner. But like an array, insertions and deletions can be done at any
point in the list in a constant time.
A linked list can be perceived as a train or a sequence of nodes in which each node contains one or
more data fields and a pointer to the next node.

Start

Simple Linked List

Since in a linked list, every node contains a pointer to another node which is of the same type, it is
also called a self-referential data type.

START - stores the address of the first node in the list.


next - stores the address of its succeeding node.

54
Declaraction of a Node:
struct node
{
int data;
struct node *next;
}

Memory Allocation and De-allocation for a Linked List


The Function malloc is most commonly used to attempt to ``grab'' a continuous portion of
memory. It is defined by:
void *malloc(size_t number_of_bytes);
it is usual to use the sizeof() function to specify the number of bytes:

Struct node *new_node;


new_node = (struct node*)malloc(sizeof(struct node));

SINGLY LINKED Lists


A singly linked list is the simplest type of linked list in which every node contains some data and a
pointer to the next node of the same data type. By saying that the node contains a pointer to the next node,
we mean that the node stores the address of the next node in sequence.
A singly linked list allows traversal of data only in one way. Figure 6.7 shows a singly linked list.

START

1 2 3 4 5 6 7 X

Singly linked list

Inserting a New Node in a Linked List


In this section, we will see how a new node is added into an already existing linked list. We will
take four cases and then see how insertion is done in each case.
Case 1: The new node is inserted at the beginning.
Case 2: The new node is inserted at the end.
Case 3: The new node is inserted after a given node.

Case 1: Inserting a Node at the Beginning of a Linked List

struct node *insert_beg(struct node *start)


{
55
struct node *new_node;
int num;
printf(“\n Enter the data : “);
scanf(“%d”, &num);
new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = num;
new_node -> next = start;
start = new_node;
return start;
}

Case 2: Inserting a Node at the End of a Linked List

struct node *insert_end(struct node *start)


{
struct node *ptr, *new_node;
int num;
printf(“\n Enter the data : “);
scanf(“%d”, &num);
new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = num;
new_node -> next = NULL;
ptr = start;

while(ptr -> next != NULL)


ptr = ptr -> next;

ptr -> next = new_node;


return start;
}

56
Case 3: Inserting a Node After a Given Node in a Linked List

struct node *insert_after(struct node *start)


{
struct node *new_node, *ptr, *preptr;
int num, val;
printf(“\n Enter the data : “);
scanf(“%d”, &num);
printf(“\n Enter the value after which the data has to be inserted : “);
scanf(“%d”, &val);
new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = num;

ptr = start;
preptr = ptr;
while(preptr -> data != val)
{
preptr = ptr;
ptr = ptr -> next;
}

preptr -> next=new_node;


new_node -> next = ptr;
return start;
}

57
Deleting a Node from a Linked List:
Case 1: The first node is deleted.
Case 2: The last node is deleted.
Case 3: The node equal to a given value is deleted.

Case 1: Deleting the First Node from a Linked List

struct node *delete_beg(struct node *start)


{
struct node *ptr;
ptr = start;
start = start -> next;
free(ptr);
return start;
}

Case 2: Deleting the Last Node from a Linked List

struct node *delete_end(struct node *start)


{
struct node *ptr, *preptr;
ptr = start;
while(ptr -> next != NULL)
{
preptr = ptr;
ptr = ptr -> next;
}
preptr -> next = NULL;
free(ptr);
return start;
}

58
Case 3: Deleting the Node equal to a Given Value in a Linked List

struct node *delete_node(struct node *start)


{
struct node *ptr, *preptr;
int val;
printf(“\n Enter the value of the node which has to be deleted : “);
scanf(“%d”, &val);
ptr = start;
if(ptr -> data == val)
{
start = delete_beg(start);
return start;
}
else
{
while(ptr -> data != val)
{
preptr = ptr;
ptr = ptr -> next;
}
preptr -> next = ptr -> next;
free(ptr);
return start;
}
}

Programming Example
1. Write a program to create a linked list and perform insertions and deletions of all cases.
Write functions to sort and finally delete the entire list at once.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

59
#include <malloc.h>
struct node
{
int data;
struct node *next;
};
struct node *start = NULL;
struct node *create_ll(struct node *);
struct node *display(struct node *);
struct node *insert_beg(struct node *);
struct node *insert_end(struct node *);
struct node *insert_before(struct node *);
struct node *insert_after(struct node *);
struct node *delete_beg(struct node *);
struct node *delete_end(struct node *);
struct node *delete_node(struct node *);
struct node *delete_after(struct node *);
struct node *delete_list(struct node *);
struct node *sort_list(struct node *);
int main(int argc, char *argv[]) {
int option;
do
{
printf(“\n\n *****MAIN MENU *****”);
printf(“\n 1: Create a list”);
printf(“\n 2: Display the list”);
printf(“\n 3: Add a node at the beginning”);
printf(“\n 4: Add a node at the end”);
printf(“\n 5: Add a node before a given node”);
printf(“\n 6: Add a node after a given node”);
printf(“\n 7: Delete a node from the beginning”);
printf(“\n 8: Delete a node from the end”);
printf(“\n 9: Delete a given node”);
printf(“\n 10: Delete a node after a given node”);
printf(“\n 11: Delete the entire list”);
printf(“\n 12: Sort the list”);
printf(“\n 13: EXIT”);
printf(“\n\n Enter your option : “);
scanf(“%d”, &option);
switch(option)
{
case 1: start = create_ll(start);
printf(“\n LINKED LIST CREATED”);
break;
case 2: start = display(start);
break;
case 3: start = insert_beg(start);
break;
case 4: start = insert_end(start);
break;
case 5: start = insert_before(start);
60
break;
case 6: start = delete_beg(start);
break;
case 7: start = delete_end(start);
break;
case 8: start = delete_node(start);
break;
case 9: start = sort_list(start);
break;
}
}while(option <10);
getch();
return 0;
}
struct node *create_ll(struct node *start)
{
struct node *new_node, *ptr;
int num;
printf(“\n Enter -1 to end”);
printf(“\n Enter the data : “);
scanf(“%d”, &num);
while(num!=-1)
{
new_node = (struct node*)malloc(sizeof(struct node));
new_node -> data=num;
if(start==NULL)
{
new_node -> next = NULL;
start = new_node;
}
else
{
ptr=start;
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next = new_node;
new_node->next=NULL;
}
printf(“\n Enter the data : “);
scanf(“%d”, &num);
}
return start;
}
struct node *display(struct node *start)
{
struct node *ptr;
ptr = start;
while(ptr != NULL)
{
printf(“\t %d”, ptr -> data);
ptr = ptr -> next;
}
61
return start;
}

struct node *insert_beg(struct node *start)


{
struct node *new_node;
int num;
printf(“\n Enter the data : “);
scanf(“%d”, &num);
new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = num;
new_node -> next = start;
start = new_node;
return start;
}

struct node *insert_end(struct node *start)


{
struct node *ptr, *new_node;
int num;
printf(“\n Enter the data : “);
scanf(“%d”, &num);
new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = num;
new_node -> next = NULL;
ptr = start;

while(ptr -> next != NULL)


ptr = ptr -> next;

ptr -> next = new_node;


return start;
}
struct node *insert_after(struct node *start)
{
struct node *new_node, *ptr, *preptr;
int num, val;
printf(“\n Enter the data : “);
scanf(“%d”, &num);
printf(“\n Enter the value after which the data has to be inserted : “);
scanf(“%d”, &val);
new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = num;

ptr = start;
preptr = ptr;
while(preptr -> data != val)
{
preptr = ptr;
ptr = ptr -> next;
}

preptr -> next=new_node;


62
new_node -> next = ptr;
return start;
}
struct node *delete_beg(struct node *start)
{
struct node *ptr;
ptr = start;
start = start -> next;
free(ptr);
return start;
}
struct node *delete_end(struct node *start)
{
struct node *ptr, *preptr;
ptr = start;
while(ptr -> next != NULL)
{
preptr = ptr;
ptr = ptr -> next;
}
preptr -> next = NULL;
free(ptr);
return start;
}
struct node *delete_node(struct node *start)
{
struct node *ptr, *preptr;
int val;
printf(“\n Enter the value of the node which has to be deleted : “);
scanf(“%d”, &val);
ptr = start;
if(ptr -> data == val)
{
start = delete_beg(start);
return start;
}
else
{
while(ptr -> data != val)
{
preptr = ptr;
ptr = ptr -> next;
}
preptr -> next = ptr -> next;
free(ptr);
return start;
}
}
struct node *sort_list(struct node *start)
{
struct node *ptr1, *ptr2;
int temp;
ptr1 = start;
63
while(ptr1 -> next != NULL)
{
ptr2 = ptr1 -> next;
while(ptr2 != NULL)
{
if(ptr1 -> data > ptr2 -> data)
{
temp = ptr1 -> data;
ptr1 -> data = ptr2 -> data;
ptr2 -> data = temp;
}
ptr2 = ptr2 -> next;
}
ptr1 = ptr1 -> next;
}
return start; // Had to be added
}
Extra:
Declare a structure to store information of a particular date.
struct date
{
int day;
int month;
int year;
};

Declare a structure to create an inventory record.


struct inventory
{
char prod_name[20];
float price;
int stock;
};

Write a program, using an array of pointers to a structure, to read and display the data of
students.
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
struct student
{
int r_no;
char name[20];
char course[20];
int fees;
};
struct student *ptr_stud[10];
int main()
{
int i, n;
64
printf("\n Enter the number of students : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
ptr_stud[i] = (struct student *)malloc(sizeof(struct student)); printf("\n
Enter the data for student %d ", i+1); printf("\n ROLL NO.: ");
scanf("%d", &ptr_stud[i]–>r_no);
printf("\n NAME: ");
gets(ptr_stud[i]–>name);
printf("\n COURSE: "); Output
gets(ptr_stud[i]–>course); Enter the number of
printf("\n FEES: "); students : 1
Enter the data for
scanf("%d", &ptr_stud[i]–>fees); student 1
} ROLL NO.: 01
NAME: Rahul
printf("\n DETAILS OF STUDENTS"); COURSE: BCA
for(i=0;i<n;i++) FEES: 45000
DETAILS OF STUDENTS
{ ROLL NO. = 01
printf("\n ROLL NO. = %d", ptr_stud[i]–>r_no);
NAME = Rahul
COURSE = BCA
printf("\n NAME = %s", ptr_stud[i]–>name); printf("\n
FEES = 45000
COURSE = %s", ptr_stud[i]–>course); printf("\n FEES =
%d", ptr_stud[i]–>fees);
}
return 0;
}

Write a program that passes a pointer to a structure to a function.


#include <stdio.h>
#include <conio.h>
#include <alloc.h>
struct student
{
int r_no;
char name[20];
char course[20];
int fees;
};
void display (struct student *);
int main()
{
struct student *ptr;
ptr = (struct student *)malloc(sizeof(struct student));
printf("\n Enter the data for the student ");
printf("\n ROLL NO.: ");
scanf("%d", &ptr–>r_no);
printf("\n NAME: ");
gets(ptr–>name);
printf("\n COURSE: ");
gets(ptr–>course);

65
printf("\n FEES: "); Output
scanf("%d", &ptr–>fees); Enter the data for the
student
display(ptr); ROLL NO.: 01
getch(); NAME: Rahul
COURSE: BCA
return 0; FEES: 45000
} DETAILS OF STUDENT
ROLL NO. = 01
void display(struct student *ptr) NAME = Rahul
{ COURSE = BCA
FEES = 45000
printf("\n DETAILS OF STUDENT");
printf("\n ROLL NO. = %d", ptr–>r_no);
printf("\n NAME = %s", ptr–>name);
printf("\n COURSE = %s ", ptr–>course);
printf("\n FEES = %d", ptr–>fees);
}

66
UNIT V FILE PROCESSING
Files – Types of file processing: Sequential access, Random access – Sequential access file - Example
Program: Finding average of numbers stored in sequential access file - Random access file - Example Program:
Transaction processing using random access files – Command line arguments.

Q1: FILE:
Definition: It is a block of useful data which is available to a computer program and is usually
stored on a persistent storage medium. Storing a file on a persistent storage medium like hard disk
ensures the availability of the file for future use.

File Attributes
• File name It is a string of characters that stores the name of a file. File naming conventions vary
from one operating system to the other.
• File position It is a pointer that points to the position at which the next read/write operation will
be performed.
• File structure It indicates whether the file is a text file or a binary file. In the text file, the
numbers (integer or floating point) are stored as a string of characters. A binary file, on the other
hand, stores numbers in the same way as they are represented in the main memory.

Attribute Flags
A file can have six additional attributes attached to it. These attributes are usually stored in a
single byte, with each bit representing a specific attribute. If a particular bit is set to ‘1’ then this
means that the corresponding attribute is turned on.

(i) Read-only A file marked as read-only cannot be deleted or modified.


(ii) Hidden A file marked as hidden is not displayed in the directory listing.
(iii) Volume Label Every disk volume is assigned a label for identification.
(iv) Directory In directory listing, the files and sub-directories of the current directory are
differentiated by a directory-bit.
(v) Archive The archive bit is used as a communication link between programs that modify files and
those that are used for backing up files.
Types Of Files
(i) A text file, also known as a flat file or an ASCII file, is structured as a sequence of
67
lines of alphabet,numerals, special characters, etc. However, the data in a text file,
whether numeric or non-numeric,is stored using its corresponding ASCII code. The
end of a text file is often denoted by placing a special character, called an end-of-file
marker, after the last line in the text file.
(ii) A binary file contains any type of data encoded in binary form for computer storage
and processing purposes. A binary file can contain text that is not broken up into lines.
A binary file stores data in a format that is similar to the format in which the data is
stored in the main memory.

Basic File Operations


(i) Creating a File
A file is created by specifying its name and mode. Then the file is opened for writing records
that are read from an input device.
Once all the records have been written into the file, the file is closed. The file is now available
for future read/write operations by any program that has been designed to use it in some way or the
other.

(ii)Updating a File
Updating a file means changing the contents of the file to reflect a current picture of reality. A
file can be updated in the following ways:
1. Inserting a new record
2. Deleting an existing record.
3. Modifying an existing record.

(iii) Retrieving from a File


It means extracting useful data from a given file. Information can be retrieved from a file
either for an inquiry or for report generation. An inquiry for some data retrieves low volume of data,
while report generation may retrieve a large volume of data from the file.

(iv) Maintaining a File


It involves restructuring or re-organizing the file to improve the performance of the
programs that access this file. Restructuring a file keeps the file organization unchanged and changes
only the structural aspects of the file (for example, changing the field width or adding/deleting fields).
Reading and writing to a text file
1. Declare a file pointer
2. Open file
3. Process file
4. Close file

68
Declaring a file pointer

FILE *filepointername;

Eg:FILE *fp;

Opening A File
fopen() function is used for opening the file.
SYNTAX:
FILE *fopen(const char *filename,const char *mode);

Filename-the path information about file is specified

Mode-it conveys the type of processing that will be done with the file.

Eg:
FILE *fp=fopen(“C:/student.dat”,”r”);
If(fp==NULL)
Printf(“file couldn’t open”);

Closing A File
fclose() is used disconnect a file pointer from a file.
Syntax:
fclose(filepointername); Eg:
FILE *fp;
fclose(fp);
fcloseall() closes all streams that are currently opened.

Reading Data From File:


C provides the following set of functions to read data from a file
• fscanf()
• fgets()
• fgetc()
• fread()

(i) fscanf()
It is used to read formatted data from the stream.

69
int fscanf(FILE *stream,const char *format,….)
The type specifiers are as follows

Type Qualifying input


c Character
d Decimal
f Float
o Octal
s String
u Unsigned decimal values
x Hexadecimal values
Eg:
int main()
{
FILE *fp;
Char name[10]; Int
rollno; OUTPUT: Enter
Fp=fopen(“student.dat”,”r”); If(fp==NULL)
{ name rollno John 1
Printf(“file couldn’t open”);
} Name John RollNo 1
printf(“enter name and roll no” );
fscanf(stdin,”%s%d”,name,&rollno); Name John Roll no 1
printf(“Name%s Rollno %d”,name,rollno);
Fscanf(fp,”%s%d”,name,&rollno);
Printf(“name%s \t rollno %d”,name,rollno);
fclose(fp);
return 0;
}

(ii) fgets()
It is used to get a string from a stream.It terminates as soon as it encounters newline
character,EOF or any error.

Char *fgets(char *str,int size,FILE *stream);


Eg: #include<stdio.h>
int main ()
{
FILE *fp;
Char str[10];
fp=fopen(“student.txt”,”r”); if
(fp==NULL)
{ OUTPUT:hi hello how
Printf(“file couldn’t be opened”); are you
}
While(fgets(str,10,fp)!=NULL)
Printf(“%s”,str);
fclose(fp);
return 0;
}

70
(iii) fgetc()
It reads a single character from the current position of file.

int fgets(FILE *stream);


Eg:int main()
{ OUTPUT
FILE *fp; char #include<
str[20]; int I,ch; stdio.h> int
main()
fp=fopen(“c:/sum.c”,”r”);
{
if(fp==NULL) int a,b,c;
{ printf(“entr
printf(“file not found”); numbers”);
} scanf(“%d”,&a,&b); c=a+b;
ch=fgetc(fp); printf(“%d”,c);
for(i=0;i<20&&(feof(fp)==0);i++) }
{
str[i]=(char)ch;
ch=fgetc(fp);
}
str[i]=’\0’;
printf(“\n%s”,str);
fclose(fp);
}

(iv) fread()
It is used to read data from file.
int fread(void *str,size_t size,size_t num,FILE *stream);

It reads number of objects and places them into the array pointed
by str . Eg:int main()
{
FILE *fp; char
str[11];
fp=fopen(file1.text”,”r+”);
if(fp===NULL)
{
printf(“file not found”); OUTPUT:
} hello how are you
fread(str,1,10,fp);
str[10]=’\0’;
printf(“%s”,str);
fclose(fp);
}

Writing Data To Files


The following functions are used to write data to the files.
• fprintf()
• fputs()
• fputc()
• fwrite()
71
i) fprintf()
It is used to write data that is formatted as specified by the format argument to the specified stream.
int fprintf(FILE *stream,const char *format,…);
Eg:
int main()
{
FILE *fp;; char OUTPUT:
name[20]; int i; Enter
float salary; name Peter Enter
fp=fopen(“details.txt”,”w”); salary 10000
if(fp==NULL) …….
{
printf(“File not found”);
}
for(int i=0;i<10;i++)
{
puts(“Enter name”);
gets(name); printf(“enter
sdalary”);
scanf(“%f”,&salary);
fprintf(fp,”%s%f”,name,salary);
}
fclose(fp);
return 0;
}

ii)fputs()
It is used to write a line to a file .
int fputs(const char *str,FILE *stream);
Eg:
int main()
{
FILE *fp; char
str[100];
fp=fopen(“file2.txt”,”w”);
if(fp==NULL)
{
printf(“file not found”); output:good
}
gets(str);
fputs(str,fp);
fclose(fp);
return 0;
}

iii) fputc()
It will write the byte specified by C to the output stream pointed to by stream.
int fputc(int c,FILE *stream);
int main()
{
FILE *fp; char
str[100]; int I;
72
fp=fopen(“file3.txt”,”w”);
if(fp==NULLL)
printf(“file not found”);
gets(str);
for(i=0;i<str[i];i++) output:good
fputc(str[i],fp);
fclose(fp);
}
iv) fwrite()
It is used to write data to a file.It will write objects of size specified by size from array
pointed to by ptr to the stream.fwrite is used in binary mode.It can write integers,characters or structures
to a file.
int fwrite(const void *str,size_t size,size_t count,FILE *stream);
Eg:
int main()
{
FILE *fp; int
count;
char str[]=”good morning”;
fp=fopen(“welcome.txt”,”wb”); if(fp==NULL)
{
printf(“file not openend”);
} OUTPUT: 13 bytes were written to the file.
count=fwrite(str,1,strlen(str),fp);
printf(“%d bytes were written to the file”,count);
fclose(fp);
return 0;
}

Detecting The End Of File:


There are two ways to detect end of file
1. EOF-It has the value -1. Eg:
int c;
while(1)
{
if(c==EOF) break;
printf(%c”,c);
}
2. feof()-It checks whether end of file is reached or not.It returns error code when end of file is
not reached.

int feof(FILE *fp);


Eg:
int main()
{
FILE *fp; char
str[80];
fp=fopen(“student.dat”,”r”); Output:hi hello
if(fp==NULL) how are you
{
printf(“file not opened”);
}
73
while(!feof(fp))
{
fgets(str,79,fp);
printf(“%s”,str);
}
fclose(fp);
return 0;
}

Q2: FILE ORGANIZATION


file is a collection of related records. Organization of records means the logical arrangement of
records in the file and not the physical layout of the file as stored on a storage media.

Types:
a. Sequential Organization
A sequentially organized file stores the records in the order in which they were entered. That
is,the first record that was entered is written as the first record in the file, the second record enteredis
written as the second record in the file, and so on. As a result, new records are added only at the end
of the file.Sequential files can be read only sequentially, starting with the first record in the file.

Functions used for sequential access file


1.fwrite()
It is used to write data to a file.It will write objects of size specified by size from array pointed
to by ptr to the stream pointed to by stream.fwrite is used in binary mode.It can write
integers,characters or structures to a file.

74
Syntax:
int fwrite(const void *str,size_t size,size_t count,FILE *stream);

2.fread()
It is used to read data from file.
Syntax:
int fread(void *str,size_t size,size_t num,FILE *stream);
It reads number of objects and places them into the array pointed by str .

3. fprintf()
It is used to write data that is formatted as specified by the format argument to the specified
stream.
Syntax:
int fprintf(FILE *stream,const char *format,…);

4. fscanf()
It is used to read formatted data from the stream.
Syntax:
int fscanf(FILE *stream,const char *format,….)
Eg:
int main()
{
FILE *fp;
Char name[10]; Int
rollno;
Fp=fopen(“student.dat”,”r”); OUTPUT: Enter
If(fp==NULL)
{ name rollno John 1
Printf(“file couldn’t open”);
} Name John RollNo 1
printf(“enter name and roll no” );
fscanf(stdin,”%s%d”,name,&rollno); Name John Roll no 1
printf(“Name%s Rollno %d”,name,rollno);
Fscanf(fp,”%s%d”,name,&rollno);
Printf(“name%s \t rollno %d”,name,rollno);
fclose(fp);
return 0;
}

b. Random Access Files Random access means we can move to any part of a file and read or write
data from it without having to read through the entire file.
C supports these functions for random access file processing.
1. fseek()
2. ftell()
3. rewind()
fseek():
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
75
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 of file.
1 Current position
2 End of file
Ex: fseek( p,10L,0)
Here, 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.

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

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

Example 1: //program for fseek():


#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is tutorialspoint.com",
fp); fseek( fp, 7, SEEK_SET );
fputs(" C Programming Language",
fp); fclose(fp);
return(0);
}

Example 2: // program to read last ‘n’ characters of the file using appropriate file functions(Here
we need fseek() and fgetc()).

#include<stdio.h> void
main()
{
FILE *fp; char
ch; clrscr();
fp=fopen("file1.c", "r"); if(fp==NULL)
printf("file cannot be opened"); else
{
printf("Enter value of n to read last ‘n’ characters");
scanf("%d",&n);
fseek(fp,-n,2);
while((ch=fgetc(fp))!=EOF)
76
{
printf("%c\t",ch);
}
}
fclose(fp);
getch();
}

Example 3:
#include<stdio.h>
struct Student
{
int roll;
char name[25]; float
marks;
}stu;
void main()
{
FILE *fp; char
ch;
fp = fopen("Student.dat","r"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
printf("\n\nLast record in file.\n"); fseek(fp, Output :
sizeof(Stu)*-1,SEEK_END);
fread(&Stu,sizeof(Stu),1,fp); Last record in file.
printf("\n\tRoll : %d",Stu.roll); Roll : 5
printf("\n\tName : %s",Stu.name); Name : Sumit
printf("\n\tMarks : %f",Stu.marks); Marks : 87.36
printf("\n\nFirst record in file.\n");
fseek(fp,0,SEEK_SET); First record in file.
fread(&Stu,sizeof(Stu),1,fp); Roll : 1
printf("\n\tRoll : %d",Stu.roll); Name : Kumar
printf("\n\tName : %s",Stu.name); Marks : 78.53
printf("\n\tMarks : %f",Stu.marks);
printf("\n\nSecond record in file.\n"); Second record in file.
fseek(fp,0,SEEK_CUR); Roll : 2
fread(&Stu,sizeof(Stu),1,fp); Name : Utsav
printf("\n\tRoll : %d",Stu.roll); Marks : 69.42
printf("\n\tName : %s",Stu.name);
printf("\n\tMarks : %f",Stu.marks);
fclose(fp);
}

77
Q3: WHAT ARE COMMAND LINE ARGUMENTS?
Inputs to the function main are given by making use of special arguments known as command
line arguments.
The C language provides a method to pass parameters to the main() function. This is
typically accomplished by specifying arguments on the operating system command line
(console).
To pass command line arguments, we typically define main() with two arguments:
1. Number of command line arguments – argc
2. list of command line arguments – argv

The syntax for main() looks like:


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

}
Where, argc – is int and stores number of arguments in the command line including program name.
The value of the argc should be non negative.
argv[] – is array of character pointers carrying all the arguments. If argc is greater than
zero, the array elements from argv[0] to argv[argc-1] will conain pointers to strings.
argv[0] is the name of the program.

Program to find sum of n numbers using command line argument.


#include<stdio.h> int
main()
{
int i,sum=0; for(i=1;i<=argc;i++)
{
sum=sum+atoi(argv[i]);
}
printf(“Sum=%d”,sum); return
0;
}
Q4: Write a C program to find the average of numbers stored in sequential access file
#include <stdio.h>
int main (int argc, const char * argv[])
{
FILE *fp;
int nmber, sum,avg; sum = 0;
fp = fopen("data.txt","r"); while(!feof(fp))
{
fscanf(fp,"%d",&number); sum = sum + number;
}
fclose(fp); avg=sum/number;
printf("The sum of the numbers is %d %d.\n",sum,avg);
return 0;
}

78
Q5: Write a C Program for Transaction processing using random access files
#include<stdio.h>
struct account
{
int accno;
char cname[20]; float
balance;
};
void main()
{
struct account acc;
int op,ano,amt,count=0,i=0; FILE
*fp; fp=fopen("Acct.txt","wb+");
do
{
printf("Enter accno,name & amount");
scanf("%d%s%f",&acc.accno,acc.cname,&acc.balance); fwrite(&acc,sizeof(struct
account),1,fp);
++count;
printf("Do you want to continue[1/0]?");
scanf("%d",&op);
}while(op==1); do
{
printf("1.Deposit\n2.Withdraw\n3.Balance\n4.Display\n");
printf("Enter your option");
scanf("%d",&op);
switch(op)
{
case 1:
printf("Enter the accno:");
scanf("%d",&ano);
printf("Enter the amount to be deposited:");
scanf("%d",&amt);
fseek(fp,(ano-1)*sizeof(struct account),SEEK_SET);
fread(&acc,sizeof(struct account),1,fp);
acc.balance=acc.balance+amt;
fwrite(&acc,sizeof(struct account),1,fp);
break;
case 2:
printf("Ener the accno:");
scanf("%d",&ano);
printf("Enter the amount to be deposited:");
scanf("%d",&amt);
fseek(fp,ano-1*sizeof(struct account),SEEK_SET);
case 3:
printf("Ener the accno:");
scanf("%d",&ano);
fseek(fp,(ano-1)*sizeof(struct account),SEEK_SET);
fread(&acc,sizeof(acc),1,fp);
printf("\nAccNo:%d\nAccName:%s\nBalance:%f\n",acc.accno,acc.cname,acc.balance);
case 4:
do
{
79
//fseek(fp,i*sizeof(struct account),SEEK_SET);
fread(&acc,sizeof(struct account),1,fp);
printf("****Details****");
printf("\nAccNo:%d\nAccName:%s\nBalance:%f\n",acc.accno,acc.cname,acc.balance);
}while(feof(fp)==NULL);
}
printf("Do you want to continue[1/0]?");
scanf("%d",&op);
}while(op==1);
fclose(fp);
}

Extra:
Example: //Program to read data from test.txt.
#include <stdio.h>
void main()
{
FILE *fp; char buff[255];
fp = fopen("test.txt", "r");
fscanf(fp, "% [^\t]s", buff);
printf(" %s\n", buff ); fclose(fp);
}

//Program to copy one file content into another file. (OR) Copy content of input.txt into output.txt file.
(May/June 2015) (May/June 2016)
#include <stdio.h>
void main()
{
FILE *fp1,*fp2;
char buff[255];
fp1 = fopen("input.txt", "r");
fscanf(fp1, "%[^\t]s", buff);
fp2=fopen("output.txt","w");
fprintf(fp2,buff );
fclose(fp1);
fclose(fp2);
}
Program to display size of the file. (May/June 2014)
#include<stdio.h>
#include<string.h>
void main()
{
FILE *fp1;
int len;
fp1=fopen("in.txt","r");
fseek(fp1,-1,SEEK_END);
len=ftell(fp1);
printf("%d",len);
fclose(fp1);
}

80
//Program to copy file content into another in reverse order. (OR) C program to read the contents
of a file “in.txt” from last to first and write the contents to “out.txt”. (May/June 2014)
#include<stdio.h>
#include<string.h>
void main()
{
FILE *fp1,*fp2;
char ch,str[150];
int len;
fpos_t pos;
fp1=fopen("in.txt","r");
fp2=fopen("out.txt","w");
fseek(fp1,-1,SEEK_END);
len=ftell(fp1);
while(len--!=-1)
{
ch=(char)fgetc(fp1);
printf("%c",ch);
fputc(ch,fp2);
fseek(fp1,len-1,SEEK_SET);
}
fclose(fp1);
fclose(fp2);
}

Program to count number of vowels, consonants, digits and white spaces in a string.

#include <stdio.h>
int main()
{
char line[150];
int i, vowels, consonants, digits, spaces;

vowels = consonants = digits = spaces = 0;

printf("Enter a line of string: ");


scanf("%[^\n]", line);

for(i=0; line[i]!='\0'; ++i)


{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
line[i]=='o' || line[i]=='u' || line[i]=='A' ||
line[i]=='E' || line[i]=='I' || line[i]=='O' ||
line[i]=='U')
{
++vowels;
}
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
{
++consonants;
}
81
else if(line[i]>='0' && line[i]<='9')
{
++digits;
}
else if (line[i]==' ')
{
++spaces;
}
}

printf("Vowels: %d",vowels);
printf("\nConsonants: %d",consonants);
printf("\nDigits: %d",digits);
printf("\nWhite spaces: %d", spaces);

return 0;
}

82

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy