Program in C Notes
Program in C Notes
Program in C Notes
CS8251 – Programming in C
for I Year II Sem CSE & IT
1
SYLLABUS-
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.
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.
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
4
int 2 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
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;
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)
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
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;
7) Bitwise operators:
It is perform operations at bit level. It operates on integer only. It may not be applied to float or real.
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
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]
Q6: PREPROCESSORS:
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
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
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.
16
#include <stdio.h>
void main( )
{
int c;
printf("Enter a character");
c = getchar();
putchar(c);
}
#include<stdio.h>
void main()
{
/* character array of length 100 */
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}
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.
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];
19
for (i = 0; i < 7; i++)
{
if (m[i] > maxCount)
{
maxCount = m[i];
modeValue = a[i];
}
}
printf("\nMode value is : %d", modeValue);
}
Linear Search:
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
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");
}
}
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);
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
#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;
}
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.
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
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
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.
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.
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:
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);
}
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.
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
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.
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.
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.
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,
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
return 0;
}
Output :
The value of ptr is 0
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;
}
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.
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
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:
Compare:
if(stud1.fees==stud2.fees)
printf(“Fees of s2 and s1 are equal”);
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
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.
Start
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.
54
Declaraction of a Node:
struct node
{
int data;
struct node *next;
}
START
1 2 3 4 5 6 7 X
56
Case 3: Inserting a Node After a Given Node in a Linked List
ptr = start;
preptr = ptr;
while(preptr -> data != val)
{
preptr = ptr;
ptr = ptr -> next;
}
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.
58
Case 3: Deleting the Node equal to a Given Value in a Linked List
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;
}
ptr = start;
preptr = ptr;
while(preptr -> data != val)
{
preptr = ptr;
ptr = ptr -> next;
}
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;
}
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.
(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.
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);
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.
(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
(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.
70
(iii) fgetc()
It reads a single character from the current position of file.
(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);
}
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;
}
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.
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.
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 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
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;
printf("Vowels: %d",vowels);
printf("\nConsonants: %d",consonants);
printf("\nDigits: %d",digits);
printf("\nWhite spaces: %d", spaces);
return 0;
}
82