PROGRAMMING IN C AND DATA STRUCTURES - Unit1&2
PROGRAMMING IN C AND DATA STRUCTURES - Unit1&2
UNIT – I
History of C and its importance:
History of C:
C language is developed by Mr. Dennis Ritchie in the year 1972 at bell laboratory
at USA.
C is a simple and structure Oriented Programming Language.
In the year 1988 C programming language standardized by ANSI (American
national standard institute),
that version is called ANSI-C.
In the year of 2000 C programming language standardized by ISO that version is
called C-99.
All other programming languages were derived directly or indirectly from C
programming concepts.
Importance of ‘C’ language :
It is robust language whose rich setup of built in functions and operator can be used to
write any complex program.
Program written in C are efficient due to several variety of data types and powerful
operators.
The C compiler combines the capabilities of an assembly language with the feature of
high level language. Therefore it is well suited for writing both system software and
business package.
There are only 32 keywords; several standard functions are available which can be
used for developing program.
C is portable language; this means that C programs written for one computer system
can be run on another system, with little or no modification.
C language is well suited for structured programming, this requires user to think of a
problems in terms of function or modules or block. A collection of these modules
make a program debugging and testing easier.
C language has its ability to extend itself. A c program is basically a collection of
functions that are supported by the C library. We can continuously add our own
functions to the library with the availability of the large number of functions. In India
and abroad mostly people use C programming language because it is easy to learn and
understand.
Structure of C Program :
The components of the basic structure of a C program consists of 6 parts.
Documentation section:
The documentation section consists of a set of comment lines giving the name of the
program, the author and other details.
Link section:
The link section provides instructions to the compiler to link functions from the
system library such as using the #include directive.
Definition section:
The definition section defines all symbolic constants such using the #define directive.
Global declaration section:
There are some variables that are used in more than one function.
Such variables are called global variables and are declared in the global declaration
section that is outside of all the functions.
This section also declares all the user-defined functions.
main () function section:
Every C program must have one main function section. This section contains two parts;
declaration part and executable part.
Declaration part:
The declaration part declares all the variables used in the executable part.
Executable part:
There is at least one statement in the executable part.
These two parts must appear between the opening and closing braces.
The program execution begins at the opening brace and ends at the closing
brace.
The closing brace of the main function is the logical end of the program.
All statements in the declaration and executable part end with a semicolon.
Subprogram section:
If the program is a multi-function program then the subprogram section
contains all
the user-defined functions that are called in the main () function.
User-defined functions are generally placed immediately after the main ()
function, although they may appear in any order.
Data Types:
Data types specify how we enter data into our programs and what type of data we
enter.
C language has some predefined set of data types to handle various kinds of data that
we can use in our program.
These data types have different storage capacities.
C language supports 2 different type of data types:
Primary data types:
These are fundamental data types in C namely integer(int), floating point(float),
character(char) and void.
Derived data types:
Derived data types are nothing but primary data types but a little twisted or grouped
together like array, structure, union and pointer.
Data type determines the type of data a variable will hold.
If a variable x is declared as int. it means x can hold only integer values.
Every variable which is used in the program must be declared as what data-type it is.
Primary data types in c Integer type Integers are used to store whole numbers.
Integer type on 16-bit machine:
int or signed int 2 -32,768 to 32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
unsigned short int 1 0 to 255
long int or signed long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
Floating point type:
Floating types are used to store real numbers.
Size and range of Integer type on 16-bit machine Type Size(bytes) Range
Float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932
Character type:
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine Type Size(bytes) Range
char or signed char 1 -128 to 127
unsigned char 1 0 to 255
int - data type int is used to define integer numbers.
{ int Count; Count = 5; }
float - data type:
float is used to define floating point numbers.
{ float Miles; Miles = 5.6; Programming in C 10 }
double - data type:
double is used to define BIG floating point numbers.
It reserves twice the storage for the number.
On PCs this is likely to be 8 bytes. { double Atoms; Atoms = 2500000; }
char - data type:
char defines characters. { char Letter; Letter = 'x'; }
Derived data types :
The derived data type consists of Arrays (used to manage large numbers of objects of
the same type) ,
Functions (does a specific job), Pointers (represents the address and type of a variable
or a function).
Constants:
Constants refer to fixed values.
They are also called as literals. Constants are categorized into two basic types.
Integer Constant:
Integer constants are whole numbers without any fractional part.
Thus integer constant consist of a sequence of digits.
Integer constant can be written in three different number systems:
Decimal, b) Octal and c) Hexadecimal.
Decimal Integer:
It consists of any combination of digits taken from the set 0 through 9.
It can either be positive or negative.
For Example:
0 -321 1234 +786
Embedded spaces, commas, and non-digit characters are not permitted between digits.
For example, 15 750 20,000 $10000 are illegal numbers .
Octal Integer:
It consist of any combination of digits taken from the set 0 through 7.
However, the first digit must be 0, in order to identify the constant as an octal number.
For Example:
0 01 0125 055
Hexadecimal Integer:
A hexadecimal integer constant must begin with either 0x or 0X.
It can then be followed by any combination of digits taken from the set 0 through 9
and A through F (either upper-case or lower-case).
The following are valid hexadecimal integer
constants. 0X0 0x1 0XAB125 -0x5bcd
Real Constant:
A real constant is combination of a whole number followed by a decimal point and
the fractional part.
Example: 0.0083 -0.75 .95215.
Integer numbers are inadequate to represent quantities that vary continuously,
Such as distances, heights, temperatures, prices and soon.
Constants refer to fixed values.
Single Character Constants :
It simply contains a single character enclosed within ' and ' (a pair of single quote).
It is to be noted that the character '8' is not the same as 8.
Character constants have a specific set of integer values known as ASCII values
(American Standard Code for Information Interchange).
Example: 'X' '5' ';'
String Character Constants :
These are a sequence of characters enclosed in double quotes, and they may include
letters, digits, special characters, and blank spaces.
It is again to be noted that "G" and 'G 'are different – because "G" represents a string
as it is enclosed within a pair of double quotes whereas 'G' represents a single
character.
Example: "Hello!", "2015", "2+1"
Backslash character constant:
Although it consists of two characters, it represents single character.
Each and Every combination starts with back slash(),.
They are non-printable characters.
They are used in output functions.
For Example: \t is used to give a tab space is used to give a new line.
VARIABLES:
Variable is a data name that may be used to store a data value.
variables are changeable, we can change value of a variable during execution of a program.
A programmer can choose a meaningful variable name.
A variable must be declared before it can be defined.
Datatype of Variable:
A variable in C language must be given a type, which defines what type of data the variable
will hold.
char:
Can hold/store a character init.
int:
Used to hold an integer.
float:
Used to hold a float value.
double:
Used to hold a double value.
Void
Rules to name a Variable:
1. Variable name must not start with a digit.
2. Variable name can consist of alphabets, digits and special symbols like underscore_
3. Blank or spaces are not allowed in variable name.
4. Keywords are not allowed as variable name.
5. Upper and lower case names are treated as different, as C is case-sensitive, so it is
suggested to keep the variable in lowercase.
Declaration of variables:
Declaration of variables must be done before they are used in the program.
Declaration does two things.
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
Until the variable is defined the compiler doesn't have to worry about allocating memory
space to the variable.
Syntax:
v1,v2,…..vn are the names of variables.
Variables are separated by commas( ,).
A declaration statement must end with a semicolon( ;).
For example:
Initialization of Variable: (Assigning a value to a variable)
Variable initialization means assigning a value to the variable.
C variables declared can be initialized with the help of assignment operator‘=’.
Example:
int a = 10; int a = b+c; a = 10; a = b+c;
Operators and Expressions:
Operators:
An operator is a symbol that tells the computer to perform certain mathematical or
logical manipulations.
Operators require some data to operate on and such data is called operands.
Operators in C can be classified into following categories:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Increment and Decrement Operators
Conditional Operators
Bitwise Operators
Special Operators.
Arithmetic Operators:
C programming language provides all basic arithmetic operators.
These are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus.
The ‘/’ is integer division which only gives integer part as result after division.
‘%’ is modulo division which gives the remainder of integer division as result.
Relational Operators:
Relational Operators These operators are used to compare the value of two variables.
If the relation is true then it will return value 1 or if the relation is false then it will
return value 0.
C programming offers 6 relational operators.
Logical Operators :
These operators are used to perform logical operations on the given two variables.
Logical operators are used when more than one conditions are to be tested and based
on that result, decisions have to be made.
An expression which combines two or more relational expressions is known as logical
expression.
Assignment Operators:
Assignment operators are used to assign result of an expression to a variable.
‘ = ’ is the assignment operator in C.
Furthermore, C also allows the use of shorthand assignment operators.
Shorthand operators take the form: var op = exp; where var is a variable, op is arithmetic
operator, exp is an expression.
In this case, ‘op=’ is known as shorthand assignment operator. The above assignment.
x + =y ; Here, the above statement means the same as x = x + y;
Evaluation of Expressions:
Expressions are evaluated using an assignment statement of the form:
Variable = expression;
In the above syntax, variable is any valid C variable name.
When the statement like the above form is encountered, the expression is evaluated first
and then the value is assigned to the variable on the left hand side.
All variables used in the expression must be declared and assigned values before evaluation
is attempted.
Examples of expressions are:
x=a*b–c;
y = b / c * a;
z = a – b / c + d;
Expressions are evaluated based on operator precedence and associativity rules when an
expression contains more than one operator.
Rules for evaluation of expression :
•First parenthesized sub expression left to right are evaluated.
• If parenthesis are nested, the evaluation begins with the innermost sub expression.
• The precedence rule is applied in determining the order of application of operators in
evaluating sub expressions.
• The associability rule is applied when two or more operators of the same precedence level
appear in the sub expression.
• Arithmetic expressions are evaluated from left to right using the rules of precedence.
• When Parenthesis are used, the expressions within parenthesis assume highest priority.
Order of Precedence:
At first, the expressions within parenthesis are evaluated.
If no parenthesis is present, then the arithmetic expression is evaluated from left to
right.
There are two priority levels of operators in C.
High priority: * / %
Low priority: + -
The evaluation procedure of an arithmetic expression includes two left to right passes
through the entire expression.
In the first pass, the high priority operators are applied as they are encountered and in
the second pass, low priority operations are applied as they are encountered.
we have an arithmetic expression as: x = 9 – 12 / 3 + 3 *2 – 1.
This expression is evaluated in two left to right passes as:
First Pass
Step 1: x = 9-4 + 3 * 2 – 1
Step 2: x = 9 – 4 + 6 – 1
Second Pass
Step 1: x = 5 + 6 – 1
Step 2: x = 11 – 1
Step 3: x = 10
But when parenthesis is used in the same expression, the order of evaluation gets changed.
For example ,x = 9 – 12 / (3 + 3) * (2 – 1)
When parentheses are present then the expression inside the parenthesis are evaluated
first from left to right.
The expression is now evaluated in three passes as:
First Pass
Step 1: x = 9 – 12 / 6 * (2 – 1)
Step 2: x= 9 – 12 / 6 * 1
Second Pass
Step 1: x= 9 – 2 * 1
Step 2: x = 9 – 2
Third Pass
Step 3: x= 7.
There may even arise a case where nested parentheses are present (i.e. parenthesis
inside parenthesis).
In such case, the expression inside the innermost set of parentheses is evaluated first
and then the outer parentheses are evaluated.
For example, we have an expression as: x = 9 – ((12 / 3) + 3 * 2) – 1.
The expression is now evaluated as:
First Pass:
Step 1: x = 9 – (4 + 3 * 2) – 1
Step 2: x= 9 – (4 + 6) – 1
Step 3: x= 9 – 10 -1
Second Pass
Step 1: x= - 1 – 1
Step 2: x = -2.
Evaluation of Arithmetic expression:
1. First, parenthesized sub expressions from left to right are evaluated.
2. If parentheses are nested, the evaluation begins with the innermost sub-expression.
3. The precedence rule is applied in determining the order of application of operators in
evaluating sub-expressions.
4. The associativity rule is applied when to or more operators of the same precedence appear
in a subexpression.
5. Arithmetic expressions are evaluated from left to right using the rules of precedence.
6. When parentheses are used, the expressions within parentheses assume highest priority.
Type conversion in expressions :
Implicit Type Conversion :
C automatically converts any intermediate values to the proper type so that expression
can be evaluated without losing any significance.
This automatic conversion is known as implicit type conversion.
During evaluation, if the operands are of different types, the lower type is
automatically converted to the higher type before the operation proceeds.
And the result is always of the higher type.
For example: 5/2 = 2
5/2.0 = 2.5 (Implicit type conversion)
5.0/2 = 2.5 (Implicit type conversion)
Explicit Type Conversion:
There are instances when we want to force a type conversion in a way that is different
from the automatic conversion.
This problem is solved by converting locally one of the variables to the higher type.
For Example: 5/2 = 2 (float)
5/2 = 2.5 (Explicit type conversion)
5/ (float)2 = 2.5 (Explicit type conversion)
Explicit type conversion is also known as type casting.
There are instances when we want to force a type conversion in a way that is different
from the automatic conversion.
This problem is solved by converting locally one of the variables to the higher type.
Decision Statements: if, if-else, and nested if statements:
Decision making and branching statement transfers the control from one line to
another line, based on some condition and the execution continues from there.
IF STATEMENT:
if statement is a conditional control statement.
Based on some condition(Boolean value of an expression), it executes one block of
statements, ignoring another block of statements.
If …… else:
The condition is checked.
If it is true, the Statement Block 1 is executed,( ignoring Statement Block 2 and
comes to the next statement.)
If it is false, the Statement B lock 2 is executed, (ignoring Statement Block 1 and
comes to the next statement.)
Nested if:
If, an if statement contains another if block inside it, then it is known as Nested if
statement.
The condition 1 is checked. If it is true, Condition2 is checked.
If condition1 and 2 are true Statement Block1 is executed, (ignoring Statement Block
2 and Statement Block3 and comes to the Next Statement).
if condition1 is true and Condition2 is false, Statement Block2 is executed, (ignoring
Statement Block 1 and Statement Block3 and comes to the Next Statement.)
If condition1 is false, the Statement B lock3 is executed, (ignoring Statement Block 1
and Statement Block2 and comes to the Next Statement).
SWITCH STATEMENT :
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each
switch case.
The expression is evaluated.
The value is matched with the case value
If match occurs, that statement block is executed until break statement is reached and
comes to the next statement’
If no match occurs, the default block is executed.
Rules:
The expression used in a switch statement must have an integral value
Any number of case statements are allowed within a switch.
Each case is followed by the value to be compared to and a colon.
The constant value for a case must be the same data type as the variable in the switch.
It must be a constant or a literal.
If no break appears, the flow of control will fall through to subsequent cases until a
break is reached. A switch statement can have an optional default case, which must
appear at the end of the switch.
The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.
UNIT – II
Function:
A large C program is divided into basic building blocks called C function.
C function contains set of instructions enclosed by “{ }” which performs specific
operation in a C program.
Collection of these functions creates a C program.
Types of Function in C:
1) Library Functions in C:
C provides library functions for performing some operations.
These functions are present in the c library and they are predefined.
For example :
sqrt( ) is a mathematical library function which is used for finding the square root of
any number .
scanf( ) and printf( ) are input and output library function.
strcmp() and strlen() for string manipulations.
2) User Defined Functions in C:
A user can create their own functions for performing any specific task of program
are called user defined functions.
To create and use these function we have to know these 3 elements.
1.Function Declaration
2.Function Definition
3.Function Call
Function Declaration:
A function must also be declared before its used.
Function declaration informs the compiler about the function name, parameters and
its return type.
The actual body of the function can be defined separately.
Function declaration consists of 4 parts.
return type (function type).
function name.
parameter list.
terminating semicolon
Eg:
int add (int x, int y);
Function Definition:
The function definition consists of the whole description and code of a
function.
It tells that what the function is doing and what are the input outputs for
that.
A function is called by simply writing the name of the function followed
by the argument list inside the parenthesis.
Eg:
return-type function-name(parameters)
{
declarations
statements
return value;
}
Function Call:
A function can be called by simply using the function name followed by a list
of actual parameters(or arguments).
Example:
Void main( )
{
int c;
c = add(10 , 5); // function calls
printf("%d\n", c);
}
Category of Functions:
(i ) Functions with no arguments and no return values.
(ii) Functions with arguments and no return values.
(iii) Functions with arguments and return values.
(iv) Functions with no arguments and return values.
v) Functions that return multiple values.
Nested Functions:
It provides a facility to write one function with in another function.
There is no limit as to how deeply functions can be nested.
This is called nesting of function.
Eg:
#include<stdio.h>
Void main()
{
func1();
getch();
}
Void func1()
{
for(int i=1;i<=10;i++)
{
Func2();
}
}
Void func2()
{
Printf(“\n%d”,i)
}
Recursion:
A function that calls itself is known as a recursive function.
Recursion is the process of repeating items in a self-similar way.
A function inside the same function, then it is called a recursive call of the
function.
Eg:
#include<stdio.h>
int factorial(int n)
{
if(n==0)
return 1;
else
return(factorial(n-1)*n);
}
int main()
{
int num,f;
printf("Enter a number: ");
scanf("%d",&num);
f=factorial(num);
printf("Factorial of %d = %d",num,f);
getch();
}
Call by reference:
Here, the address of the variables are passed by the calling function to the called
function.
The address which is used inside the function is used to access the actual argument.
If there are any changes made in the parameters, they affect the passed argument.
For passing a value to the reference, the argument pointers are passed to the
functions just like any other value.
Example:
#include<stdio.h>
int sum (int *n);
void main()
{
int a = 5;
printf("\n The value of 'a' before the calling function is = %d", a);
sum(&a);
printf("\n The value of 'a' after calling the function is = %d", a);
}
int sum (int *n)
{
*n = *n + 20;
printf("\n value of 'n' in the called function is = %d", n);
}
When an array is an argument to a function, only the address of the first element of the array is
passed, not a copy of the entire array.
There are three ways to declare a parameter that is to receive an array pointer.
First it can be declared as an array of the same type and size as that used to call the function,
Example:
#include <stdio.h>
void display(int num[10]); main()
{
int t[10],i; for(i=0;i<10;++i)t[i]=i;
display(t);
return 0;
}
void display(int num[10])
{
int i;
for(i=0;i<10;i++) cout <<num[i]<<' ';
}
UNIT IV
No Function Description
.
3) strcat(first_string, concats or joins first string with second string. The result of the string is
second_string) stored in first string.
4) strcmp(first_string, compares the first string with second string. If both strings are same, i
second_string) returns 0.
STRING LENGTH
The strlen() function returns the length of the given string. It doesn't count null character.
Syntax
strlen(Varibale name);
Example
#include<stdio.h>
#include <string.h>
void main()
{
char ch[20];
int x;
ch=”HELLO”;
x= strlen(ch);
printf("Length of string is: %d",x);
}
Output:
COPY STRING
Syntax
Strcpy(variable1,variable2);
#include<stdio.h>
#include <string.h>
void main()
{
char ch1[20];
char ch2[20];
ch2=”program”;
strcpy(ch1,ch2);
printf("Value of second string is: %s",ch1);
}
Output:
The strcat(first_string, second_string) function concatenates two strings and result is returned to
first_string.
Syntax
strcat(variable1,variable2);
#include<stdio.h>
#include <string.h>
void main()
{
char ch1[10], ch2[10];
ch1=”Hai”;
ch2=”Hello”;
strcat(ch1,ch2);
printf("Value of first string is: %s",ch1);
}
Output:
COMPARE STRING
The strcmp (first_string, second_string) function compares two string and returns 0 if both strings are equal.
Syntax
strcmp(variable1,variable2);
#include<stdio.h>
#include <string.h>
void main()
{
char str1[20],str2[20];
str1[20]=”Hello”;
str2[20]=”Hello”;
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
}
Output:
STRING REVERSE
The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev() function.
Syntax
strrev(variable1);
Example
#include<stdio.h>
#include <string.h>
void main()
{
char str1[20], str2;
str1=”Name”;
printf("String is: %s",str1);
str2= strrev(str1) ;
printf("\nReverse String is: %s",str2);
}
Output:
The getchar() and putchar() are declared in the header file stdio.h. Both the functions are involved in the
input/output operations of the character.
getchar() function
The getchar() function enables the user to enter a character. getchar() function help us to get a single character
as a input for instead of scanf() function.
Syntax
Variable name=getchar();
putchar() function
The putchar() function enables the user to print a character. putchar() function help us to print a single character
as a output for instead of printf() function.
syntax
putchar(variable name);
Let's see an example to write a character using putchar() and print it on the console using putchar().
Example
#include<stdio.h>
#include <string.h>
void main()
{
char id;
printf("Enter A character: ");
id=getchar(); //read a character from user
printf("Your ID is: ");
putchar(id); //display a character
}
Output:
Enter A character: X
Your ID is: X
The gets() and puts() are declared in the header file stdio.h. Both the functions are involved in the input/output
operations of the strings.
gets() function
The gets() function enables the user to enter some characters followed by the enter key. All the characters
entered by the user get stored in a character array. The null character is added to the array to make it a string.
The gets() allows the user to enter the space-separated strings. It returns the string entered by the user.
Syntax
gets(variable name);
Reading string using gets()
#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}
Output
Enter the string?
javatpoint is the best
You entered javatpoint is the best
The gets() function is risky to use since it doesn't perform any array bound checking and keep reading
the characters until the new line (enter) is encountered. It suffers from buffer overflow, which can be avoided
by using fgets(). The fgets() makes sure that not more than the maximum limit of characters are read. Consider
the following example.
puts() function
The puts() function is very much similar to printf() function. The puts() function is used to print the string
on the console which is previously read by using gets() or scanf() function. The puts() function returns an
integer value representing the number of characters being printed on the console. Since, it prints an additional
newline character with the string, which moves the cursor to the new line on the console, the integer value
returned by puts() will always be equal to the number of characters present in the string plus 1.
syntax
puts(variable name);
Let's see an example to read a string using gets() and print it on the console using puts().
Example:
#include<stdio.h>
#include <string.h>
void main()
{
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
}
Output:
Enter your name: Sonoo Jaiswal
Your name is: Sonoo Jaiswal
File Handling in C
In programming, we may require some specific input data to be generated several numbers of times.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very large,
and only a limited amount of data can be displayed on the console, and since the memory is volatile, it is
impossible to recover the programmatically generated data again and again. However, if we need to do so, we
may store it onto the local file system which is volatile and can be accessed every time. Here, comes the need
of file handling in C.
File handling in C enables us to create, update, read, and delete the files stored on the local file system through
our C program. The following operations can be performed on a file.
There are many functions in the C library to open, read, write, search and close the file. A list of file functions
are given below:
We must open a file before it can be read, write, or update. The fopen() function is used to open a file. The
syntax of the fopen() is given below.
Syntax
FILE *fp;
fp=fopen( “filename”, “mode” );
1) File Name
2) Data Structure
3) Purpose
Mode Description
o Then, it loads the file from the disk and place it into the buffer. The buffer is used to provide efficiency
for the read operations.
o It sets up a character pointer which points to the first character of the file.
Closing File:
The fclose() function is used to close a file. The file must be closed after performing all the operations on it.
The syntax of fclose() function is given below:
Syntax
fclose( *fp );
Consider the following example which open and close a file in write and read mode.
Example
#include<stdio.h>
void main( )
{
FILE *fp ;
char ch;
fp = fopen("Input","w") ;
ch = getc ( fp ) ;
fp = fopen("Input","r") ;
printf("%c",ch) ;
fclose (fp ) ;
}
Output
Once a file is opened, reading or writing to a file is accomplished using the standard I/O routines in file. File
supports list of I/O operations are below,
The putc() function is used to write a single character into file. It outputs a character to a stream.
Syntax:
putc(c,fp);
Example:
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("Input", "w");//opening file
putc('a',fp);//writing single character into file
fclose(fp);//closing file
}
file1.txt
Reading a character in File
The getc() function returns a single character from the file. It gets a character from the stream. It returns EOF at
the end of file.
Syntax:
Variable name=getc(fp);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
fp=fopen("Read","r");
c=getc(fp);
printf("%c",c);
fclose(fp);
}
The putw() function is used to write integer value into file. It outputs integer to a stream. This function would
be useful to deal with integer data.
Syntax:
putw(variable,fp);
The getw() function returns integer data from the file. It gets integer from the stream. This function would be
useful to deal with integer data.
Syntax:
getw(fp);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int num;
num=10;
fp=fopen("Data","r");
printf(“Inserting a data in FILE”);
putw(number,fp);
printf(“Gettng a data from FILE”);
getw(fp);
fclose(fp);
}
The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.
Syntax:
Example:
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("Item", "w"); //opening file
fprintf(fp, "Hello file by fprintf"); //writing data into file
fclose(fp); //closing file
}
The fscanf() function is used to read set of characters from file. It reads a word from the file and returns EOF at
the end of file.
Syntax:
fscanf(fp,”control string”,list)
Example:
#include <stdio.h>
main()
{
FILE *fp;
char name[20]; //creating char array to store data of file
fp = fopen("Item", "r");
fscanf(fp, "%s", name);
printf(“Result%s”,name);
fclose(fp);
}
Output:
fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to write data into file at
desired location.
Syntax:
Value Meaning
0 Beginning of the file
1 Current position
2 End of the file
Statement Meaning
fseek(fp,0L,0); Beginning of the file
fseek(fp,0L,1); Current position
fseek(fp,0L,2); End of the file
Example:
#include <stdio.h>
void main()
{
FILE *fp;
fp = fopen("Data","w+");
fputs("This is c program", fp);
fseek( fp, 7, 0 );
fputs("sonoo jaiswal", fp);
fclose(fp);
}
rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have to use stream
many times.
Syntax:
rewind(fp);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("file","r");
c=fgetc(fp);
printf("%c",c);
rewind(fp); //moves the file pointer at beginning of the file
c=fgetc(fp)
printf("%c",c);
fclose(fp);
getch();
}
Output:
X
X
As you can see, rewind() function moves the file pointer at beginning of the file that is why "this is simple text"
is printed 2 times. If you don't call rewind() function, "this is simple text" will be printed only once.
ftell() function
The ftell() function returns the current file position of the specified stream. We can use ftell() function to get the
total size of a file after moving file pointer at the end of file. We can use SEEK_END constant to move the file
pointer at the end of file.
Syntax:
ftell(fp);
Example:
#include <stdio.h>
#include <conio.h>
void main ()
{
FILE *fp;
int length;
clrscr();
fp = fopen("file", "r");
fseek(fp, 0, 2);
length = ftell(fp);
fclose(fp);
printf("Size of file: %d bytes", length);
getch();
}
Output:
STACKS
Stack Model :
A stack is a linear data structure which follows Last In First Out (LIFO) principle, in which both insertion and deletion
occur at only one end of the list called the Top.
Stack Representation
The following diagram depicts a stack and its operations
Basic Operations
Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from these basic
stuffs, a stack is used for the following two primary operations −
To use a stack efficiently, we need to check the status of stack as well. For the same purpose, the following
functionality is added to stacks −
peek() − get the top data element of the stack, without removing it.
isFull() − check if stack is full.
isEmpty() − check if stack is empty.
At all times, we maintain a pointer to the last PUSHed data on the stack. As this pointer always represents the
top of the stack, hence named top. The top pointer provides top value of the stack without actually removing it.
Push Operation
The process of putting a new data element onto stack is known as a Push Operation. Push operation involves a
series of steps −
Pop Operation
Accessing the content while removing it from the stack, is known as a Pop Operation. In an array
implementation of pop() operation, the data element is not actually removed, instead top is decremented to a
lower position in the stack to point to the next value. But in linked-list implementation, pop() actually removes
data element and deallocates memory space.
Queue Representation
As we now understand that in queue, we access both ends for different reasons. The following diagram given
below tries to explain queue representation as data structure
As in stacks, a queue can also be implemented using Arrays, Linked-lists, Pointers and Structures. For the sake
of simplicity, we shall implement queues using one-dimensional array.
Basic Operations
Queue operations may involve initializing or defining the queue, utilizing it, and then completely erasing it
from the memory. Here we shall try to understand the basic operations associated with queues −
Few more functions are required to make the above-mentioned queue operation efficient. These are −
peek() − Gets the element at the front of the queue without removing it.
isfull() − Checks if the queue is full.
isempty() − Checks if the queue is empty.
In queue, we always dequeue (or access) data, pointed by front pointer and while enqueing (or storing) data in
the queue we take help of rear pointer.
Enqueue Operation
Queues maintain two data pointers, front and rear. Therefore, its operations are comparatively difficult to
implement than that of stacks.
The following steps should be taken to enqueue (insert) data into a queue −
Dequeue Operation
Accessing data from the queue is a process of two tasks − access the data where front is pointing and remove
the data after access. The following steps are taken to perform dequeue operation −
Array Implementation(Enqueue)
Linked List contains collections of nodes, which interconnected each other by a link.
Each link contains two fields
1) Data field
2) Link field
Data field contains the items.
Link field contains the link of the next item.
Last node of the list contain null pointer.
Basic Operations
Following are the basic operations supported by a list.
positionNewnode;
Newnode = malloc (size of (Struct
Node)); If (Newnode! = NULL)
{
Newnode Element = X;
Newnode Next =
PNext; P Next =
Newnode;
}
}
INSERT (25, P, L)
Print(“List
is Empty”);
}
As per the above illustration, following are the important points to be considered.
positionNewnode;
Newnode = malloc (size of (Struct
Node)); If (Newnode! = NULL)
{
Newnode Element = X;
Newnode Next =
PNext; P Next =
Newnode;
}
}
print(“List is
Empty”);
}
TREES
A tree data structure is a non-linear data structure because it does not store in a
sequential manner.
It is a hierarchical structure as elements in a Tree are arranged in multiple levels.
In the Tree data structure, the topmost node is known as a root node
Terminologies
Path − Path refers to the sequence of nodes along the edges of a tree.
Root − The node at the top of the tree is called root. There is only one root per tree and
one path from the root node to any node.
Parent − Any node except the root node has one edge upward to a node called parent.
Child − The node below a given node connected by its edge downward is called its child
node.
Leaf − The node which does not have any child node is called the leaf node.
Subtree − Subtree represents the descendants of a node.
Visiting − Visiting refers to checking the value of a node when control is on the node.
Traversing − Traversing means passing through nodes in a specific order.
Levels − Level of a node represents the generation of a node. If the root node is at level
0, then its next child node is at level 1, its grandchild is at level 2, and so on.
keys − Key represents a value of a node based on which a search operation is to be
carried out for a node.
Tree Node
The code to write a tree node would be similar to what is given below. It has a data part and
references to its left and right child nodes.
struct node
{
int data;
struct node *leftChild;
struct node *rightChild;
};
Basic Operations
The basic operations that can be performed on a binary search tree data structure, are the
following −
Tree Traversal
Traversal is a process to visit all the nodes of a tree and may print their values too. Because, all
nodes are connected via edges (links) we always start from the root (head) node. That is, we
cannot randomly access a node in a tree. There are three ways which we use to traverse a tree −
In-order Traversal
Pre-order Traversal
Post-order Traversal
Generally, we traverse a tree to search or locate a given item or key in the tree or to print all the
values it contains.
In-order Traversal
In this traversal method, the left subtree is visited first, then the root and later the right sub-tree.
We should always remember that every node may represent a subtree itself.
If a binary tree is traversed in-order, the output will produce sorted key values in an ascending
order.
We start from A, and following in-order traversal, we move to its left subtree B. B is also
traversed in-order. The process goes on until all the nodes are visited. The output of inorder
traversal of this tree will be −
D→B→E→A→F→C→G
Pre-order Traversal
In this traversal method, the root node is visited first, then the left subtree and finally the right
subtree.
We start from A, and following pre-order traversal, we first visit A itself and then move to its left
subtree B. B is also traversed pre-order. The process goes on until all the nodes are visited. The
output of pre-order traversal of this tree will be −
A→B→D→E→C→F→G
Post-order Traversal
In this traversal method, the root node is visited last, hence the name. First we traverse the left
subtree, then the right subtree and finally the root node.
We start from A, and following Post-order traversal, we first visit the left subtree B. B is also
traversed post-order. The process goes on until all the nodes are visited. The output of post-order
traversal of this tree will be −
D→E→B→F→G→C→A
Traversal is a process to visit all the nodes of a tree and may print their values too. Because, all nodes are
connected via edges (links) we always start from the root (head) node. That is, we cannot random access
a node in a tree.
Binary Trees
Definition :-
Binary Tree is a tree in which no node can have more than two
children. Maximum number of nodes at level i of a binary tree is 2i+1.
15
18 20
8 5 10
3
Fig. 3.2 Binary Tree
Binary Tree Node Declarations
StructTreeNode
{
int Element;
StructTreeNode
*Left ;
StructTreeNode
*Right;
• Full binary tree: A Binary Tree is full if every node has 0 or 2 children. In a Full
binary tree, the number of leaf nodes is number of internal nodes +1.
• Complete binary tree: A Binary Tree is complete Binary Tree if all levels are
completely filled except possibly the last level and the last level has all keys as left as
possible.
• Perfect binary tree: A Binary tree is Perfect Binary Tree in which all internal nodes have
two children and all leaves are at same level.