CP Material
CP Material
UNIT-I: Overview of computers and programming – Electronic computers then and now –
Computer hardware – Computer software – Algorithm – Flowchart – Software development method –
Applying the software development method.
Types, Operators and Expressions – Variable names – Data types and sizes – Constants –
Declarations – Arithmetic operators – Relational and Logical operators – Type conversions –
Increment and Decrement operators – Bitwise operators – Assignment operator and Expressions –
Conditional Expressions – Precedence and Order of evaluation.
UNIT-V : Reading and Writing characters – Reading and writing strings – Formatted
console I/O – Printf – Scanf – Standard C Vs Unix File I/O – Streams and Files – File System basics –
Fread and Fwrite – Fseek and Random Access I/O – Fprintf() and Fscanf() – The standard streams –
The preprocessor directives #define and #include.
Text Books:
1. Programming in c, Second Edition – Pradip Dey, Manas Ghosh, Oxford University Press.
2. “C From Theory to Practice” – George S. Tselikis – Nikolaos D. Tselikas – CRC Press.
3. “Programming with C” – R S Bichkar – University Press.
4. Programming in C and Data Structures” – J.R.Hanly, Ashok N. Kamthane and A.Ananda
Rao, Pearson Education.
*****
Page 1
UNIT – I
COMPUTER Computer is an electronic device that takes data as input from input
devices, process the instructions, and produces information as output on output devices.
(Data) (Information)
Input Devices Output Devices
Computer
(Input) (Output)
Raw content used for processing the instructions is known as data whereas processed
data is known as information.
Computer system is formed with the combination of two major components namely
hardware components and software components.
Computer Hardware:
Physical parts of the computer which are possible to touch and visible are known as
hardware components. The most important components are:
1. Input Devices
2. Output Devices
3. Central Processing Unit
4. Memory Unit
Memory Unit
1. Input Devices:
Page 2
Input devices are used to submit data to the computer for processing the instructions.
2. Output Devices:
Output devices are used to display information after processing the instructions by the
computer. The output information can be of visual or audio type depending on the type of
output device used.
Monitor:
Central processing unit (CPU) is main heart of the computer. CPU consists of three
major components namely
Arithmetic and Logical Unit (ALU)
Control Unit (CU)
Register Unit (RU)
Arithmetic and logical calculations are performed inside the arithmetic and logical
unit. Control unit is responsible for to follow up all the signals carried out by the computer.
CPU’s current instructions data values are stored temporarily inside a high-speed memory
location called register unit.
4. Memory Unit:
Page 3
Memory unit is used to store the data. Memory unit consists of an ordered sequence
of storage locations called memory cells and each memory cell has a unique address. The
data stored in a memory cell are called the contents of the cell.
A memory cell is grouping of smaller units called as bytes. Each byte is a
combination of 8 bits. Each bit is capable to the data as a binary digit 0/1.
a) Primary Memory
b) Secondary Memory
ROM stores programs or data permanently. It allows only read operation. It’s is a
non-volatile memory. i.e., the data stored doesn’t disappear even though the system is
switched off.
RAM stores programs or data or results temporarily. It allows both read and write
operations. It’s a volatile memory. i.e., the data stored will be disappearing whenever the
power is switched off.
RAM is very expensive in cost and has limited storage capacity. So that large volume
of data is not possible to store in RAM. For storing huge amount of data, it is better to select
secondary storages devices.
Page 4
First, the program must be transferred from secondary storage devices to main
memory before it can be executed. Programmer submits input data from input devices to
process the instructions. Those values are stored in the computer’s main memory.
Depending on the type of the instructions, CPU manipulates with the interaction of main
memory. Results values are again stored in main memory. Finally, the information in main
memory can be displayed on output devices and is possible to store in secondary storage
devices for future re-use.
Computer Software:
1. Operating system
2. Application software
3. Package.
1. Operating System:
2. Application Software:
Page 5
Application specific software
General purpose software can be used for more than one application.
Application specific software can be used only for its intended purpose (Only for one
application).
3. Packages:
Packages are used to store large volume of data for future use.
***
In early days, vacuum tubes are the basic electronic components used for the
calculations. Later in next generations vacuum tubes are replaced with transistors then with
integrated circuits then with microprocessors.
Using today’s technology, the entire circuit can be packaged into a single component
known as micro-processor and known as CPU.
Based on the size and performance, computers are categorized into different ways as:
Page 6
CHARACTERISTICS OF COMPUTERS
Computer performs complex calculation at a very high speed. Computer takes a few
micro/nano second to execute an operation.
Computer always gives 100% actual outputs (result), if the user provides
correct Input and Instructions. Since it is100% accurate, it is reliable.
Storage:
Computer can store a huge amount of data for the future use in auxiliary device like
floppy disk, hard disk or compact disk. The storing capacity of computer is expressed in
bytes.
Versatile:
Computers are being used in different fields such as offices, school, hospital, etc. to
perform various tasks.
Versatile means ability to perform various tasks & computer can capable to do so. A
computer can process any kind of data.
Diligence:
Personal use
School & College
Graphic designing
Audio/ Video mixing
Entertainment
Design & Modeling
Page 7
Satellites & Networking System
Research Center
Hospitals
Banks & other offices
National & Multinational organizations
Robotics etc.,
COMPUTER NETWORKS
Network is collection of systems that are communicated with each other. In network
main system is referred as server and other systems are referred as nodes. Networks are
classified into two types as:
Local Area Network (LAN)
Wide Area Network (WAN)
LAN is collection of computers that linked with each other. It is limited to a small
area like within the organization, building etc., In LAN technology systems can share
information and resources such as printers, scanners etc.,
A network that links many individual computers and local area networks over a large
geographic area is called a WAN.
***
COMPUTER LANGUAGES
a) Machine language
b) Assembly language
c) High-level languages
a) Machine language:
Machine language is formed with the combination of machine codes which are
binary numbers either 0 or 1. Machine language is also known as binary language.
Page 8
At this stage, internal circuits of a computer are made of switches, transistors and
other electronic devices that can be in one of the two states as OFF state and ON state. In
case of computers OFF state is represented by 0 and ON state is represented by 1.
b) Assembly language:
Assembly language is formed with the combination of simple English words known as
mnemonic codes like ADD, SUB, MUL etc.,
High-level languages are formed with the combination of simple English sentences.
High level languages are easier to design compared to machine language and assembly
language.
#include<stdio.h>
#include<conio.h>
main()
{
int x,y,z;
clrscr();
printf(“\nEnter Two Values:”);
scanf(“%d%d”,&x,&y);
z=x+y;
printf(“\nResult = %d”,z);
}
Most of the users are interested to design programs in high-level languages. But a
computer can understood only machine language which consists of binary digits as either 0 or
Page 9
1. So, that a mediator is required to convert the given programming language into machine
codes and vice-versa. Such mediators are known as translators.
TRANSLATORS
A translator is a program that converts the given programming language from one
type to machine codes and vice-versa. The process of conversion is known as compilation.
Assembler
Compiler
Interpreter
Compiler is a translator used to convert the high level language programs into
machine code and vice-versa.
Data
Interpreter is also used as a translator for High level language programs. It takes one
statement of a high level language at a time and translates it into machine language which is
immediately executed.
Interpreter loaded
Source Program Result
computer
Page 10
Data
Compiler and Interpreter both are translators used to convert the high-level
language program into machine code and vice versa.
Compiler converts the entire source program into machine code and displays
errors if occurred. Whereas interpreter converts line by line of the source
program into machine code and displays errors immediately, if occurred.
Designing of interpreters are easy compared to compilers.
Compilers are more efficient than interpreters.
The process of creating and running programs is falls into four stages as:
The software used to write programs is known as a text editor. The text editor allows
to enter, change and store character data. It also allows some editing features to search and
locate replace statements, copy and paste commands, move statements from one place to
another place etc.,
After typing the program in the editor, save the file in the disk. This program is
known as a source file. Source file acts as an input to the compiler for the next stage.
b) Compiling Programs
The process of converting the source program from one language into machine code
is known as compilation. Compilation process is done with either compilers or interpreters.
Preprocessor program scans the special instructions from the source program and
make substitutions in the code which is proper format for translator. After the preprocessor
Page 11
has prepared the code for compilation, translator converts the entire source program into
machine language.
The output machine language code is known as object program. The object program
code is in machine codes 0’s and 1’s.
c) Linking Programs
Module 1 Object1
Translator
Code
Source Code
Linker
Module 2 Object2
Translator
Code
Source Code
Executable
Code
Linker assembles the various objects generated by the compiler in such a manner that
all the objects are accepted as a single program during executions.
d) Executing Programs
To execute the program, it is necessary to place it in the primary memory. For this,
operating system activates loader to load the executable program into the primary memory.
When everything is loaded, the program control begins execution. The program reads
data for processing either from the user or from a file. After processing the instructions,
output can be displayed on monitor or to a file.
Source File
Compiler Page 12
Translates into
machine code
Errors Debugger
Success
Object File
Format: Binary
Format: Binary
Input Results
System
Here,
Source files are compiled with compilers. Compiler translates the source program
from high level language into machine language program. While compilation, if any
errors are occurred, and then debugger activates and shows the bugs in the program.
Whenever, the program is successfully compile without out errors then an object file
with machine code is generated by the compiler.
Linker is a program that linkers object file with other object codes and converts in
terms of executable code which is in binary format.
Page 13
Loader is a program that loads this executable code into primary memory for
execution.
Computer accepts the data from input devices and performs operations and produces
results.
***
ALGORITHM
Step 1: START
Step 1: START Step 2: READ x, y
Step 2: READ x, y Step 3: Sum ← x + y
Step 3: sum ← x + y Sub ← x – y
Step 4: WRITE sum Mul ← x * y
Step 5: STOP Div ← x / y
Step 4: WRITE Sum, Sub, Mul, Div
Step 5: STOP
Algorithm Types:
In general, the steps in an algorithm can be divided into three basic categories as:
a) Sequence algorithm
b) Selection algorithm
c) Iteration algorithm
a) Sequence algorithm:
A sequence algorithm is a series of steps in sequential order without any break. Here,
instructions are executed from top to bottom without any disturbances.
b) Selection algorithm:
Page 15
Steps of an algorithm are designed by selecting appropriate condition checking is
called as selection algorithms. Selection algorithms are designed using selection control
statements such as IF, IF-ELSE, Nested IF-ELSE, ELSE-IF Ladder and SWITCH statements.
Step 1: START
Step 2: READ x, y and z values
Step 3: IF x>y AND x>z THEN
Max ← x
ELSEIF y>z THEN
Max ← y
ELSE
Max ← z
ENDIF
Step 4: WRITE Max
Step 5: STOP
c) Iteration algorithm:
Step 1: START
Step 2: READ n value
Step 3: rev ← 0
Step 4: Repeat WHILE n > 0
k ← n MOD 0
rev ← rev * 10 + k
n ← n / 10
EndRepeat
Step 5: WRITE rev
Step 6: STOP
FLOWCHART
INPUT / OUTPUT STATEMENTS: The symbol used to represent input statements and
output statements is “Parallelogram”.
Symbol :
FLOW LINES: The symbol used to represent data flow from one place to
another place is “Arrow”. Arrow symbols are also used to connect every two symbols in the
flowchart.
Symbol :
Example :
START
READ X
WRITE X
STOP
Page 17
PROCESS STATEMENTS: The symbol used to represent processing instructions is
“Rectangle”. Assignment statements and calculation statements are placed inside the
rectangle symbol.
Symbol :
Example : SUM ← X + Y
CONNECTOR SYMBOL: The symbol used to connect every two parts of the program
flow is “Circle”.
Symbol :
When we reach the end of a column or a page and still total chart is not finished. In
this case, at the bottom of flow use a connector to show that the flow continues at the top of
the next column or page.
Example : START A
:
: :
:
STOP
A
DECISION MAKING: The symbol used for representing decision parts of the program
is “Diamond”.
Symbol :
For this symbol, input is at one way and output is either of two ways.
Example :
F
Is
x>0
T
Page 18
Additional symbols that used for designing flowcharts are:
SYMBOL DESCRIPTION
DATA BASE
SUB ROUTINE
MULTIDOCUMENTS
MERGE
Page 19
1. Addition of given two numbers.
2. Addition, Subtraction, Multiplication and Division of given two numbers.
3. Average of given three numbers.
4. Swapping of given two numbers.
5. Calculate simple interest (SI=(PTR)/100).
6. Gross Salary of an Employee Where HRA = 1500 and DA = 75% of Basic Pay
(GS=BPARY+HRA+DA).
7. Conversion of Fahrenheit Temperature into Celsius Temperature (C=(F-32)/1.8).
8. Calculate Area and Circumference of a Circle (Area= and Circumference=2∏r).
Modern projects are built using a series of interrelated phases commonly referred as
the software development life cycle (SDLC). The exact number and name of the phases of
SDLC are differing from one environment to other. One of the popular development life
cycles is Water fall model.
1. Analysis
2. Algorithm & Flowchart
3. Program Design
4. Compilation
5. Program Execution
6. Testing & Validation
Step 3: sum ← x + y
READ x, y
Step 4: WRITE sum
WRITE sum
STOP
3. Program Design: The flowchart and algorithm steps developed in the previous
phase is converted into actual programs by selecting any programming languages like C, C++
etc.,
#inlcude<stdio.h>
#include<conio.h>
main()
{
int x,y,sum;
clrscr();
pritnf(“\nEnter Two Numbers:”);
scanf(“%d%d”,&x,&y);
sum = x+y;
printf(“\nTotal:%d”,sum);
}
Example:
Run-Time Errors: These errors may occur during the execution of the programs
even though the program is successfully compiled. The most common types of run time
errors are:
Example: Divide-By-Zero, Array-Out-Of-Bounds etc.,
Logical Errors: These errors may occur due to incorrect usage of the
instructions in the program. These errors are neither detected during compilation or
execution nor cause any stoppage to the program execution. They only produce unwanted
outputs.
Page 21
Logical errors are to be detected by analyzing the outputs for different possible inputs
that can be applied to the program.
Example:
6. Testing & Validation: In this phase, the program is tested by submitting proper
input values. And then program is validated with different valid inputs. With this, the
program is maintained for future re-use.
Example:
Once testing and validation part is completed, software need to be maintained up-to-
date as company policies and government regulations etc., many organizations maintain
programs for number of years. This phase is referred as maintenance phase.
With completion of all the above phases, the program must be successfully produces
correct results.
Exercise: Apply software development method for the problem statement “ Reverse of a
given value”.
***
INTRODUCTION TO C LANGUAGE
C Language
ALGOL
BCPL
Note: In 1983, the American National Standards Institute (ANSI) began the definition of
standards for C. It was approved in December 1989.
Different ANSI versions are: C89, C95, C99, Embedded C (2008), C11 (C1X).
CHARACTERISTICS OF C LANGUAGE
3. C is a case-sensitive language.
In C language, both lower case and upper case characters are different.
5. C is a robust language. It contains rich set of built-in functions and operators that are
used to design complex programs.
C CHARACTER SET
Digits : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Page 23
Special Symbols : ~ ‘ ! @ # ^ & * ( ) [ ] { } + - / % “ , : ; < > etc.,
Example: 3X + Y = 20
KEYWORDS
The words which are predefined by the system compiler are called as keywords.
Keywords are also known as ”Reserved Words”. 32 keywords are available in C language.
Those are:
IDENTIFIER
An identifier is a name given to the variable, constant, array, structure etc. Identifiers
are defined by the users.
Example: sum
X etc.
DATA TYPES
The type of the value stored in a variable is called its data type. Data types of C
language can be classified into different types as:
Data Types
Page 24
int Array Structure
char Function Union
float Pointer Enumeration
double
C language supports char, int, float and double data types as primitive data types that
are used for storing characters, integers and real values.
The following table shows different primitive data types, memory size in bytes and
range of values possible to store.
Note:
1. Derived and user-defined data types are collectively known as complex data types.
2. Complex data types are created with the combination of primitive data types.
Page 25
VARIABLES
Declaration of Variables: All variables must be declared before they are using in the
program. Declaration of a variable directs the compiler to allocate memory for the variables.
The declaration statement begins with data type followed by the name of the variables. The
general format of declaring variables is:
Here, the right hand side value is assigned to the left hand side variable.
C-TOKENS
In a C program the smallest individual units are known as C tokens. C language has
six types of tokens as:
Page 26
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Operators
6. Special Symbols
1. Keywords: The words which are predefined by the system compiler are called as
keywords. Keywords are also known as ”Reserved Words”. 32 keywords are available in C
language.
2. Identifiers: The words which are defined by the user are known as identifiers.
Integer Constants: An integer constant refers to the sequence of digits. There are three
types of integers namely, Decimal Integers, Octal Integers and Hexa-Decimal Integers.
Hexa-Decimal Integers consist of a set of digits 0 through 9, A to F (10 to 15) with a leading
0X.
Example: 0X79 0XA76E
Real Constants: Real constant is a quantity containing fractional parts. Real constants
often called as Floating Point constants. Real constants could be written in two forms as:
Page 27
Exponential Format: The exponential format of real constant is as follows.
Example: 2179e-2
Character Constants: Character constant contains a single character enclosed within a pair of
single quotation marks.
Example: ‘A’ ‘9’ ‘#’
Example: HELLO
5. Operators: Operator is a symbol that tells the compiler to perform some action.
Example: + - & || ~ etc.
6. Special Symbols: C language supports various special symbols that perform different
types of actions.
Example: # ; etc.
C language supports some special back slash character constants which are known as
escape sequence characters that are used to format the output display. Some of them are:
CONSTANT MEANING
COMMENTS
Page 28
The lines beginning with /* and ending with */ are known as comments. These are
used in a program to enhance its readability and understanding. Comment lines are not
executable statements.
LIBRARY FUNCTIONS
Example: printf(“Hello”);
getch() ; etc.
HEADER FILES
Syntax: #include<HeaderFileName>
Or
#include “HeaderFileName”
Example: #include<stdio.h>
#include”stdio.h”
#include<conio.h>
Note: stdio.h (Standard Input Output Header File) is a header file that provides input and
output library functions.
conio.h (Console Input Output Header File) provides necessary information for
clrscr() function.
scanf() is an input statement. scanf() library function is used to provide values to the
variables as input data through the keyboard. The general format of scanf() function is:
Page 29
Syntax: scanf(“Control String”,&varname1, &varname2, . . , &varnamen);
Where,
The control string consists of the format of data being received. Control string is
formed with the combination of % symbol followed by the conversion characters of different
data types. Control strings for different data types are:
%d - int
%c - char
%lf - double
%f - float
%u - unsigned int
%ld - long int
%o - octal
%x - hexa decimal
The scanf() statement requires ‘&’ operator called address operator. The role of the
address operator is to indicate the memory location of the variables.
scanf() library function information is available in stdio.h header file.
Note: Commas, blank spaces or any other special symbol characters are not allowed in
between the control strings.
Example: scanf(“%d%d”,&x,&y);
printf() is an output statement. printf() library function is used to display any data on
the monitor. The general format of printf() function is:
Where,
The control string consists of the format of data to be displayed. Control string is
formed with the combination of % symbol followed by the conversion characters of different
data types. Control strings for different data types are:
%d - int
%c - char
%lf - double
%f - float
%u - unsigned int
%ld - long int
%o - octal
%x - hexa decimal
STRUCTURE OF A C PROGRAM
Header Files
Function Prototypes
Global Variable Declarations
main()
{
Local Variable Declarations
-----
----- /* PROGRAMMING LOGIC */
-----
}
Here,
Header files provide the necessary information that supports various library functions.
Header files are placed within the programs via #include statement.
Function prototype is a declaration statement that describes the function name, list of
arguments, type, order of arguments and type of the value returned from the function.
Variables declared inside the function are called local variables. These variables are
possible to use only within the functions.
Variables declared outside the function are called global variables. These variables
are possible to use throughout the program.
main() is a special function used by the C system to tell the compiler that where the
program execution starts. Every C program must have exactly one main function.
o Left curly brace ‘{‘ and Right curly brace ‘}’ indicates opening and ending of
the function implementation.
o All the statements between these two braces form as the function body.
Page 31
Example:
#include<stdio.h>
#inlcude<conio.h>
main()
{
clrscr();
printf(“RSR COLLEGE”);
}
SAVE : F2
FILENAME : demo.c
COMPILE : F9 (OR) ALT F9
RUN : CTRL F9
RESULT VIEW : ALT F5
Examples: Design programs for the following problem statements.
***
OPERATORS AND EXPRESSIONS
Example: x + y = 10;
Here,
x, y and 10 are operands ; + and = are operators
1. Assignment operator
2. Arithmetic operators
3. Relational operators
Page 32
4. Logical operators
5. Increment & Decrement operators
6. Conditional operator
7. Bitwise operators
8. Special operators
9. Additional operators
1. Assignment Operator:
Here, the right hand side value is assigned to the left hand side variable.
x y
Example: x = 10; 10 35
y = x+25;
#include<stdio.h>
#include<conio.h>
main()
{
int x,y;
clrscr();
x=40;
y=x+5;
printf(“\n X VALUE = %d”,x);
printf(“\n Y VALUE = %d”,y);
}
2. Arithmetic Operators:
OPERATOR MEANING
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
Page 33
Arithmetic operators are binary operators. Since, they required two operands to
perform the operation.
While performing division operation,
o If both operands are integers, result is also an integer value. Since, integer
division truncates fractional parts.
o If either operand is float, result is also a floating point value.
Modulo operator (%) can’t be applied on floating point numbers.
#include<stdio.h>
#include<conio.h>
main()
{
int x,y,sum,sub,mul,div,rem;
clrscr();
printf("\nEnter Two Numbers:");
scanf("%d%d",&x,&y);
sum=x+y;
sub=x-y;
mul=x*y;
div=x/y;
rem=x%y;
printf("\nAddition:%d",sum);
printf("\nSubtraction:%d",sub);
printf("\nMultiplication:%d",mul);
printf("\nDivision:%d",div);
printf("\nRemainder:%d",rem);
}
3. Relational Operators:
C language supports relational operators as <, >, <=, >=, == and != operators. These
operators are used to compare the given two operand values.
Any expression that forms with the combination of relational operators and operands
is termed as a relational expression.
OPERATOR MEANING
< Is Less Than
<= Is Less Than Or Equal To
> Is Greater Than
>= Is Greater Than Or Equal To
== Is Equal To
!= Is Not Equal To
The result of a relational expression is either 1 or 0. Where 1 stands for TRUE and 0
stands for FALSE.
Page 34
/* EXAMPLE PROGRAM FOR RELATIONAL OPERATORS */
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("\nResult 1:%d",14>78);
printf("\nResult 2:%d",14<78);
printf("\nResult 3:%d",25<=50);
printf("\nResult 4:%d",25>=50);
printf("\nResult 5:%d",100==100);
printf("\nResult 6:%d",100!=100);
}
4. Logical Operators:
OPERATOR MEANING
&& Logical AND
|| Logical OR
! Logical NOT
Logical AND, Logical OR operators are binary operators and Logical NOT is a unary
operator.
Logical expressions are also produces the result values as either 1 or 0, depending on
truth tables supported by the operators.
Here,
Logical AND produces result value as 1 (TRUE), if both operands are 1 (TRUE);
otherwise, result value is 0 (FALSE).
Logical OR produces result value as 0 (FALSE), if both operands are 0 (FALSE);
otherwise, result value is 1 (TRUE).
Logical NOT produces result value as 1 (TRUE), is the expression value is 0
(FALSE); otherwise, result value is 0 (FALSE).
Page 35
/* EXAMPLE PROGRAM FOR LOGICAL OPERATORS */
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("\nResult 1:%d",(14>78)&&(24<78));
printf("\nResult 2:%d",(14>78)||(24<78));
printf("\nResult 3:%d",!45);
}
++ and – operators are called increment and decrement operators. These operators are
unary operands and required only one operand.
y=x
Example: X = 7; y = x++
Y = X++; x = x+1
#include<stdio.h>
#include<conio.h>
main()
{
int x,y;
clrscr();
x=10;
y=++x;
printf("\nPre-Increment X Value:%d",x);
printf("\nPre-Increment Y Value:%d",y);
Page 36
x=45;
y=x++;
printf("\nPost-Increment X Value:%d",x);
printf("\nPost-Increment Y Value:%d",y);
}
x = x-1
Example: X = 7; y = --x
Y = --X; y=x
y=x
Example: X = 7; y = x--
Y = X++; x = x-1
#include<stdio.h>
#include<conio.h>
main()
{
int x,y;
clrscr();
x=10;
y=--x;
printf("\nPre-Decrement X Value:%d",x);
printf("\nPre-Decrement Y Value:%d",y);
x=45;
y=x--;
printf("\nPost-Decrement X Value:%d",x);
printf("\nPost-Decrement Y Value:%d",y);
}
Page 37
6. Conditional Operator:
Here,
#include<stdio.h>
#include<conio.h>
main()
{
int A,B,Max;
clrscr();
printf("\nEnter Two Numbers:");
scanf("%d%d",&A,&B);
Max=(A>B)?A:B;
printf("\nMaximum Number:%d",Max);
}
7. Bitwise Operators:
Bitwise AND (&), Bitwise OR (|), Bitwise Exclusive-OR (^) and One’s complement
(~) operators are known as bitwise logical operators. Bitwise AND, Bitwise OR and Bitwise
Exclusive-OR are binary operators and One’s complement is an unary operator.
Page 38
OPERATOR MEANING
Bit-Wise AND, Bit-Wise OR and Bit-Wise Exclusive OR follows the following bit
comparison tables.
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Here,
Bit-Wise AND compares the corresponding bits of the operands and produces 1 when
both bits are 1; 0 otherwise.
Bit-Wise OR compares the corresponding bits of the operands and produces 0 when
both bits are 0; 1 otherwise.
Bit-Wise Exclusive OR compares the corresponding bits of the operands and
produces 0 when both bits are same; 1 otherwise.
For the above operations consider the following number conversion system for octal and
hexa-decimal numbers.
0 000 0000
1 001 0001
2 010 0010
3 011 0011
4 100 0100
5 101 0101
6 110 0110
7 111 0111
8 1000
9 1001
A - 10 1010
B – 11 1011
C – 12 1100
D – 13 1101
Page 39
E – 14 1110
F - 15 1111
Example:
1. X : 011 0000000000001001
Y : 027 0000000000010111 (Octal)
X&Y : 0000000000000001 :1
X|Y : 0000000000011111 : 37
X^Y : 0000000000011110 : 36
2. X : 0X7B 0000000001111011
Y : 0X129 0000000100101001 (Hexadecimal)
X&Y : 0000000000101001 : 29
X|Y : 0000000101111011 : 17B
X^Y : 0000000101010010 : 152
One’s Complement (or) Bit Negation operator is a unary operator that complements the bits
of the given operand. i.e., Bit 0 converted into Bit 1 and Bit 1 converted into Bit 0.
Example:
X : 0X7B 0000000001111011
~X : 1111111110000100 : FF84
ii) Shift Operators: Left shift operator (<<) and right shift operator (>>) are known
as shift operators.
Left shift operator (<<): Left shift operator (<<) is a binary operator that shifts bits of
the given operand towards left hand side. It requires two integer arguments. The first
argument is the value to be shifted and the second argument is the number of bits to be
shifted. The general format of left shift operator is:
Example: Let X = 24
X << 1;
0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0
Page 40
MSB LSB
(Most Significant Bit) (Least Significant Bit)
While performing left shift operations, there is a loss of data at MSB side.
The vacated positions at LSB side are filled with zeros.
For each shift value by the number of bits, the result value is equivalent to
multiplication by 2.
Right shift operator (>>): Right shift operator (>>) is a binary operator that shifts bits of
the given operand towards right hand side. It requires two integer arguments. The first
argument is the value to be shifted and the second argument is the number of bits to be
shifted. The general format of left shift operator is:
Example: Let X = 24
X >> 1;
0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0
MSB LSB
(Most Significant Bit) (Least Significant Bit)
Result value = 12
While performing right shift operations, there is a loss of data at LSB side.
The vacated positions at MSB side are filled with zeros.
For each shift value by the number of bits, the result value is equivalent to division
with 2.
#include<stdio.h>
#include<conio.h>
main()
{
int x;
clrscr();
x=24;
printf("\nLeft Shift Result:%d",x<<2);
x=24;
printf("\nRight Shift Result:%d",x>>2);
}
Page 41
8. Special Operators:
C language supports some special operators such as unary minus operator, comma
operator, sizeof operator, pointer operators (& and *) and member selection operators (. and
->).
a) Unary minus operator: Unary minus (-) operator changes sign of the given operand.
i.e., +ve sign is changed as –ve sign and –ve sign is changed as +ve sign.
Example: +10 → -10
-456 → +456
b) Comma Operator: Comma (,) operator is used to separate the operands from one
to another.
Example: int x,y;
c) sizeof Operator: sizeof operator is a compile time operator used to return the number of
bytes occupied by the given operand. The general format of sizeof operator is:
Syntax: sizeof(Operand);
Here,
The operand may be a variable, a constant or a data type.
#include<stdio.h>
#include<conio.h>
main()
{
int k;
char p;
float z;
double t;
clrscr();
printf("\nSIZE OF K:%d Bytes",sizeof(k));
printf("\nSIZE OF P:%d Bytes",sizeof(p));
printf("\nSIZE OF Z:%d Bytes",sizeof(z));
printf("\nSIZE OF T:%d Bytes",sizeof(t));
printf("\nSIZE OF INT:%d Bytes",sizeof(int));
printf("\nSIZE OF CHAR:%d Bytes",sizeof(char));
printf("\nSIZE OF FLOAT:%d Bytes",sizeof(float));
printf("\nSIZE OF DOUBLE:%d Bytes",sizeof(double));
printf("\nSIZE OF INT VALUE:%d Bytes",sizeof(100));
printf("\nSIZE OF CHAR VALUE:%d Bytes",sizeof('A'));
printf("\nSIZE OF FLOAT VALUE:%d Bytes",sizeof(23.45f));
printf("\nSIZE OF DOUBLE VALUE:%d Bytes",sizeof(456.678));
Page 42
}
9. Additional Operators:
Syntax:
Example:
a += 2 ↔ a = a+2
a -= 5 ↔ a = a-5
a *= 3 ↔ a = a*3
a /= 2 ↔ a = a/2
a %= 4 ↔ a = a%4
#include<stdio.h>
#include<conio.h>
main()
{
int x;
clrscr();
printf("\nEnter X Value:");
scanf("%d",&x);
x+=6;
printf("\nX Value=%d",x);
x-=2;
printf("\nX Value=%d",x);
x*=4;
printf("\nX Value=%d",x);
x/=3;
printf("\nX Value=%d",x);
x%=5;
Page 43
printf("\nX Value=%d",x);
}
Classification
Depending upon the number of operands used with the operator, operators are
classified into three categories as:
a) Unary operators: Unary operator requies only one operand for implementing the
specified operation.
Example: Unary Minus operator, ++, --, ! etc.,
b) Binary operators: Binary operator requires two operands for implementing the
specified operation.
Example: +, - , *, /, %, &&, ||, < etc.,
Highest precedence operator is evaluated first before the lowest precedence operator.
If two or more operators have same precedence, it follows associativity.
Example: X = 2;
Y = X + 10 * 2;
X Y
= + *
2 22
Y = X + 20
= +
Y = 22
Page 44
Associativity: Associativity refers to the direction of evaluations as from left to right
or from right to left.
Left-to-Right associativity evaluates the expression by starting on the left and moving
to the right.
Example: 3*8/4%4*5
*/%* L→R
24 / 4 % 4 * 5
/%* L→R
6%4*5
%* L→R
2*5
*
10
a += b *= c -= 5
+= *= -= R→L
a += b *= 3
*= -= R→L
a += 15
+=
a = 23
1 ( ) [ ] -> . ++ (POSTFIX) L to R
- - (POSTFIX)
2 ++ (PREFIX) - - (PREFIX) ! ~ R to L
sizeof unary minus &(Address)
*(Pointer)
3 */ % L to R
4 +- L to R
Page 45
5 << >> L to R
6 < <= > >= L to R
7 == != L to R
8 & L to R
9 ^ L to R
10 | L to R
11 && L to R
12 || L to R
13 ?: R to L
14 = += -= *= /= %= >>= <<= &= ^= | R to L
=
15 , (comma operator) L to R
Solution: X = 7, Y = 9 and Z = 18
Solution: X = 8, Y = 2 and Z = 0
Solution: X = 5 and Y = 24
#include<stdio.h>
#include<conio.h>
main()
{
int y;
clrscr();
y=2+10*2;
printf("\nResult 1:%d",y);
y=3*8/4%4*5;
printf("\nResult 2:%d",y);
}
Page 46
TYPE CONVERSION (or) CASTING
The process of converting data item from one data type to another data type is called
type casting.
Conversion rank procedure is:
Real Values
float
double
Integer Values long double
int
short int
Character Values long int
char
1. Implicit Type Casting: If the operands are of different data types, the lower data type is
automatically converted into the higher data type by the compiler before the operation
proceeds. Such conversion is known as implicit type casting. Implicit type casting is also
known as automatic type conversion.
In implicit type casting, the result is in higher data type and there is no loss of data.
2. Explicit Type Casting: Users can also be converting the data items from one
data type to another data type. Such conversion is known as explicit type casting.
For explicit type casting, the target data type placed within in parenthesis before the
data item.
z = 14/3; z = 14.000000/3;
z = 4.000000; z = 4.666667
#include<stdio.h>
#include<conio.h>
main()
{
int x,y,z,total;
float avg;
clrscr();
printf("\nEnter Three Values:");
scanf("%d%d%d",&x,&y,&z);
total=x+y+z;
avg=(float)total/3;
printf("\nAverage Result:%f",avg);
}
***********
Page 48
UNIT – II
STATEMENTS
A statement is a syntactic construction that performs some action when the program is
executed. In C language, statements are classified into three types as:
Any sequence of simple statements can be grouped together and enclosed within a
pair of braces is termed as compound statements. Compound statements are also known as
block statements.
Example: {
int x=4, y=2, z;
z=x+y;
printf(“\nResult :%d”,z);
}
3. Control Statements
Selection control statements are used to skip one or more statements depending on the
outcome of the logical test. Selection control statements are also known as decision control
statements. C language supports decision control statements as:
Page 49
ii) if-else statement
iii) Nested if-else statement
Multi-way selection: iv) else-if ladder
v) switch statement
Syntax: if(condition)
{
Block-I Statements
}
Statements-X;
Here,
/* PROGRAM TO READ THE VALUE OF X AND PRINT Y AS Y=1 FOR X>0; Y=0
FOR X=0 AND Y=-1 FOR X<0 */
#include<stdio.h>
#include<conio.h>
main()
{
int x,y;
clrscr();
printf("\nEnter x value:");
scanf("%d",&x);
if(x>0)
y=1;
if(x==0)
y=0;
if(x<0)
y=-1;
printf("\nY value is:%d",y);
}
Page 50
Syntax: if(condition)
{
Block-I Statements
}
else
{
Block-II Statements
}
Statements-X;
Here,
First condition is evaluated. It produces either TRUE or FALSE.
If the condition outcome is TRUE, then Block-I Statements are executed by the
compiler. After executing the Block-I Statements, control reaches to Statements-X.
If the condition outcome is FALSE, then Block-II Statements are executed by the
compiler. After executing the Block-II Statements, control reaches to Statements-X.
#include<stdio.h>
#include<conio.h>
main()
{
int x;
clrscr();
printf("\nEnter one value:");
scanf("%d",&x);
if(x%2= =0)
printf("\n%d is Even Number",x);
else
printf("\n%d is Odd Number",x);
}
iii) Nested if-else statement: An if-else statement is embedded within another if-else
statement such representation is called as nested if-else statement. The general format of
nested if-else statement is:
Syntax: if(condition1)
{
if(condition2)
{
Block-I Statements
}
else
{
Block-II Statements
}
}
else
Page 51
{
Block-III Statements
}
Statements-X;
Here,
First condition1 is evaluated. It produces either TRUE or FALSE.
If the condition1 outcome is TRUE, then control enters into condition2 section.
Condition2 is evaluated and produces either TRUE or FALSE.
o If Condition2 outcome is TRUE, then Block-I Statements are executed by the
compiler. After executing the Block-I Statements, control reaches to
Statements-X.
o If Condition2 outcome is FALSE, then Block-II Statements are executed by
the compiler. After executing the Block-II Statements, control reaches to
Statements-X.
If the condition1 outcome is FALSE, then Block-III Statements are executed by the
compiler. After executing the Block-III Statements, control reaches to Statements-X.
#include<stdio.h>
#include<conio.h>
main()
{
int x,y,z;
clrscr();
printf("\nEnter Three Numbers:");
scanf("%d%d%d",&x,&y,&z);
if(x>=y)
{
if(x>=z)
printf("\nMaximum Number:%d",x);
else
printf("\nMaximum Number:%d",z);
}
else
{
if(y>=z)
printf("\nMaximum Number:%d",y);
else
printf("\nMaximum Number:%d",z);
}
}
Programs:
Page 52
1. Write a progam to read a value for X and print Y value as Y = 0 for X = 0, Y = -1 for
X < 0 and Y = 1 for X > 0.
iv) Else-If Ladder Statement: Else-If ladder statement is a multi-way statement. The
general format of else-if ladder statement is:
Syntax: if(condition1)
{
Block-I Statements
}
else if(condition2)
{
Block-II Statements
}
.
.
.
else if(conditionn)
{
Block-n Statements
}
else
{
ElseBlock Statements
}
Statements-X
Here,
First condition1 is evaluated. It produces either TRUE or FALSE.
If the condition1 outcome is TRUE, then Block-I Statements are executed by the
compiler. After executing Block-I Statements control reaches to Statements-X.
If the condition1 outcome is FALSE, then control reaches to condition2 and is
evaluated. If condition2 outcome is TRUE, then Block-II Statements are executed by
the compiler. After executing Block-II Statements control reaches to Statements-X.
If condition2 outcome is FALSE, then control reaches to condition3 and so on.
#include<stdio.h>
#include<conio.h>
main()
{
int x,y,z;
clrscr();
printf("\nEnter Three Numbers:");
scanf("%d%d%d",&x,&y,&z);
if(x>=y&&x>=z)
Page 53
printf("\nMaximum Number:%d",x);
else if(y>=z)
printf("\nMaximum Number:%d",y);
else
printf("\nMaximum Number:%d",z);
}
Programs:
1. Write a progam to read a value for X and print Y value as Y = 0 for X = 0, Y = -1 for
X < 0 and Y = 1 for X > 0.
2. Write a program to print electric bill paid by the customer based on
Consumption Units Rate of Charge
0 – 100 Rs: 1.75
101 – 200 Rs: 2.25
201 – 300 Rs: 3.75
Above 300 Rs: 5.00
3. Write a program to print status of the student according to the following rules:
Average Marks Grade
0 to 39 FAIL
40 to 49 THIRD DIVISION
50 to 59 SECOND DIVISION
60 to 79 FIRST DIVISION
80 to 100 HONOUR
v) switch Statement: switch statement is also a multi-way decision that allows for
placing different block statements and execution depends on the result of the expression
value. The general format of switch statement is:
Syntax: switch(Expression)
{
case value1: Block-I Statements
break;
case value2: Block-II Statements
break;
.
.
.
case valuen: Block-n Statements
break;
default: DefaultBlock Statements
}
Statements-X
Page 54
Here,
First Expression is evaluated and produces an integer value.
Now, the expression value will be compared with case values value1, value2, ---,
valuen by the compiler. If any case value coincide with the expression value then that
particular block statements are executed until break statement is encountered.
break is a branch control statement used to transfer the control out of the loop.
If the expression value doesn’t match with any case value then default block
statements will be executed. Default block is optional block.
Case values value1, value2, …. are either integer constants (or) character constants.
Case labels must be unique. No two case labels should have the same name.
Generally switch statements are used for creating menu programs.
#include<stdio.h>
#include<conio.h>
main()
{
int ch;
clrscr();
printf("\n1:RED\n2:GREEN\n3:BLUE");
printf("\nEnter Your Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\nRED SELECTED"); break;
case 2:printf("\nGREEN SELECTED"); break;
case 3:printf("\nBLUE SELECTED"); break;
default:printf("\nINVALID SELECTION");
}
}
Switch statement allows for executing same block statements for more than one case
with different syntax as:
Syntax: switch(Expression)
{
case value1:
case value2:
:
:
case valuen: Block Statements;
break;
:
default: defaultBlockStatements
}
Page 55
/* PROGRAM TO CHECK WHETHER A GIVEN CHARACTER IS VOWEL OR NOT */
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
clrscr();
printf("\nEnter A Character:");
scanf("%c",&ch);
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':printf("\nVOWEL");
break;
default:printf("\nCONSONANT");
}
}
CONDITIONAL EXPRESSION
Here,
Page 56
/* EXAMPLE PROGRAM FOR CONDITIONAL EXPRESSION */
#include<stdio.h>
#include<conio.h>
main()
{
int A,B,Max;
clrscr();
printf("\nEnter Two Numbers:");
scanf("%d%d",&A,&B);
Max=(A>B)?A:B;
printf("\nMaximum Number:%d",Max);
}
#include<stdio.h>
#include<conio.h>
main()
{
int A,B,Max;
clrscr();
printf("\nEnter Two Numbers:");
scanf("%d%d",&A,&B);
if(A>B)
Max=A;
else
Max=B;
printf("\nMaximum Number:%d",Max);
}
b) Loop (or) Iterative Control Statements
Series of
Statements
Pre-test and Post-test loops: A loop can be either a pre-test loop or a post-test loop.
In a pre-test loop, the condition is checked before beginning of the each iteration. If
the condition outcome is TRUE, then associated statements are executed. The process is
Page 57
repeated until the test condition reaches to FALSE. Pre-test loop is also known as entry-
controlled loop.
FALSE
Con
diti
on
TRUE
Statements
Statements
FALSE
Cond
ition
TRUE
i) while statement
Page 58
ii) do-while statement
iii) for statement
i) while statement: While statement is used for repetitive execution of statements more
than once.
Syntax: while(condition)
{
- - -
- - - Block Statements
}
Here,
First the condition is evaluated. It produces either TRUE or FALSE.
If the condition is TRUE, then Block Statements will be executed by the compiler.
After executing the Block Statements, again control reaches to condition section and
is evaluated.
The process is repeated until the condition becomes FALSE.
When the condition reaches to FALSE, then the control is transferred out of the loop.
Flowchart:
Condition
F
T
Block Statements
#include<stdio.h>
#include<conio.h>
main()
{
int i,n;
clrscr();
Page 59
printf("\nEnter how many numbers:");
scanf("%d",&n);
printf("\nNatural Numbers Are:");
i=1;
while(i<=n)
{
printf(" %d",i);
i=i+1;
}
}
ii) do-while statement: do-while is also a loop control statement used for
repetitive execution of statements. The general format of a do-while statement is:
Syntax: do
{
- - -
- - - Block Statements
- - -
}
while(condition);
Flowchart:
Block Statements
T F
is
Condition
Here,
First the compiler executes Block statements and then enters into condition
section.
Condition is evaluated and produces either TRUE or FALSE.
If the condition outcome is TRUE, then again control enters into Block
Statement and is executed. This procedure is repeated until the condition
becomes FALSE.
When the condition outcome reaches to FALSE, then the control is transferred
out of the loop.
Note: The main difference between while and do-while statements is do-while statement
executed the Block Statements at least once even though the condition becomes FALSE.
Since, compiler checks the condition after executing the Block Statements.
iii) for statement: for is also a loop control statement used for repetitive execution of
statements. The general format of a for statement is:
Flowchart:
Initialization
Condition F
Block Statements
Increment /
Decrement
Here,
Page 61
First control reaches to Initialization section. Initialization starts with assigning a
value to the variable and executes only once at the start of the loop. Then control
enters into Condition section.
Condition is evaluated and produces either TRUE or FALSE.
If the outcome of the Condition is TRUE, then Block Statements are executed by the
compiler. After executing Block Statements, control reaches to Increment/Decrement
section.
Increment/Decrement section updates the control variables. After updating the
control variable, again control reaches to Condition section and is evaluated.
This procedure is repeated until the condition becomes FALSE.
When Condition outcome becomes FALSE, then control is transferred out of the loop.
Programs:
1. Write a program to read a list of numbers and print even and odd sum, even and odd
count from the list.
2. Write a program to print distance travelled by a vehicle in regular intervals of time
using the equation distance = ut + 0.5 a t2 ; Where, u is velocity, t is time period and a
is acceleration.
1. More than one variable can be initialized at a time in the for statement. In such
situations the variables are separated with comma operator. Similarly, the
Increment/Decrement section may also have more than part.
Ex: for(i = 1, j = 5 ; j >= 1 ; i++ , j--)
{
printf(“\n”);
printf(“%d \t %d”,i,j);
}
Page 62
3. An important feature of for loop is that one or more sections (Initialization and
Increment/Decrement) can be omitted. In such situations, initialization has
been done before the for statement and the control variable is incremented or
decremented inside the loop.
Ex: i = 1;
j = 5;
for ( ; i<=5; )
{
printf(“\n%d \t %d”,i,j);
i++;
j--;
}
NESTED LOOPS
Loop control statements can be placed within another loop control statement. Such
representation is known as nested loops. In these situations, inner loop is completely
embedded within outer loop.
1) 1 2) 1 3) 3 2 1 4) *
12 22 21 **
123 333 1 ***
#include<stdio.h>
#include<conio.h>
main()
{
int k,n=1,q=0,x,n;
clrscr();
printf("\nEnter how many Rows:");
Page 63
scanf("%d",&p);
printf("\nRESULT IS:\n");
while(q<p)
{
for(k=20-q;k>=1;k--)
printf(" ");
for(x=0;x<=q;x++)
{
if(x==0||q==0)
n=1;
else
n=(n*(q-x+1))/x;
printf(" %d",n);
}
printf("\n");
++q;
}
}
i) break statement: The break statement is used in loop control statements such as while,
do-while, for and switch statements to terminate the execution of the loop or switch
statement. The general format of break statement is:
Syntax: break;
When the keyword break is encountered inside any C loop, control automatically skip
entire loop and passes to the statements available after the loop.
Page 64
ii) continue statement: The continue statement is used in while, do-while and for
statements to terminate the current iteration of the loop. The general format of continue
statement is:
Syntax: continue;
When the keyword continue is encountered inside any C loop, compiler skips the
remaining statements available after the continue statement and control reaches to next
iteration of the loop.
main()
{
int i,x,sum=0;
clrscr();
for(i=1;i<=5;i++)
{
printf("\nEnter Number %d:",i);
scanf("%d",&x);
if(x<0)
continue;
sum=sum+x;
}
printf("\nTotal:%d",sum);
}
iii) goto statement: The goto statement is used to alter the normal sequence of program
execution by transferring the control to some other part of the program. In its general form,
the goto statement can be written as:
Where,
Label is an identifier used to specify the target statements to which control will be
necessary to transfer. The target statements must be labeled and the label must be followed
by a colon as:
Each label statement with in the program must have a unique name.
Depending on passing the control, goto statements can be classified as forward jump and
backward jump.
___ Label : _ _ _
goto Label; _ __
___ __ _
___ goto Label;
Label : _ _ _ ___
Page 65
___ ---
/* Example program for FORWARD JUMP */ /* Example program for BACKWARD JUMP */
main() main()
{ {
int i,x,sum=0; int i,x,sum;
clrscr(); clrscr();
for(i=1;i<=5;i++) tp:
{ sum=0;
printf("\nEnter Number %d:",i); for(i=1;i<=5;i++)
scanf("%d",&x); {
if(x<0) printf(“\nEnter Number %d:”,i);
goto tp; scanf(“%d”,&x);
sum=sum+x; if(x<0)
} goto tp;
tp: sum=sum+x;
printf("\nTotal:%d",sum); }
} printf(“\nTotal :%d”,sum);
}
Additional Statements
i) return statement:
The return statement is used to return from a function. The general form of a return
statement is:
If the function does not return any value, simply use the syntax as:
Syntax: return;
The exit() function causes immediate termination of the entire program execution.
The general form of the exit() function is:
Syntax: exit();
***
ARRAYS
Page 66
subscripts determines the dimensionality of the array. Depending on the number of
subscripts used, arrays can be classified into different types as:
1. Single (or) One dimensional arrays
2. Double (or) Two dimensional arrays
3. Multi dimensional arrays
Where,
datatype specifies the type of the elements that will be stored in the array.
ArrayName specifies the name of the array that follows same rules as a valid
identifier.
size indicates the maximum number of elements that can be stored inside the array.
Index Values 0 1 2 3 4
x
Let ‘m’ is the size of an array, the one dimensional array can be defined as – “One
dimensional array is a collection of m homogeneous data elements that are stored in m
memory locations”.
1. Each memory location size is 2 bytes. Since, the data type is int. Compiler allocates
a total of 10 bytes.
2. All memory locations share a common name as ‘x’.
3. An individual element of the array is accessed with index as:
main()
{
int n,i,x[10];
clrscr();
printf("\nEnter how many elements:");
Page 67
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Element %d:",i+1);
scanf("%d",&x[i]);
}
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf("%5d",x[i]);
}
1) We can initialize the elements of the array in the same way as the ordinary variables
when they are declared. The general form of initializing the one dimensional array is:
Syntax: datatype ArrayName[size] = {List of Values};
main()
{
int x[5]={11,22,33,44,55}, i;
clrscr();
printf("\nArray Elements Are:");
for(i=0;i<=4;i++)
printf(" %d",x[i]);
}
2) While initializing elements, size may be omitted. In such cases, the compiler
allocates sufficient memory for all initialized elements.
Example: int k[ ] = {11,22,33,44,55}; /* 11 22 33 44 55 */
Where,
datatype specifies the type of the elements that will be stored in the array.
ArrayName specifies the name of the array that follows same rules as a valid
identifier.
Page 68
size1specifies row size i.e., number of rows.
size2specifies column size i.e., number of columns.
0 1 2 3
K 1
Let ‘m’ is the row size and ‘n’ is the column size, then a double dimensional array can
be defined as – “Double dimensional array is a collection of m x n homogeneous data
elements that are stored in m x n successive memory locations”.
main()
{
int m,n,i,j,x[10][10];
clrscr();
printf("\nEnter how many rows:");
scanf("%d",&m);
printf("\nEnter how many columns:");
scanf("%d",&n);
printf("\nEnter Array Elements:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&x[i][j]);
}
Page 69
1) Like one-dimensional arrays, double dimensional arrays can also be initialized by
placing a list of values enclosed within braces as:
Syntax: datatype ArrayName[size1][size2] = {List of Values};
main()
{
int x[2][3] = {11,22,33,44,55,66},i,j;
clrscr();
printf("\nArray Elements Are:");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf(" %d",x[i][j]);
}
}
2) List of values can also be initialized in the form of a matrix representation as:
Syntax: datatype ArrayName[size1][size2] = { {Row1 Values},
{Row2 Values},
----
--- -
};
3) While initializing list of values, size1 (Row Size) may be omitted. In such cases,
the compiler allocates sufficient memory for all initialized elements.
Example: int k[ ][3] = { {1,2,3}, {4,5,6}, {2,4,5} };
The above example is a three dimensional array. Here, compiler allocates memory as
in terms of tables.
Let m1, m2, - - - , mn are the sizes, then a multidimensional array can be defined as –
“Multidimensional array is a collection of m1 x m2 x - - - - x mn homogeneous data elements
that are stored in m1 x m2 x - - - - x mn successive memory locations”.
Page 70
/* PROGRAM TO READ A MULTDIMENSIONAL ARRAY AND PRINT IT */
main()
{
int m,n,p,i,j,k,x[10][10][10];
clrscr();
printf("\nEnter how many Tables:");
scanf("%d",&m);
printf("\nEnter how many rows:");
scanf("%d",&n);
printf("\nEnter how many columns:");
scanf("%d",&p);
printf("\nEnter Array Elements:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
for(k=0;k<p;k++)
scanf("%d",&x[i][j][k]);
}
}
printf("\nArray Elements Are:");
for(i=0;i<m;i++)
{
printf("\n");
printf("\n");
for(j=0;j<n;j++)
{
printf("\n");
for(k=0;k<p;k++)
printf("%5d",x[i][j][k]);
}
}
}
#include<stdio.h>
#include<conio.h>
main()
Page 71
{
int x[2][3][2]={1,2,3,4,5,6,7,8,9,10,11,12},i,j,k;
clrscr();
printf("\nArray Elements Are:\n\n\n");
for(i=0;i<2;i++)
{
printf("\n\n");
for(j=0;j<3;j++)
{
printf("\n");
for(k=0;k<2;k++)
printf(" %d",x[i][j][k]);
}
}
}
2) List of values can also be initialized in the form of a table representation as:
Example: int k[2][3][2] = { { {1,2}, {4,5},{6,7}}, {{8,9},{10,11},{12,13}} };
3) While initializing list of values, size1 may be omitted. In such cases, the compiler
allocates sufficient memory for all initialized elements.
Example: int k[ ][3][2] = {11,22,33,44,55,66,77,88,99,10,11,12};
***
STRINGS
Any group of characters defined between double quotation marks is a constant string.
Ex: “KAVALI”
Each string is terminated by the null character (‘\0’), which indicates the end of the
string.
When the compile assigns a character string to a character array, it automatically
supplies a null character at the end of the string.
%s format specification is used to read and write a string.
The ampersand ‘&’ symbol is not required before the variable name in scanf()
function while reading strings.
Page 72
Main problem with the scanf() function is that it terminates its input on the first white
space it found.
main()
{
char city[10];
clrscr();
printf("\nEnter City Name:");
scanf("%s",city);
printf("\nRESULT:%s",city);
}
main()
{
char city[10];
int i,n;
clrscr();
printf("\nEnter how many Characters:");
scanf("%d",&n);
printf("\nEnter %d Characters:",n);
for(i=0;i<n;i++)
scanf("%c",&city[i]);
city[i]='\0';
printf("\nRESULT:%s",city);
}
gets() and puts() functions: gets() and puts() functions are library functions used for to read
and write an entire line of text including blank spaces.
Syntax: gets(string);
puts(string);
Each of these library functions accepts a single argument as string. These functions
are defined in “stdio.h” head file. In gets(), the string will be entered from the keyboard and
terminated with a new line character.
/* EXAMPLE PROGRAM */
main()
{
char str[50];
clrscr();
printf("\nEnter a line of text:");
gets(str);
printf("\nRESULT:");
puts(str);
Page 73
}
****************
UNIT – III
Page 74
} }
set()
{
--
}
Advantages:
FUNCTION TYPES
C functions are classified into two types as: Library functions and User-defined
functions.
a) Library functions: Functions that are predefined by the compiler are known as
library functions.
Ex: scanf(), printf(), getch(), getche(), etc.,
For all the library functions, definitions and necessary information is available in
header files. Some of the important header files are:
stdio.h - Standard Input and Output header file
conio.h - Console Input and Output header file
stdlib.h - Standard library header file
ctype.h - Character type header file
math.h - Mathematical header file
ctype.h header file provides several library functions used for character testing and
conversions.
Functions:
Page 75
Function determines whether the given argument is alphabet or not. If the character is
alphabet, it returns a non-zero value that represents TRUE; otherwise, it returns ‘0’ that
represents FALSE.
Programs
1. Write a program to count number of alphabets, digits, words and special symbols of a given line.
2. Write a program to convert lower case characters into upper case characters and vice-versa of a
given line.
3. Write a program to accept a line and print number of vowels, consonants, blank spaces, digits and
special characters.
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
main()
{
char str[100];
int i,nv,nc,nb,nd,sp;
clrscr();
nv=0;
nc=0;
nb=0;
nd=0;
Page 76
sp=0;
printf("\nEnter A Line=");
gets(str);
for(i=0;str[i]!='\0';i++)
{
if(isalpha(str[i]))
{
if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u'||
str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')
nv=nv+1;
else
nc=nc+1;
}
else if(isspace(str[i]))
nb=nb+1;
else if(isdigit(str[i]))
nd=nd+1;
else
sp=sp+1;
}
printf("\n Number of Vowels = %d",nv);
printf("\nNumber of Consonants = %d",nc);
printf("\nNumber of Blank Spaces = %d",nb);
printf("\nNumber of Digits = %d",nd);
printf("\nNumber of Special Characters = %d",sp);
}
math.h header file provides several library functions used for mathematical operations.
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
float a,b,c,r1,r2,dis;
clrscr();
printf("\nEnter a,b and c values:");
scanf("%f%f%f",&a,&b,&c);
dis=(b*b)-(4*a*c);
if(dis = =0 )
{
printf("\nROOTS ARE REAL AND EQUAL");
r1=-b/(2*a);
r2=-b/(2*a);
printf("\nROOT 1 = %.2f",r1);
printf("\nROOT 2 = %.2f",r2);
}
else if(dis>0)
{
Page 78
printf("\nROOTS ARE REAL AND DIFFRENT");
r1=(-b+sqrt(dis))/(2*a);
r2=(-b-sqrt(dis))/(2*a);
printf("\nROOT 1 = %.2f",r1);
printf("\nROOT 2 = %.2f",r2);
}
else
printf("\nROOTS ARE IMAGINARY");
}
Where,
FunctionName is the name given to the function, which allows the same rules as valid
identifier.
ReturnType specifies the type of the data returned from the function to calling
function.
datatype arg1, - - - - are the arguments used to perform the function implementation.
Argument names arg1, -- , argn are optional.
2. Function call: The function call statement invokes the function by passing
arguments. The arguments which passed at the function call are called “actual arguments”.
The general format of a function call is:
Where, var1,----, varn are actual values passed to the function definition.
Note: The function name, type, number and order of arguments listed in the function call
statement must match with that of the function prototype and function definition.
Example: p = Fact(5);
Page 79
3. Function body (or) definition: Function definition contains implement code of
the function. The general format of a function definition is:
---
Function proto type
- --
main()
{
--
Function call Calling Function
--
}
Function definition
{
-- Called Function
--
}
Page 80
/* PROGRAM TO FIND FACTORIAL OF A GIVEN NUMBER USING FUNCTIONS */
#include<stdio.h>
#include<conio.h>
int Fact(int);
main()
{
int p,n;
clrscr();
printf("\nEnter a Value:");
scanf("%d",&n);
p=Fact(n);
printf("\nFactorial Value:%d",p);
}
int Fact(int k)
{
int i,f=1;
for(i=1;i<=k;i++)
f=f*i;
return f;
}
FUNCTION CATEGORIES
Depending on whether arguments are passed or not and function returns any value or
not, functions are classified into different categories as:
Case 1: When a function has no arguments, it does not receive any data from the
calling function. Similarly when it does not return any value, the calling function does not
receive any data from the called function.
Note: If the function does not return any value, return type must be void.
/* EXAMPLE PROGRAM */
#include<stdio.h>
#include<conio.h>
void sum();
main()
{
clrscr();
sum();
}
void sum()
Page 81
{
int x,y,z;
printf("\nEnter Two Values:");
scanf("%d%d",&x,&y);
z=x+y;
printf("\nResult = %d",z);
}
Case 2: In this case, calling function send data to the called function. But, called
function does not return any value after completing function implementation.
/* EXAMPLE PROGRAM */
#include<stdio.h>
#include<conio.h>
void sum(int,int);
main()
{
int x,y;
clrscr();
printf("\nEnter Two Values:");
scanf("%d%d",&x,&y);
sum(x,y);
}
void sum(int p,int q)
{
int z;
z=p+q;
printf("\nResult = %d",z);
}
Case 3: In this case, calling function does not send data to the called function. After
implementation of the function, called function return value to the calling function.
/* EXAMPLE PROGRAM */
#include<stdio.h>
#include<conio.h>
int sum();
main()
{
int p;
clrscr();
p=sum();
printf("\nResult = %d",p);
}
int sum()
{
int x,y,z;
Page 82
printf("\nEnter Two Values:");
scanf("%d%d",&x,&y);
z=x+y;
return z;
}
Case 4: In this case, calling function send data to the called function and called
function also returns some value to the function call after completing the function
implementation.
/* EXAMPLE PROGRAM */
#include<stdio.h>
#include<conio.h>
int sum(int,int);
main()
{
int x,y,z;
clrscr();
printf("\nEnter Two Values:");
scanf("%d%d",&x,&y);
z=sum(x,y);
printf("\nResult = %d",z);
}
int sum(int p,int q)
{
int t;
t=p+q;
return t;
}
Programs:
The data flow between the calling and called functions can be divided into three
strategies as:
Downward flow
Upward flow
Bi-directional flow
Functions can also be included within another function. Such representation is known
as nested functions.
#include<stdio.h>
#include<conio.h>
void fun1();
void fun2();
main()
{
clrscr();
printf("\nMAIN STARTS");
fun1();
printf("\nMAIN ENDS");
}
void fun1()
Page 84
{
printf("\nFUNCTION 1 STARTS");
fun2();
printf("\nFUNCTION 1 ENDS");
}
void fun2()
{
printf("\nFUNCTION 2 STARTS");
printf("\nFUNCTION 2 ENDS");
}
RECURSION
A function calls itself is called recursion and the function is called as recursive
function. The main advantage of recursion is to avoid the length of the code.
Ex: main()
{
--
main();
--
}
2. Indirect recursion: A function calls another function, which initiates to call of the initial
function is known as indirect recursion.
Note:
1. Recursion uses more memory compare to non-recursive functions.
Page 85
2. While using recursion, control may falls into infinite loop. This disadvantage can be
avoided by placing a return statement associated with if-else statement somewhere to force
the control without calling recursive call.
So that in recursion concept, two types of conditions must be placed. Those are base
condition and recursive condition. Base condition avoids the recursive call and recursive
condition calls the recursive procedure.
#include<stdio.h>
#include<conio.h>
int Fact(int);
main()
{
int p,k;
clrscr();
printf("\nEnter a Value:");
scanf("%d",&k);
p=Fact(k);
printf("\nFactorial Value:%d",p);
}
int Fact(int n)
{
if(n= =1)
return 1;
else
return n*Fact(n-1);
}
Variables declared inside the function definition or block is called local variables.
Local variables can be used by only that particular function or block where it was defined.
Variables declared outside the function definition are called global variables. Global
variables can be used by any function at any time.
#include<stdio.h>
#include<conio.h>
void change();
main()
{
int x=10;
clrscr();
printf("\nValue 1:%d",x);
Page 86
change();
printf("\nValue 2:%d",x);
}
void change()
{
int x;
x = 20;
printf("\nValue 3:%d",x);
}
#include<stdio.h>
#include<conio.h>
void change();
int x=10;
main()
{
clrscr();
printf("\nValue 1:%d",x);
change();
printf("\nValue 2:%d",x);
}
void change()
{
x=x+10;
printf("\nValue 3:%d",x);
x=x+10;
}
STORAGE CLASSES
Storage class deals with scope and life time of variables with four access specifiers
namely auto, extern, static and register. Storage class access specifiers provide access
permission of the variables.
C language supports four access specifiers as: auto, extern, static and registers that
are used with data type in the declaration statement of a variable. Hence, the storage classes
are termed as:
Page 87
1. Automatic Storage class:
Variables declared inside the function or block starts with the keyword ‘auto’ are
termed as automatic variables. The general format of an automatic variable is:
Note: Variables declared inside the function or block without a storage class specification,
by default compiler assigns ‘auto’ keyword and treated as automatic variables.
#include<stdio.h>
#include<conio.h>
void Fun();
main()
{
auto int x=100;
clrscr();
printf("\nValue 1:%d",x);
Fun();
}
void Fun()
{
int y=20;
printf("\nValue 2:%d",y);
}
Variables declared outside the function with the keyword ‘extern’ are termed as
external variables. The general format of an external variable is:
Page 88
External variables are declared outside of all functions. Hence, an external variable is
also known as a global variable.
Scope of the external variable is entire file and other files also and the life time is until
the program execution comes to end (global).
Note: Variables declared outside the function without a storage class specification, by
default compiler assigns ‘extern’ keyword and treated as external variables.
#include<stdio.h>
#include<conio.h>
void Fun();
main()
{
clrscr();
printf("\nValue 1:%d",x);
Fun();
}
void Fun()
{
printf("\nValue 2:%d",y);
}
3. Static Storage class:
Variables declared inside the function or outside the function with the keyword
‘static’ are termed as static variables. The general format of a static variable is:
Internal static variables: Variables declared inside the function with ‘static’
access specifier are known as internal static variables.
Page 89
The scope of internal static variable is up to the end of the function in which they are
defined and life time is throughout the remainder of the program.
#include<stdio.h>
#include<conio.h>
void Fun();
main()
{
int i;
clrscr();
for(i=1;i<=3;i++)
Fun();
}
void Fun()
{
static int x=10;
x=x+5;
printf("\nValue :%d",x);
}
External static variables: Variables declared outside the function with ‘static’
access specifier are known as internal static variables.
These variables are available to all functions. The scope of external static variable is
only in that file and the life time is global.
#include<stdio.h>
#include<conio.h>
void Fun();
static int x=10;
main()
{
int i;
clrscr();
for(i=1;i<=3;i++)
{
printf("\nValue :%d",x);
Fun();
}
}
void Fun()
{
x=x+5;
}
4. Register Storage class:
User can also be possible to tell the compiler that a variable should be kept in register
unit, instead of keeping in memory unit by using the keyword ‘register’. Such variables are
called register variables. The general format of a register variable is:
Page 90
Syntax : register datatype identifier;
#include<stdio.h>
#include<conio.h>
main()
{
register int x;
clrscr();
x=10;
printf("\nValue :%d",x);
}
/* PROGRAM TO FIND LCM OF GIVEN TWO VALUES USING RECURSION */
#include<stdio.h>
#include<conio.h>
int LCM(int,int);
main()
{
int x,y,z;
clrscr();
printf("\nEnter Two Values = ");
scanf("%d%d",&x,&y);
z=LCM(x,y);
printf("\nLCM Result Value = %d",z);
}
Page 91
SYMBOLIC CONSTANTS
Symbolic constant is a constant representation that does not change during program
execution. #define statement is used for defining symbolic constants.
Rules:
#include<stdio.h>
#include<conio.h>
#define PI 3.14159
main()
{
float R,Area;
clrscr();
printf("\nEnter Radius of the Circle:");
scanf("%f",&R);
Area=PI*R*R;
printf("\nAREA OF THE CIRCLE IS:%.2f",Area);
}
TYPE QUALIFIERS
const and volatile qualifiers can be applied to any variables, but restrict qualifier may only
applied to pointer.
Constant variable
Page 92
#include<conio.h>
main()
{
const int x=10;
clrscr();
printf("\nResult = %d",x);
}
Volatile variable
Variables that can be changed at any time by external programs or the same program
are called as volatile variables. For this the keyword volatile is placed before the variable
declaration.
#include<stdio.h>
#include<conio.h>
main()
{
volatile int x=10;
clrscr();
printf("\nResult 1= %d",x);
x=20;
printf("\nResult 2= %d",x);
}
C PREPROCESSOR COMMANDS / DIRECTIVES
C compiler is made with two programs namely preprocessor program and translator
program.
Preprocessor is a program that processes the source code before it passes through the
compiler. Preprocessing is done under the control of preprocessor commands or directives.
Compilation Process
- - Pre - - - - Trans - - - --
- - Processor lator - - - --
- - - -
- - Translation - - - --
All preprocessor directives are begin with the symbol ‘#’ and do not require a
semicolon at the end. Preprocessor directives are placed in the source program before the
main () function.
Page 93
In C language, preprocessor directives are divided into three categories as:
In this representation, the identifier in the program replaced with the macro value.
This type of macro’s are called simple macros.
#include<stdio.h>
#include<conio.h>
#define area(x) 3.14159*x*x
main()
{
float R=3.97,A;
clrscr();
A=area(R);
printf("\nAREA OF THE CIRCLE IS:%.2f",A);
}
In this program, wherever the preprocessor found area(x), it expands it into the
statement as 3.14159*x*x. After the code has passed through the preprocessor, compiler
works on this as:
main()
{
float R=3.97,A;
clrscr();
A=3.14159*R*R;
printf("\nAREA OF THE CIRCLE IS:%.2f",A);
}
c) Simple programming code with multiple lines can also be replaced by using macro
substitution. In such cases, a ‘\’ character is used at the end of each line while defining the
macro.
/* EXAMPLE PROGRAM */
#include<stdio.h>
Page 94
#include<conio.h>
main()
{
int a=35,b=79;
clrscr();
Max(a,b);
}
When this program passed through the processor, then compiler works on this as:
main()
{
int a=35,b=79;
clrscr();
if(a>b)
printf(“\n%d is Maximum”,a);
else
printf(“\n%d is Maximum”,b);
}
File inclusion directives causes’ one file to be included in another file. The file may
contain functions or macro definitions. The preprocessor command for a file inclusion is:
First format is used to direct the preprocessor for including header files from the
system library.
Second format is used to direct the preprocessor for including header files from the
user defined directories.
COMMAND MEANING
#if Expression When Expression is TRUE, then the code that follows is
included for compilation
Page 95
#endif Terminates the conditional command
#else Specifies alternative code in two way decision
#elif Expression Specifies alternative code in multi way decision
#ifdef MacroName Expression Abbreviation for #if defined macro
#error Reporting errors by the preprocessor
POINTERS
Example: int x;
Then compiler will allocate a memory cell for this data item. The data item can be
accessed, if we know the location (i.e., address) of the item. The address of a variable is
accessed with address operator &, which is a unary operator preceded by the variable.
Address of the variable is always unsigned integer.
Example: &x;
#include<stdio.h>
#include<conio.h>
main()
{ x
int x;
clrscr(); 10
printf("\nAddress of x:%u",&x);
x=10; 65524
Page 96
printf("\nValue of x:%d",x);
}
Note:
1. The address operator & can be used only with a simple variable (or) an array
element.
2. Address operator cannot act upon constants, and arithmetic expression.
***
POINTERS
Note: Any type of pointer occupies only 2 bytes of memory. Since, pointer holds address of
the variable which is always an unsigned integer.
Page 97
Initializing Pointers: Once a pointer variable has been declared, it can be initialized
using an assignment operator as:
65592 65594
10 65592
x ptr
A pointer variable can also be initialized at the time of its declaration itself.
Example: int x, *ptr = x;
Accessing variable value through pointer: The value of a variable can be accessed
through pointer variable using a unary operator ‘*’, usually known as indirection operator.
The operator refers to “value at the address in”.
main()
{
int x,*ptr;
clrscr();
printf("\nAddress of x is:%u",&x);
printf("\nAddress of ptr is:%u",&ptr);
x=10;
printf("\nx value using x:%d",x);
ptr=&x;
printf("\nValue in p:%u",ptr);
printf("\nx value using ptr:%d",*ptr);
}
***
/* Write a program to demonstrate every pointer variable same (2 bytes) amount of memory space */
Page 98
#include<stdio.h>
#include<conio.h>
main()
{
char *p; int *q; float *r; double *s;
clrscr();
printf(“\n Memory Size of Char Pointer Variable = %d Bytes”,sizeof(p));
printf(“\n Memory Size of Int Pointer Variable = %d Bytes”,sizeof(p));
printf(“\n Memory Size of Float Pointer Variable = %d Bytes”,sizeof(p));
printf(“\n Memory Size of Double Pointer Variable = %d Bytes”,sizeof(p));
}
***
PASSING PARAMETERS TO FUNCTIONS
1. Call by value: The process of passing actual value of the variable as an argument to a
function is known as call by value (or) pass by value.
In this mechanism, a copy of the value is passed from calling function to the called
function. Now, this value is stored temporarily in the formal argument of the called function.
At this stage, if we made any changes inside the function definition with the received
value, those changes are not effect on the original variable. Entire changes effected only on
the formal arguments of the called function.
#include<stdio.h>
#include<conio.h>
void change(int,int);
main()
{
int x,y;
clrscr();
printf(“\nEnter Two Values =”);
scanf(“%d%d’,&x,&y);
printf("\nBefore Passing to the Function");
printf("\nx value:%d\ny value:%d",x,y);
change(x,y);
printf("\nAfter Passing to the Function");
printf("\nx value:%d\ny value:%d",x,y);
}
void change(int p,int q)
{
p=p+5;
q=q+5;
}
Page 99
In this mechanism, when we pass address of the variable as an argument to a function,
the receiving argument at the called function must be a pointer variable. When the pointer
variable received the address, it points to the actual variable.
At this stage, if made any changes inside the function definition; those changes are
effected on the original variable. Since, pointer variable points the original argument.
#include<stdio.h>
#include<conio.h>
void change(int *,int *);
main()
{
int x,y;
clrscr();
printf(“\nEnter Two Values =”);
scanf(“%d%d’,&x,&y);
printf("\nBefore Passing to the Function");
printf("\nx value:%d\ny value:%d",x,y);
change(&x,&y);
printf("\nAfter Passing to the Function");
printf("\nx value:%d\ny value:%d",x,y);
}
void change(int *p,int *q)
{
*p=*p+5;
*q=*q+5;
}
***
Valid Operations:
Page 100
Example: int *p1,*p2, x, y, z;
p1 = &x;
p2 = &y;
z = p1 – p2;
main()
{
int *p1,*p2,x,y;
clrscr();
p1=&x;
p2=&y;
printf("\np1 Address:%u",&p1); /* 65518 */
printf("\np1 value:%u",p1); /* 65522 */
printf("\np2 Address:%u",&p2); /* 65520 */
printf("\np2 value:%u",p2); /* 65524 */
x=p2-p1;
printf("\nx value:%d",x); /* 1 */
p1=p1+2;
printf("\np1 value:%u",p1); /* 65526 */
p2=p2-1;
printf("\np2 value:%u",p2); /* 65522 */
}
Invalid Operations:
Page 101
3. Addition, Multiplication and division of two pointer variables is also invalid
operation.
***
VOID POINTER
A void pointer is a special type of pointer that can points to any data type variables.
The general format of a void pointer variable is:
For accessing value of the variable with the pointer variable, type casting must be
placed to refer the specific data item.
main()
{
int x=10;
double y=3.45678;
void *ptr;
clrscr();
ptr=&x;
printf("\nValue 1 =%d",*(int *)p);
ptr=&y;
printf("\nValue 2 =%lf",*(double *)p);
}
NULL POINTER
A pointer variable can also be initialized in such a way that it does not point to any
data type. Such a pointer is known as a NULL pointer.
A null pointer is a special type of pointer that cannot points to anywhere. Null pointer
is assigned by using the predefined constant NULL; which is defined by several header files
including stdio.h, stdlib.h and alloc.h.
Page 102
#include<stdio.h>
main()
{
int *p;
clrscr();
p=NULL;
printf("\nValue :%d",*p);
}
POINTERS AND ARRAYS
When an array is declared, the compiler allocates a base address and sufficient
amount of storage space for storing all the elements of the array in successive memory
locations. The name of the array is the beginning address (first element index 0) of the array,
called the base address. So, that the array name is referred to as an address constant.
0 1 2 3 4 Index Values
x 10 20 30 40 50 Element Values
Base Address
Here,
x = &x[0] = &x all are referred to the address location 1000.
With the relationship between the array and pointer, array subscripts can also be
defined in terms of pointer arithmetic operations which are known as indexing pointers.
Page 103
Similarly, for double dimensional arrays,
main()
{
int x[10],i,n;
clrscr();
printf("\nEnter how many numbers:");
scanf("%d",&n);
printf("\nEnter %d Numbers:",n);
for(i=0;i<n;i++)
scanf("%d",x+i);
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf("%5d",*(x+i));
}
(OR)
main()
{
int x[10],i,n,*p;
clrscr();
p=x;
printf("\nEnter how many numbers:");
scanf("%d",&n);
printf("\nEnter %d Numbers:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf("%5d",*(p+i));
}
/* WRITE A PROGRAM TO READ LIST OF FLOATING POINT NUMBERS AND PRINT SUM
OF THE ARRAY ELEMENTS USING POINTERS */
main()
{
float x[10],*p,sum;
int i,n;
clrscr();
p=x;
printf("\nEnter how many numbers:");
scanf("%d",&n);
printf("\nEnter %d Numbers:",n);
for(i=0;i<n;i++)
Page 104
scanf("%f",p+i);
sum=0;
for(i=0;i<n;i++)
sum=sum+*(p+i);
printf("\nTotal :%.2f",sum);
}
main()
{
int x[10][10],i,j,m,n;
clrscr();
printf("\nEnter how many Rows:");
scanf("%d",&m);
printf("\nEnter how many Columns:");
scanf("%d",&n);
printf("\nEnter Array Elements:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",*(x+i)+j);
}
printf("\nArray Elements Are:");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%5d",*(*(x+i)+j));
}
}
(OR)
main()
{
int x[10][10],i,j,m,n,(*p)[10];
clrscr();
printf("\nEnter how many Rows:");
scanf("%d",&m);
printf("\nEnter how many Columns:");
scanf("%d",&n);
p=x;
printf("\nEnter Array Elements:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",*(p+i)+j);
}
printf("\nArray Elements Are:");
for(i=0;i<m;i++)
Page 105
{
printf("\n");
for(j=0;j<n;j++)
printf("%5d",*(*(p+i)+j));
}
} ***
ARRAY OF POINTERS
Array of pointers are used to define more than one pointer variable of the same data
type. The general format of declaring array of pointers is:
main()
{
int i,*p[5],x,y,z;
clrscr();
x=10;
y=20;
z=30;
p[0]=&x;
p[1]=&y;
p[2]=&z;
printf("\nElements Are:");
for(i=0;i<3;i++)
printf("%5d",*p[i]);
}
main()
{
int i,j,*p[5];
int x[]={1,2,3},y[]={4,5,6},z[]={7,8,9};
clrscr();
p[0]=x;
p[1]=y;
p[2]=z;
printf("\nElements Are:");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
Page 106
printf("%5d",*(*(p+i)+j));
}
}
***
POINTERS AND STRINGS
A string is an array of characters that terminated with a null character ‘\0’. As similar
to arrays, string contents can also be accessed with the pointer variable.
main()
{
char s[50]="KAVALI",*p;
int i;
clrscr();
p=s;
printf("\nString Elements Are:");
for(i=0;*(p+i)!='\0';i++)
printf("%c",*(p+i)));
}
/* EXAMPLE PROGRAM */
main()
{
char s[50]="KAVALI",*p="NELLORE";
int i;
clrscr();
printf("\nResult 1:");
puts(s);
printf("\nResult 2:");
puts(p);
}
***
main()
{
int a=5,*p,**q;
clrscr();
p=&a;
q=&p;
printf("\nValue with p is:%d",*p);
printf("\nValue with q is:%d",**q);
}
/* PROGRAM THAT SHOWS FOR READING AND PRINTING A VARIABLE VALUE USING
POINTER-TO-POINTER */
main()
{
int x,*p,**q;
clrscr();
p=&x;
q=&p;
printf("\nEnter a value:");
scanf("%d",&x);
printf("\nValue with x is:%d",x);
printf("\nEnter another value with p:");
scanf("%d",p);
printf("\nValue with p is:%d",*p);
printf("\nEnter another value with q:");
scanf("%d",*q);
printf("\nValue with q is:%d",**q);
}
***
The memory allocation may be classified as static memory allocation and dynamic
memory allocation.
Static memory allocation: Memory for the variables is created at the time of compilation
is known as static memory.
Dynamic memory allocation: Memory for the variables is allocated at the time of
execution of the program is called dynamic memory. The following functions are used for
dynamic memory allocation which are defined in stdlib.h and alloc.h header files.
1. malloc() 2. calloc() 3. realloc() 4. free()
malloc(), calloc() and realloc() are memory allocation functions and free() is a memory
releasing function.
Page 108
Memory allocation process
LOCAL VARIABLES
STACK
GLOBAL VARIABLES
PERMANENT
STORAGE
PROGRAM INSTRUCTIONS AREA
The program instructions, global and static variables are stored in a region known as
permanent storage area. Local variables are stored in another region called stack. The
memory spaced located between stack and permanent storage area is available for dynamic
memory allocation during execution of the program. This free memory region is called as
heap.
1. malloc() function: malloc() function is used to allocate memory for the variables
at run time. The malloc() function reserves a single block of memory with the specified size
and returns a pointer of type void. With this, we can assign it to any type of pointer. The
general form of malloc() function is:
X Garbage Values
10 BYTES
main()
{
int *p,i,n;
clrscr();
printf("\nEnter how many numbers:");
Page 109
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));
printf("\nEnter %d Elements:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf(" %d",*(p+i));
}
Where,
ptrvariable is a pointer variable of type casttype.
n represents number of blocks.
elesize represents block size.
All blocks are initialized with ‘0’ and a pointer of the first block is returned. If there
is not enough space to allocate, then it returns a NULL pointer.
X = (int*)calloc(5,sizeof(int));
X 0 0 0 0 0
10 BYTES
main()
{
int *p,i,n;
clrscr();
printf("\nEnter how many numbers:");
scanf("%d",&n);
p=(int*)calloc(n,sizeof(int));
printf("\nEnter %d Elements:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
Page 110
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf(" %d",*(p+i));
}
main()
{
int *p,*q,i,m,n;
clrscr();
printf("\nEnter how many numbers:");
scanf("%d",&m);
p=(int*)malloc(m*sizeof(int));
printf("\nArray Elements Are:");
for(i=0;i<m;i++)
printf(" %d",*(p+i));
printf("\nEnter how many numbers:");
scanf("%d",&n);
q=(int*)calloc(n,sizeof(int));
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf(" %d",*(q+i));
}
3. realloc(): Suppose previously allocated dynamic memory is not sufficient (or) memory
is much larger than the requirement, in both cases some memory changes are required.
Memory changes can be done by using a library function called realloc() function.
realloc() function provides the altering the size of the memory allocation and the
process is called reallocation of memory. The general form of realloc() function is:
Where,
ptrvariable is a pointer variable of type casttype.
Here,
This function allocates a new memory space of the specified newsize and returns a
pointer variable that represent first byte of the new memory block. The newsize may be
larger or smaller than the previous size.
Note:
I. The new memory block may or may not be begin at the same place as the old one. In
case, it is not able to find additional space in the same region, it will create the same
in an entirely new region and moves the contents of the old block into the new block.
II. If the function is unsuccessful to allocate the memory space, it returns a NULL
pointer and the original block is lost.
Page 111
/* EXAMPLE PROGRAM FOR REALLOC() FUNCTION */
main()
{
int *p,i,n;
clrscr();
printf("\nEnter how many numbers:");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));
printf("\nEnter %d Elements:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
p=(int*)realloc(p,(n+2)*sizeof(int));
printf("\nEnter %d Elements:",n+2);
for(i=0;i<n+2;i++)
scanf("%d",p+i);
printf("\nArray Elements Are:");
for(i=0;i<n+2;i++)
printf(" %d",*(p+i));
}
4. free(): The memory allocation done by malloc(), calloc() and realloc() functions at
run time are released by invoking the function free() by the user explicitly. The releasing of
storage space becomes very important when the storage is space is limited. The general form
of free() function is:
Syntax: free(ptrvariable);
Example: free(ptr);
***
VARIABLE LENGTH ARRAYS
In C99 version, array dimensions can be specified by any valid expression, those
whose value is known only at run time. Such a representation is known as variable-length
array.
Like the simple variables, it is also possible to pass values of an array as an argument
to functions. Arrays can be passed as an argument in two ways. Those are:
Page 112
1. Passing individual elements as an argument
2. Passing entire array as an argument
/* Example program for passing individual element of the array as an argument to a function */
#include<stdio.h>
#include<conio.h>
void change(int);
main()
{
int x[10],i,n;
clrscr();
printf("\nEnter How Many Values=");
scanf("%d",&n);
printf("\nEnter %d Elements=",n);
for(i=0;i<n;i++)
scanf("%d",&x[i]);
printf("\nBefore Passing To Function Array Values Are=\n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
change(x[3]);
printf("\nAfter Passing To Function Array Values Are=\n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
}
void change(int p)
{
p=p+5;
}
For passing entire array as an argument to a function, list name of the array and size
of the array at the calling function. In such cases, an array or pointer is required to receive
the array at the called function. Then if we made changes inside the function with the
received argument, those changes are effected on the original array.
/* Example program for passing entire array as an argument to a function */
#include<stdio.h>
#include<conio.h>
void sort(int[],int);
Page 113
main()
{
int x[10],i,n;
clrscr();
printf("\nEnter How Many Values=");
scanf("%d",&n);
printf("\nEnter %d Elements=",n);
for(i=0;i<n;i++)
scanf("%d",&x[i]);
printf("\nBefore Passing To Function Array Values Are=\n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
sort(x,n);
printf("\nAfter Passing To Function Array Values Are=\n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
}
void sort(int p[10],int k)
{
int i,j,temp;
for(i=0;i<=k-2;i++)
{
for(j=i+1;j<=k-1;j++)
{
if(p[i]>p[j])
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
}
/* Example program for passing entire array as an argument to a function using pointers */
#include<stdio.h>
#include<conio.h>
void sort(int *,int);
main()
{
int x[10],i,n;
clrscr();
#include<stdio.h>
#include<conio.h>
void change(int[][],int,int);
main()
{
int x[10][10],i,r,c,j;
clrscr();
printf("\nEnter How Many Rows=");
scanf("%d",&r);
printf("\nEnter How Many Columns=");
scanf("%d",&c);
printf("\nEnter Matrix Elements=");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf("%d",&x[i][j]);
}
printf("\nBefore Passing To Function Matrix Values Are=\n");
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
printf(" %d",x[i][j]);
}
change(x,r,c);
printf("\nAfter Passing To Function Matrix Values Are=\n");
Page 115
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
printf(" %d",x[i][j]);
}
}
void change(int p[10][10],int m,int n)
{
p[0][0]=10;
p[1][1]=20;
p[2][2]=30;
}
***
Functions usually return only one value from called function to the calling function
after completion of the function implementation.
Pointers allow the user to return more than one value by allowing the arguments to be
passed by address, which allows the function to alter the values that pointed to and thus
return more than one value from the function.
#include<stdio.h>
#include<conio.h>
int* sort(int*,int);
main()
{
int x[5]={77,11,33,88,55},*k,i;
clrscr();
printf("\nBefore Sorting Elements Are:");
for(i=0;i<5;i++)
printf(" %d",x[i]);
k=sort(x,5);
printf("\nAfter Sorting Elements Are:");
for(i=0;i<5;i++)
printf(" %d",*(k+i));
}
int* sort(int *p,int n)
{
int i,j,temp;
for(i=0;i<=n-2;i++)
{
for(j=i+1;j<=n-1;j++)
Page 116
{
if(*(p+i)>*(p+j))
{
temp=*(p+i);
*(p+i)=*(p+j);
*(p+j)=temp;
}
}
}
return p;
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
char* rev(char*);
main()
{
char *s=”C LAB”,*p;
clrscr();
printf(“\nOriginal String:”);
puts(s);
p=rev(s);
printf(“\nReverse String:”);
puts(p);
}
char* rev(char *k)
{
strrev(k);
return k;
}
***
POINTER TO FUNCTION
Page 117
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("\nAddress of printf function is:%u",printf);
printf("\nAddress of scanf function is:%u",scanf);
printf("\nAddress of clrscr function is:%u",clrscr);
}
#include<stdio.h>
#include<conio.h>
void show();
main()
{
clrscr();
show();
printf("\nAddress of the Function:%u",show);
}
void show()
{
printf("\nFunction Called");
}
The address of the function can also be assigned to a pointer variable. For this, the
general form of declaring the pointer variable as pointer-to-function is:
#include<stdio.h>
#include<conio.h>
int show(int,int);
main()
{
int x,y,z,(*p)();
clrscr();
x=10;
y=20;
p=show;
z=(*p)(x,y);
Page 118
printf("\nResult=%d",z);
}
int show(int a,int b)
{
return a+b;
}
***
VARIABLE POINTER
For x compiler allocates 2 Bytes and For p compiler allocates 2 Bytes and
for y compiler allocates 1 Byte for q also compiler allocates 2 Bytes
memory. memory.
5. For ordinary variables only static 5. For pointer variables dynamic memory
memory allocation is possible. allocation is possible.
6. /* Example program for Variables */ 6. /* Example program for Pointer */
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
int x = 10; int x = 10, *p=&x;
clrscr(); clrscr();
printf(“\nResult = %d”,x); printf(“\nResult = %d”,*p);
} }
Page 119
ARRAY POINTER
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main()
main() {
{ int x = 10, *p=&x;
int x[5]={2,4,6,1,3},i; clrscr();
clrscr(); printf(“\nResult = %d”,*p);
printf(“\nArray Elements Are=”); }
for(i=0;i<5;i++)
printf(“ %d”,x[i]);
}
USES OF POINTERS
Page 120
Pointer enables us to access a variable that is defined outside the function.
Pointers support dynamic memory allocation for saving lot of memory space.
Pointers allow returning more than one value from a function.
Pointers reduce length and complexity of the program.
Pointers increase execution speed of the program.
COMMAND LINE ARGUMENTS
The arguments that pass to main() function at the command prompt of the operating system
are called command line arguments. The general format of the main() function with command line
arguments is:
Page 121
Syntax: struct Tag
{
Datatype Member1;
Datatype Member2;
---
---
Datatype Membern;
};
Declaration of the structure does not reserve any storage space. Memory is allocated
only at the time of defining a structure variable. The general format of defining a structure
variable is:
BName : BName :
B1 B2
Pages : Pages :
Price : Price :
i.e., Memory is allocated individually for each structure variable as well as individual
memory area for each member of the structure.
Page 122
‘.’ Dot operator is used to access members of the structure with its structure variable.
Here dot operator is also known as member operator (or) period operator. It forms link
between structure member and structure variable. The general format of accessing a structure
member with structure variable is:
Syntax: structurevariable.member;
Example: B1.Pages;
#include<stdio.h>
#include<conio.h>
struct Book
{
char BName[50];
int Pages;
float Price;
};
main()
{
struct Book B1;
clrscr();
printf("\nEnter Titile of the Book:");
gets(B1.BName);
printf("\nEnter Number of Pages:");
scanf("%d",&B1.Pages);
printf("\nEnter Cost of the Book:");
scanf("%f",&B1.Price);
printf("\nBOOK TITLE:%s",B1.BName);
printf("\nNUMBER OF PAGES:%d",B1.Pages);
printf("\nBOOK COST:%.2f RS",B1.Price);
}
Note:
Structure declaration and definition can also be combined into a single statement. For this,
use the syntax as:
struct Date
{
int Day,Month,Year;
}x;
main()
{
clrscr();
printf("\nEnter Current Day:");
scanf("%d",&x.Day);
printf("\nEnter Current Month:");
scanf("%d",&x.Month);
printf("\nEnter Current Year:");
scanf("%d",&x.Year);
printf("\nTODAY DATE:%d/%d/%d",x.Day,x.Month,x.Year);
}
INITIALIZING A STRUCTURE
A structure can be initialized with a list of values at the time of defining the structure
variable. But, individual member initialization inside the structure declaration is not possible.
The general format of initializing a structure is:
#include<stdio.h>
#include<conio.h>
struct product
{
Page 124
int pid;
char pname[10];
float price;
};
main()
{
struct product s1={111,"soap",25.00};
clrscr();
printf("\nProduct Code=%d\n”,s1.pid);
printf(“\nProduct Name=%s\n”,s1.pname);
printf(“\nProduct Cost=%.2f Rs",s1.price);
}
Copy:
Two variables of the same structure type can be copied in the same way as ordinary
variables. In this case, use assignment operator for copying.
Example: Let B1 and B2 are two structure variables of the same structure type,
and then the details of B1 are copied into B2 as:
B2 = B1;
Here,
Each individual member of the B1 is copied into individual member of B2.
#include<stdio.h>
#include<conio.h>
struct product
{
int pid;
char pname[10];
float price;
};
main()
{
struct product s1={111,"soap",25.00},s2;
clrscr();
printf("\nOriginal structure is:");
printf("\n%d\t%s\t%.2f",s1.pid,s1.pname,s1.price);
s2=s1;
printf("\nCopied structure is:");
printf("\n%d\t%s\t%.2f",s2.pid,s2.pname,s2.price);
}
Comparison:
Page 125
Direct comparison of one structure variable with another structure variable using relational
operators is not possible.
i.e., Let B1 and B2 are two structure variables of the same structure type, and then the
comparisons like
B1>B2, B1<B2, B1<=B2, B1>=B2, B1==B2 and B1!=B2 are invalid operations.
#include<stdio.h>
#include<string.h>
struct product
{
int pid;
char pname[10];
float price;
};
main()
{
struct product s1,s2;
clrscr();
printf("\nEnter Product 1 id:");
scanf("%d",&s1.pid);
fflush(stdin);
printf("\nEnter Prouduct 1 Name:");
gets(s1.pname);
printf("\nEnter Product 1 Cost:");
scanf("%f",&s1.price);
printf("\nEnter Product 2 id:");
scanf("%d",&s2.pid);
fflush(stdin);
printf("\nEnter Prouduct 2 Name:");
gets(s2.pname);
printf("\nEnter Product 2 Cost:");
scanf("%f",&s2.price);
if((s1.pid==s2.pid)&&((strcmp(s1.pname,s2.pname))==0)&&(s1.price==s2.price))
printf("\nBOTH ARE EQUAL");
else
printf("\nBOTH ARE DIFFERENT");
}
C permits the use of array as structure members. i.e., an array can also be placed as a
member of a structure.
Page 126
#include<stdio.h>
#include<conio.h>
struct student
{
char name[50];
int sub[3],total;
}s;
main()
{
int i,j,n;
clrscr();
printf(“\nEnter student Name =”);
gets(s.name);
printf(“\nEnter 3 subject Marks:”);
for(i=0;i<3;i++)
scanf(“%d”,&s.sub[i]);
s.total=0;
for(i=0;i<3;i++)
s.total=s.total + s.sub[i];
printf(“\nStudent Name = %s”,s.name);
printf(“\nTotal Marks = %d”,s.total);
}
ARRAY OF STRUCTURES
A similar type of structure variables placed with a common variable name is called an
array of structures. Array of structure concept is used to define more than one structure
variable of the same type.
Where,
struct is a keyword used to define the structure.
Tage specifies name of the structure that follows same rules as a valid identifier.
Member1, Member2, - - - - , Membern are the elements of the structure.
Variable species name of the structure variable that follows same rules as a valid
identifier.
Size represents maximum number of structure variables.
Page 127
/* EXAMPLE PROGRAM TO READ A LIST OF STUDENTS INFORMATION AND PRINT THEM IN
ASCENDING ORDER OF THEIR AVERAGE MARKS USING ARRAY OF STRUCTURES */
#include<stdio.h>
#include<conio.h>
struct student
{
char name[50],branch[5];
int sub1,sub2,sub3;
float avg;
}s[10];
main()
{
int i,j,n;
struct student temp;
clrscr();
printf("\nEnter how many students:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fflush(stdin);
printf("\nEnter student %d Name:",i);
gets(s[i].name);
fflush(stdin);
printf("\nEnter student %d Branch:",i);
gets(s[i].branch);
printf("\nEnter 3 subject Marks:");
scanf("%d%d%d",&s[i].sub1,&s[i].sub2,&s[i].sub3);
}
for(i=1;i<=n;i++)
s[i].avg=(s[i].sub1+s[i].sub2+s[i].sub3)/3.0;
for(i=1;i<=n-1;i++)
{
for(j=i+1;j<=n;j++)
{
if(s[i].avg>s[j].avg)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
Page 128
Array of structures can be initialized at the time of its declaration by a list of values
placed within pair of braces.
#include<stdio.h>
#include<conio.h>
struct student
{
char name[50],branch[5];
int sub1,sub2,sub3;
}
s[10] = { { “satish kumar”,”cse”,67,89,90} , { “praveen”, “it”,45,78,89}};
main()
{
int i;
clrscr();
printf(“\nStudents Details Are=\n”);
for(i=0;i<2;i++)
printf(“%s\t%s\t%d\t%d\t%d”,s[i].name,s[i].branch,s[i].sub1,s[i].sub2,s[i].sub3);
}
Page 129
Example: struct Employee
{
char name[25];
struct Date
{
int d,m,y;
}Join;
float salary;
}st;
Dot operator is used to access the members of the innermost as well as the outermost
structures. The general format of accessing inner structure members is:
Syntax: OuterStructureVariable.InnerStructureVariable.InnerMember;
Example: st.Join.d;
#include<stdio.h>
#include<conio.h>
struct Employee
{
char name[25];
struct Date
{
int d,m,y;
}Join;
float salary;
}st;
main()
{
clrscr();
printf("\nEnter Name of the Employee:");
gets(st.name);
printf("\nEnter Date of Joining:");
scanf("%d%d%d",&st.Join.d,&st.Join.m,&st.Join.y);
printf("\nEnter Salary of the Employee:");
scanf(“%f”,&st.salary);
printf("\nEMPLOYEE NAME:%s",st.name);
printf("\nSALARY :%.2f RS",st.salary);
printf("\nJOIN DATE :%d / %d / %d",st.Join.d,st.Join.m,st.Join.y);
}
#include<stdio.h>
#include<conio.h>
struct Employee
Page 130
{
char name[25];
struct Date
{
int d,m,y;
}Join;
float salary;
}st = {“Ravi Kumar”,10,6,2014,23456.25};
main()
{
clrscr();
printf("\nEMPLOYEE NAME:%s",st.name);
printf("\nSALARY :%.2f RS",st.salary);
printf("\nJOIN DATE :%d / %d / %d",st.Join.d,st.Join.m,st.Join.y);
}
Here, PtrVariable can be assigned to any other structure of the same type, and can be used to
access the members of its structure.
‘→’ Arrow operator is used to access members of the structure with its pointer variable. ‘→’
operator is formed with the combination of a minus (-) sign and a greater than(>) symbol.
The general format of accessing structure member with the structure pointer variable is:
Example : P → Acno;
The same representation can also be placed with dot operator is as:
Example : (*P).Acno;
Page 131
#include<stdio.h>
#include<conio.h>
struct Account
{
int Acno;
float AcBalance;
}S={111,35000.75}, *P;
main()
{
clrscr();
P=&S;
printf("\nACCOUNT INFORMATION IS:");
printf("\n%d\t%.2f",P→Acno,P→AcBalance);
}
#include<stdio.h>
#include<conio.h>
struct demo
{
int x;
float y;
char z;
};
main()
{
struct demo s={10,345.72,'K'},*p;
clrscr();
printf("\nWith Variable and Dot Operator:");
printf("\n%d\t%.2f\t%c",s.x,s.y,s.z);
p=&s;
printf("\nWith Pointer Variable and Arrow Opeator:");
printf("\n%d\t%.2f\t%c",p→x,p→y,p→z);
printf("\nWith Pointer Variable and Dot Opeator:");
printf("\n%d\t%.2f\t%c",(*p).x,(*p).y,(*p).z);
}
A structure can also be passed as an argument to a function in three ways. Those are:
Page 132
Then if we made any changes inside the function with the received value, those
changes are not recognized by the outside function. Since, entire changes are effects only on
the formal arguments.
#include<stdio.h>
#include<conio.h>
struct cricket
{
char name[15];
int matches;
float avg;
}s={"sachin",400,56.78};
void change(int);
main()
{
clrscr();
printf("\nBefore Passing:");
printf("\n%s\t%d\t%.2f",s.name,s.matches,s.avg);
change(s.matches);
printf("\nAfter Passing:");
printf("\n%s\t%d\t%.2f",s.name,s.matches,s.avg);
}
void change(int x)
{
x=410;
}
Then if we made any changes inside the function with the received argument, those
changes are not recognized by the outside function. Since, entire changes effects only on the
formal structure.
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct cricket
{
char name[15];
Page 133
int matches;
float avg;
}s={"sachin",400,56.78};
main()
{
clrscr();
printf("\nBefore Passing:");
printf("\n%s\t%d\t%.2f",s.name,s.matches,s.avg);
change(s);
printf("\nAfter Passing:");
printf("\n%s\t%d\t%.2f",s.name,s.matches,s.avg);
}
void change(struct cricket x)
{
strcpy(x.name,"sehwag");
x.matches=250;
x.avg=50.23;
}
Then if made any changes inside the function on structure, those changes are
recognized by outside function. So, that all changes are effects on the original structure.
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct cricket
{
char name[15];
int matches;
float avg;
}s={"sachin",400,56.78};
main()
{
clrscr();
printf("\nBefore Passing:");
printf("\n%s\t%d\t%.2f",s.name,s.matches,s.avg);
change(&s);
printf("\nAfter Passing:");
Page 134
printf("\n%s\t%d\t%.2f",s.name,s.matches,s.avg);
}
void change(struct cricket *k)
{
strcpy(k→name,"sehwag");
k→matches=250;
k→avg=50.23;
}
TYPEDEF (TYPE DEFINITION)
The typedef keyword allows the user to specify a new name for the existing data
types. The general format of the declaration statement using the typedef keyword is:
Where,
ExistingDataType may be either a primitive data type of user-defined data type.
Note: typedef declaration does not create any new data types. It just adds a new name for
the existing data type.
typedef keyword is very useful in the case of user-defined data types like structure.
While using typedef keyword with the structure creation, structure tag is optional.
Complex k;
#include<stdio.h>
#include<conio.h>
typedef struct
{
float real,imag;
}Complex;
main()
{
Complex k;
Page 135
clrscr();
printf("\nEnter Real Part:");
scanf("%f",&k.real);
printf("\nImaginary Part:");
scanf("%f",&k.imag);
printf("\nComplex Number is =%.2f + i %.2f",k.real,k.imag);
}
***
BIT FIELDS
OPERATOR MEANING
Bit fields utilization with the structure allows using the bit fields to hold data items
and hereby pack several data items in a single word of memory.
The name and size of bit fields are defined using structure. For bit fields memory is
allocated in adjacent bits. The general format of bit field definition is:
Here,
The main advantage of bit fields is to save some memory as against storing variables.
By this technique, the exact number of bits required by the bit field is specified. This way a
whole word is not required to hold the field. This helps in packing a number of bit fields into
single word of memory.
Note: scanf() function is not possible for reading values in bit field members. Since,
we can’t access address of a bit field member.
#include<stdio.h>
#include<conio.h>
#include<stdio.h>
#include<conio.h>
struct day
{
unsigned int d:5;
unsigned int m:4;
unsigned int y:4;
}val;
main()
{
val.d=16;
val.m=10;
val.y=15;
clrscr();
printf("\nCurrent Date =%u / %u / %u",val.d,val.m,val.y);
}
It is also possible to force a gap in between the data member fields. Consider the
following example program that forces bit gaps in between the data member fields.
#include<stdio.h>
#include<conio.h>
Page 137
struct day
{
unsigned int d:5;
:2;
unsigned int m:4;
:1;
unsigned int y:4;
}val;
main()
{
val.d=16;
val.m=10;
val.y=15;
clrscr();
printf("\nCurrent Date =%u / %u / %u",val.d,val.m,val.y);
}
ENUMERATION TYPES
An enumeration is a user defined data type. Enumeration data types are data items
whose values may be any member of a symbolically declared set of values. The symbolically
declared members are known as “enumeration constants”.
Where,
enum keyword is used to define enumeration data types.
Tag specifies name of the data type that follows same rules as a valid identifier.
enum Tag forms as the user defined data type.
Member1, Member2, - - -, Membern are called enumerators (or) enumeration
constants (or) enumeration list.
Once the enumeration list has been defined, corresponding enumeration variables can
be created as:
Page 138
Example : enum Days start,end;
#include<stdio.h>
#include<conio.h>
enum Days
{
Mon, Tue, Wed, Thu, Fri, Sat, Sun
};
main()
{
enum Days start,end;
clrscr();
start=Mon;
end=Sun;
printf(“\nStarting Value = %d”,start);
printf(“\nEnding Value = %d”,end);
printf(“\nMemory Size of start = %d Bytes”,sizeof(start));
printf(“\nMemory Size of end = %d Bytes”,sizeof(end));
}
Note:
It is also to associate numbers other than the sequence starting at zero with the names
in the enum data type by including a specific initialization in the variable name list.
#include<stdio.h>
#include<conio.h>
enum coins
{
p1,p2=45,p3,p4=80
};
Page 139
main()
{
clrscr();
printf("\nValue of p1:%d",p1);
printf("\nValue of p2:%d",p2);
printf("\nValue of p3:%d",p3);
printf("\nValue of p4:%d",p4);
}
ANONYMOUS ENUMERATION
Syntax : enum
{
Member1, Member2, - - - - - - , Membern
};
/* EXAMPLE PROGRAM FOR ANONYMOUS ENUMERATION */
#include<stdio.h>
#include<conio.h>
enum
{
a,b,c
};
main()
{
clrscr();
printf("\nMember 1 Value=%d",a);
printf("\nMember 2 Value=%d",b);
printf("\nMember 3 Value=%d",c);
} ***
UNION
Union is also a user-defined data type which is similar to structure. i.e., Union is a
collection of non-homogeneous / heterogeneous / different data type elements that can be
grouped together under a common name.
Page 140
union is a keyword used to declare the union data type.
Tag is name the union that follows same rules as a valid identifier.
Members declared inside the union are known as union members (or) union elements.
Union declaration must be ended with a semicolon.
Memory is allocated for the union only at the time of creating union variable. The
general form of creating union variables is:
In union, compiler selects the member which occupies highest memory, and that
memory is reserved only. So, that all the members of the union are shared that
common memory. It implies that, although a union may contain many members of
different types, it can handle only one member at a time.
Dot operator is used to access member of the union with the union variable. The
general format of accessing union members with union variable is:
Example : X . balance;
#include<stdio.h>
#include<conio.h>
union Account
{
Page 141
int acno;
char actype[10];
float acbalance;
};
main()
{
union Account x;
clrscr();
printf("\nEnter Account Number:");
scanf("%d",&x.acno);
printf("\nAccount Number:%d",x.acno);
fflush(stdin);
printf("\n\n\nEnter Account Type:");
gets(x.actype);
printf("\nAccount Type:%s",x.actype);
printf("\n\n\nEnter Balance Amount:");
scanf("%f",&x.acbalance);
printf("\nBalance Amount:%.2f RS",x.acbalance);
}
Program
1. Write a program to print memory size of union members and union variable.
Note:
1. The main difference between a structure and union is in terms of their storage space.
In structure, each member has its own storage location. Whereas. In union all
members shared a common memory.
2. The main advantage of union is to save memory compared to the structure with same
members.
#include<stdio.h>
#include<conio.h>
struct demo1
{
char a;
int b;
float c;
double d;
};
union demo2
{
char a;
int b;
float c;
double d;
};
Page 142
main()
{
struct demo1 sd;
union demo2 ut;
clrscr();
printf("\nMemory Size of Structure = %d Bytes",sizeof(sd));
printf("\nMemory Size of Union = %d Bytes",sizeof(ut));
}
#include<stdio.h>
#include<conio.h>
struct demo
{
int x;
float y;
};
union hello
{
float z;
struct demo p;
int k;
};
main()
{
union hello ut;
clrscr();
printf("\n Memory Size = %d Bytes”, sizeof(ut));
}
#include<stdio.h>
#include<conio.h>
union demo
{
int x;
float y;
};
struct hello
{
float z;
union demo p;
int k;
};
main()
{
struct hello ut;
clrscr();
printf("\n Memory Size = %d Bytes”, sizeof(ut));
Page 143
}
UNIT - V
INPUT OUTPUT STATEMENTS
C language supports various library functions that are used to perform input and
output operations.
In C language, input and output statements are classified into two types as:
i) Non-formatted Input Output Statements
ii) Formatted Input Output Statements
Input-Output Statements
getchar(), getch() and getche() functions are known as non-formatted character input
statements. All these functions are used for reading a single character from the console input device –
Keyboard.
Page 144
a) getchar() Function:
getchar() library function is used for reading a single character from the keyboard.
The general format of getchar() function is:
When the statement is encountered, control waits for input character and key pressing. When
the enter key is pressed after typing the character, function accepts the character value with echoing
on the screen and then assigns to left hand side variable.
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
clrscr();
printf("\nEnter A Character=");
ch=getchar();
printf("\nResult Character=%c",ch);
}
b) getch() Function:
getch() library function is used for reading a single character from the keyboard. The
general format of getch() function is:
When the statement is encountered, control waits for input character. When the character is
typed, function accepts the character without echoing on the screen and immediately assigns to left
hand side variable without pressing any key.
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
clrscr();
printf("\nEnter A Character=");
Page 145
ch=getch();
printf("\nResult Character=%c",ch);
}
b) getche() Function:
getche() library function is used for reading a single character from the keyboard.
The general format of getche() function is:
When the statement is encountered, control waits for input character. When the character is
typed, function accepts the character with echoing on the screen and immediately assigns to left hand
side variable without pressing any key.
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
clrscr();
printf("\nEnter A Character=");
ch=getche();
printf("\nResult Character=%c",ch);
}
Non-formatted Output Statements
putchar() and putch() functions are known as non-formatted character output statements. All
these functions are used for printing a single character on the console output device – Monitor.
a) putchar() Function:
putchar() library function is used for printing a single character on the monitor. The
general format of putchar() function is:
Syntax : putchar(VariableName);
Where,
VariableName is a valid identifier of char data type.
When the statement is encountered, function displays the character value on the monitor.
#include<stdio.h>
#include<conio.h>
Page 146
main()
{
char ch;
clrscr();
printf("\nEnter A Character=");
ch=getchar();
printf("\nResult Character=”);
putchar(ch);
}
a) putch() Function:
putch() library function is used for printing a single character on the monitor. The
general format of putch() function is:
Syntax : putch(VariableName);
Where,
VariableName is a valid identifier of char data type.
When the statement is encountered, function displays the character value on the monitor.
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
clrscr();
printf("\nEnter A Character=");
ch=getchar();
printf("\nResult Character=”);
putch(ch);
}
scanf() Function:
scanf() library function is used for reading data from the console input device – Keyboard.
The general format of a scanf() function is:
Page 147
Format Specifications:
1) To read a character, provide at least one white space character in the conversion specification.
2) Conversion character should preceded with * symbol. It tells the compiler that the next input
field is to be read but not stored.
Example : int x;
float y;
scanf(“%d %*c%f”,&x,&y);
The above statement accepts one integer value, one character value and one real value. But it
stores only integer and real values.
Formatted Output Statements
printf() Function:
printf() library function is used for displaying information on console output device –
Monitor. The general format of printf() function is:
Where,
Control String specifies type of the data to be displayed. It forms with the combination of %
symbol followed by the conversion character of different data types. In addition to this,
control string allows three types of formats as:
2) Escape sequence characters are valid to print the output information in different ways.
Output : New
Programs
3) Format Specifications:
Page 148
Syntax : %Wd
Example : printf(“%d”,7492); 77 4 9 2
ii. If the number size is greater than the specified field width size, then the compiler
automatically extends the field width to fit the output value.
Example : printf(“%2d”,7492);
7 4 9 2
iii. If the number size is less than the specified field width size, then the value is right
justified with leading blank spaces.
Example : printf(“%6d”,7492); 7 4 9 2
iv. It is possible to add zero’s at blank spaces by placing a ‘0’ before the field width
specifier.
Example : printf(“%06d”,7492); 0 0 7 4 9 2
v. “%#o” format specifier is used to add a leading ‘0’ for printing octal numbers.
vi. “%#x” format specifier is used to add a leading ‘0x’ for printing hexa decimal
numbers.
vii. “%X” format specifier is used for printing hexa decimal numbers in capital letters.
i. The format specification to print the decimal notation of a floating point number is:
Syntax : %W.Pf
Where,
W specifies the minimum number of positions that are used for displaying the value.
P indicates the number of digits to be displayed after the decimal point.
While printing the value is rounded to P decimal places, and printed as right-justified.
Page 149
printf("%6.2f",7491.2579); 7491.26
printf("\n%6.2f",5678.3); 5678.30
ii. The format specification to print an exponential form of a floating point number is:
Syntax : %W.Pe
Syntax : %Wc
Where,
The character will be displayed as right-justified in the field width of W columns.
Example : printf(“%3c”,’K’); K
Syntax : %Ws
Where,
The string will be displayed as right-justified in the field width of W columns.
Example : printf(“%5s”,”LAB”); L A B
Different values can also be printed with in a single statement of prinf() statement.
Example : printf(“\n%s%4c%6d”,”LAB”,’@’,2015);
*****
Page 150
STRINGS
STRING
gets() and puts() library functions are known as string input/output functions. These
functions are used for reading and print an entire line as a string including blank spaces.
These library functions information is available in stdio.h header file.
gets() function: gets() is a library function used for reading an entire line as a
string including blank spaces. The general format of a gets() function is:
Syntax : gets(string);
Example : gets(str);
puts() function: puts() is a library function used for printing an entire line as a
string including blank spaces. The general format of a puts() function is:
Syntax : puts(string);
Example : puts(str);
#include<stdio.h>
#include<conio.h>
Page 151
main()
{
char str[50];
clrscr();
printf("\nEnter a line of text:");
gets(str);
printf("\nRESULT:");
puts(str);
}
string.h header file provides various library function that are used for manipulating
the given strings in different ways. Some of the important library functions are:
Function accepts a single argument as string and return length of the passed
string. Here, function counts number of characters as length includes blank spaces and
excluding the NULL character (‘\0’).
#include<string.h>
main()
{
char str[50];
int n;
clrscr();
printf("\nEnter a string:");
gets(str);
n=strlen(str);
printf("\nSTRING LENGTH IS:%d",n);
}
Function is used to add the given two strings. Here, the contents of the source string
are added at the end of the target stirng.
Function is used to copy the contents of one string into another string. Here, the
contents of source string are copied into the target string.
Note: While declaring target string, its size should be equal or greater than the size of the
source string.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\nEnter string 1:");
gets(str1);
printf("\nEnter string 2:");
gets(str2);
strcpy(str1,str2);
printf("\nSTRING 1:");
puts(str1);
printf("\nSTRING 2:");
puts(str2);
}
Page 153
Syntax: int strcmp(string1 , string2);
Function performs comparison between two strings character by character until there
is a mismatch or end of the strings is reached, whichever occurs first. If the two strings are
identical, function returns 0 value. If they are not identical, function returns numerical
difference between the ASCII values of the first non-matching characters.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
int k;
clrscr();
printf("\nEnter string 1:");
gets(str1);
printf("\nEnter string 2:");
gets(str2);
k=strcmp(str1,str2);
if(k>0)
printf("\nSTRING 1 IS GREATER THAN STRING 2");
else if(k<0)
printf("\nSTRING 2 IS GREATER THAN STRING 1");
else
printf("\nBOTH STRIGNS ARE IDENTICAL");
}
Function is used to compare the given two strings without case consideration.
/* PROGRAM TO COMPARE THE GIVEN TWO STRINGS WITHOUT CASE */
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\nEnter string 1:");
gets(str1);
printf("\nEnter string 2:");
Page 154
gets(str2);
if((strcmpi(str1,str2))==0)
printf("\nBOTH STRIGNS ARE SAME");
else
printf("\nBOTH STRINGS ARE DIFFERENT");
}
6. strrev() function: It refers to string reverse function.
Syntax: strrev(string);
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[10];
clrscr();
printf("\nEnter a String:");
gets(str);
strrev(str);
printf("\n Reverse String =");
puts(str);
}
Syntax: strlwr(string);
Function is used to convert all characters in the given string from upper case to lower
case characters.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[10];
clrscr();
printf("\nEnter a String in Upper Case:");
gets(str);
strlwr(str);
printf("\nResult String in Lower Case =");
Page 155
puts(str);
}
Syntax: strupr(string);
Function is used to convert all characters in the given string from lower case to upper
case characters.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[10];
clrscr();
printf("\nEnter a String in Lower Case:");
gets(str);
strupr(str);
printf("\nResult String in Upper Case =");
puts(str);
}
/* EXAMPLE PROGRAM */
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\nEnter string 1:");
gets(str1);
printf("\nEnter string 2:");
gets(str2);
strncat(str1,str2,3);
printf("\nSTRING 1:");
puts(str1);
printf("\nSTRING 2:");
puts(str2);
}
Page 156
10. strncpy(): The general format of strncpy() function is:
/* EXAMPLE PROGRAM */
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\nEnter string 1:");
gets(str1);
strncpy(str2,str1,3);
str2[3]='\0';
printf("\nRESULT 1:");
puts(str1);
printf("\nRESULT 2:");
puts(str2);
}
/* EXAMPLE PROGRAM */
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\nEnter string 1:");
gets(str1);
printf("\nEnter string 2:");
gets(str2);
if((strncmp(str1,str2,3))==0)
printf(“\n Both Are Same”);
else
printf(“\n Both Are Different”);
printf("\nRESULT:%d",strncmp(str1,str2,3));
}
Page 157
Syntax: strncmpi(string1 , string2 , n);
/* EXAMPLE PROGRAM */
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\nEnter string 1:");
gets(str1);
printf("\nEnter string 2:");
gets(str2);
if((strncmpi(str1,str2,3))==0)
printf(“\n Both Are Same”);
else
printf(“\n Both Are Different”);
}
#include<string.h>
main()
{
char str1[50],str2[50];
int i,k;
clrscr();
printf("\nEnter a String :");
gets(str1);
strcpy(str2,str1);
strrev(str1);
if((strcmp(str1,str2))==0)
printf("\nPALINDROME");
else
printf("\nNOT PALINDROME");
}
PROGRAMS
1. Write a program to print length of the given string without using library functions.
main()
{
char str[50];
int i;
clrscr();
printf("\nEnter a String:");
Page 158
gets(str);
for(i=0;str[i]!='\0';i++);
printf("\nLength is:%d",i);
}
2. Write a program to copy contents of one string to another without using library functions.
main()
{
char str1[50],str2[50];
int i;
clrscr();
printf("\nEnter a String:");
gets(str1);
printf("\nOriginal String is:");
puts(str1);
for(i=0;str1[i]!='\0';i++)
str2[i]=str1[i];
str2[i]='\0';
printf("\nCopied String is:");
puts(str2);
}
3. Write a program to add the given two strings without using library functions.
main()
{
char str1[50],str2[50];
int i,j;
clrscr();
printf("\nEnter String 1:");
gets(str1);
printf("\nEnter String 2:");
gets(str2);
for(i=0;str1[i]!='\0';i++);
for(j=0;str2[j]!='\0';j++)
str1[i+j]=str2[j];
str1[i+j]='\0';
printf("\nResult String is:");
puts(str1);
}
4. Write a program to perform string comparison without using library functions.
main()
{
char str1[50],str2[50];
int i,k;
clrscr();
printf("\nEnter String 1:");
gets(str1);
printf("\nEnter String 2:");
gets(str2);
k=0;
Page 159
for(i=0;str1[i]!='\0'||str2[i]!='\0';i++)
{
if(str1[i]!=str2[i])
{
k=str1[i]-str2[i];
goto temp;
}
}
temp:
if(k>0)
printf("\nSTRING 1 IS GREATER THAN STRING 2");
else if(k<0)
printf("\nSTRING 1 IS LESS THAN STRING 2");
else
printf("\n BOTH ARE SAME");
}
5. Write a program to reverse the given string without using library functions.
#include<stdio.h>
#include<conio.h>
main()
{
char str[50],temp;
int i,j,k;
clrscr();
printf("\nEnter A String =");
gets(str);
printf("\nOriginal String =%s",str);
for(k=0;str[k]!='\0';k++);
for(i=0,j=k-1;i<j;i++,j--)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
printf("\nReverse String =%s",str);
}
6. Write a program to check whether the given string is palindrome or not without using library
functions.
main()
{
char str1[50];
int i,n,j,k=0;
clrscr();
printf("\nEnter a String :");
gets(str1);
for(n=0;str1[n]!='\0';n++);
for(i=0,j=n-1;i<j;i++,j--)
{
Page 160
if(str1[i]!=str1[j])
{
printf(“\n NOT PALINDROME”);
exit();
}
}
printf("\nPLAINDROME");
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[100],sub[50];
int len1,len2,pos,i,j;
clrscr();
printf("\nEnter Main String =");
gets(str);
printf("\nEnter Sub String To Insert =");
gets(sub);
printf("\nEnter Position To Insert =");
scanf("%d",&pos);
len1=strlen(str);
len2=strlen(sub);
if(pos>len1)
printf("\nINSERTION NOT POSSIBLE");
else
{
for(i=len1;i>=pos-1;i--)
str[i+len2]=str[i];
for(i=pos-1,j=0;j<len2;i++,j++)
str[i]=sub[j];
}
printf("\nResultant String is = %s",str);
}
8. Write a program to delete specified number of characters from the main string.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[50];
int i,len,pos,nc;
clrscr();
printf("\nEnter Main String:");
gets(str);
printf("\nEnter Position to Delete:");
scanf("%d",&pos);
Page 161
printf("\nEnter Number of Characters to Delete:");
scanf("%d",&nc);
len=strlen(str);
for(i=pos-1;i<len;i++)
str[i]=str[i+nc];
printf("\nResultant String is =%s",str);
}
INITIALIZATION OF STRINGS
Here, collection of characters is placed within double quotation marks and termed as
string constant.
#include<stdio.h>
#include<conio.h>
main()
{
char str[50]="Language in 1972";
clrscr();
printf("\nResult String = %s",str);
}
Strings can also be initialized in the form of character array. In such cases, explicitly it is
necessary to add the NULL character (‘\0’) at the end of the string value.
A string can also be initialized by omitting the string size. In such cases, compiler
automatically allocates sufficient memory for the string by counting number of
initialized characters.
Page 162
Size1 represents maximum number of strings and size2 represents maximum number
of characters in each string.
Example: char str[10][15];
#include<stdio.h>
#include<string.h>
main()
{
char x[15][15],temp[15];
int i,j,n;
clrscr();
printf("\nEnter how many names:");
scanf("%d",&n);
printf("\nEnter %d Names:",n);
for(i=0;i<n;i++)
{
fflush(stdin);
gets(x[i]);
}
for(i=0;i<=n-2;i++)
{
for(j=i+1;j<=n-1;j++)
{
if((strcmp(x[i],x[j]))>0)
{
strcpy(temp,x[i]);
strcpy(x[i],x[j]);
strcpy(x[j],temp);
}
}
}
printf("\nLIST OF NAMES IN ALPHABETICAL ORDER ARE:\n");
for(i=0;i<=n-1;i++)
puts(x[i]);
}
INITIALIZATION OF TWO DIMENSIONAL CHARACTER ARRAYS
#include<stdio.h>
#include<conio.h>
main( )
Page 163
{
char x[3][10]={ “India” , “Pakistan” , “Srilanka”};
clrscr();
printf(“\n List of Strings Are =\n”);
for(i=0;i<3;i++)
puts(x[i]);
}
While initializing array of strings, size1 can be omitted. In such cases, compiler
allocates sufficient memory by counting number of initialized strings.
stdlib.h (standard library header file) header file supports various library functions
that are used to convert the given strings into other forms and vice-versa. Some of the
important library functions are:
1. atoi() function: atoi() function converts a string of digits into an integer value.
The general format of the atoi() function is:
Function accepts a string as an argument and returns the result value as an integer.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
Page 164
char x[10]="2009";
int k;
clrscr();
k=atoi(x)+6;
printf("\nRESULT VALUE:%d",k);
}
2. itoa() function: atoi() function converts an integer value into a string. The
general format of the itoa() function is:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>>
main()
{
char x[10];
int k=49;
clrscr();
itoa(k,x,10);
printf("\nDecimal Format:");
puts(x);
printf("\nOctal Format:");
itoa(k,x,8);
puts(x);
printf("\nHexadecimal Format:");
itoa(k,x,16);
puts(x);
}
3. atol() function: atol() function converts a string of digits into a long integer
value. The general format of the atol() function is:
Function accepts a string as an argument and returns the result value as a long integer.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
char x[10]="2009";
Page 165
long int k;
clrscr();
k=atol(x)+6;
printf("\nRESULT VALUE:%ld",k);
}
4. ltoa() function: ltoa() function converts a long integer value into a string. The
general format of the ltoa() function is:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>>
main()
{
char x[10];
long int k=49;
clrscr();
ltoa(k,x,10);
printf("\nDecimal Format:");
puts(x);
printf("\nOctal Format:");
ltoa(k,x,8);
puts(x);
printf("\nHexadecimal Format:");
ltoa(k,x,16);
puts(x);
}
5. atof() function: atof() function converts a string of digits into a real value. The
general format of the atof() function is:
Function accepts a string as an argument and returns the result value as a real value.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
char x[10]="2009";
Page 166
float k;
clrscr();
k=atof(x)+6;
printf("\nRESULT VALUE:%f",k);
}
RANDOM NUMBERS
A random number is a number selected from a set in which all members have the
same probability being selected.
C language supports rand() library function to generate pseudorandom numbers.
rand() library function information is available in stdlib.h header file. The general format of
rand() function is:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
int k,n,i;
clrscr();
printf("\nEnter How Many Numbers =");
scanf("%d",&n);
printf("\nPseudo Random Numbers Are=\n");
for(i=1;i<=n;i++)
{
k=rand();
printf("\t%d",k);
}
}
I/O FUNCTIONS
Page 167
STREAM
A stream is a sequence of flow of data bytes, which is used to read and write data. The
streams that represent the input data of program are known as input streams and the streams that
represent the output data of program are known as output streams.
Input Stream
Input
Devices
C Program
Code
Output
Devices
Output Stream
Input streams interpret data from different input devices such as keyboard, mouse etc., and
provide as input data to the program.
Output streams obtain data from the program and write the data on different output devices
such as memory unit or print them on the screen.
I/O FUNCTIONS
Depending on type of the devices used for input output operations, I/O functions are classified
into three categories as:
Console I/O functions always use the terminals keyboard and screen as the target place.
These functions work on console effectively as long as the data is small. Console representation is
not suitable to manage large volume of data.
Console I/O functions can further classified into two categories as formatted and un-
Formatted console I/O functions.
Page 168
Console I/O Functions
scanf() getch()
printf() getche()
getchar()
putch()
putchar()
gets()
puts()
Disk I/O functions are performed input and output operations with the utilization of secondary
storage devices like floppy disk, hard disk etc., In disk I/O operations data is stored interms of files.
FILES
File stream is a sequence of bytes, which is used to read and write data on files.
File name is a string of characters that make up a valid name for the operating system. It
may contain two parts as a primary name and an optional period with an extension.
All files should be declared as type FILE, which is a defined data type by the compiler. The
general format of declaring and opening a file is:
Page 169
Syntax : FILE *FilePointer; /* Declaration */
Where,
FilePointer defines as a “pointer to the data type FILE”.
fopen() function receives two arguments – FileName and Mode.
o FileName is name of the file to be opened. FileName in C language can also contain
path information. The path specifies the drive and/or director where the file is
located.
o Mode specifies the type of job to be performed on the file. Mode can be any one of
the following.
MODE MEANING
When the file is opened in read mode, if it exists, the file is opened with
current contents safe; otherwise, an error occurs.
When the file is opened in write mode, if it exists, the file is opened with
current contents are deleted; otherwise, a file with specified name is created
by the compiler.
When the file is opened in append mode, if it exists, the file is opened with
current contents safe and the file pointer placed at the end of the file;
otherwise, a file with specified name is created by the compiler.
MODE MEANING
Simplest input statement used for reading data from a file is getc() function.
getc() library function is used to read a character from the file that has been opened in read
mode. The general format of getc() function is:
Syntax : ch = getc(FilePointer);
Where,
ch is character type variable.
Here,
File Pointer is opened in read mode, and the function read the data character by character
from the file and assigned to the variable ch. Whenever the end of the file has been reached, getc()
function will return and end-of-file marker EOF.
Page 170
Writing data into a file
Simplest output statement used for writing data into the file is putc() function.
putc() library function is used to write a character into the file that has been opened in write
mode. The general format of putc() function is:
Where,
ch is character type variable.
Here,
FilePointer is opened in write mode and the function writes the data of ch into the file.
Closing a File
When all operations are completed over files, it is better to close the files explicitly by calling
fclose() function; when we want to open the same file in a different mode. For this, use the syntax as:
Syntax: fclose(FilePointer);
#include<stdio.h>
main()
{
char ch;
FILE *fp1,*fp2;
clrscr();
fp1=fopen("demo.txt","r");
if(fp1==NULL)
{
printf("\nFILE OPENING ERROR");
exit();
}
fp2=fopen("exam.txt","w");
while((ch=getc(fp1))!=EOF)
{
putc(ch,fp2);
}
fclose(fp2);
fclose(fp1);
}
***
It is possible that errors may occur during I/O operations on files. Typical errors are:
Page 171
Trying to perform an operation on a file, when the file is opened in another mode.
Opening a file with an invalid name.
Trying to read beyond the end-of-file mark etc.,
To handle most of these errors on files, C language provides two library functions ferror() and feof()
that can help us to detect I/O errors and perror() function for printing error messages.
1) When the file is opened using fopen() function, a file pointer is returned. If the file cannot be
opened with some reason, then the function returns a NULL pointer. This facility can be used
to test whether a file has been opened or not.
feof() is a library used to test for end-of-file condition. The general format of feof() function
is:
Syntax : feof(FilePointer)
Function accepts FilePointer as its only argument and returns a non-zero integer value if EOF
reached; otherwise, it returns zero.
3) ferror() Function:
ferror() is a library function used to report error status of the file indication. The general
format of ferror() function is:
Syntax: ferror(FilePointer)
Function accepts FilePointer as its only argument and returns a non-zero integer value if an
error has been detected up to that point during processing; otherwise, it returns zero.
4) perror() Function:
perror() is a standard library function used to print error messages specified by the compiler.
With this function, whenever an error occurred; the function prints error message to stderr.
Here, First the argument string is printed, then a colon, then a message corresponding to the current
value of error, finally a new line.
#include<stdio.h>
Page 172
#include<conio.h>
main()
{
FILE *f;
char ch;
clrscr();
f=fopen("out.dat","w");
while(!feof(f))
{
ch=fgetc(f);
if(ferror(f))
{
perror("Error Occured:");
exit();
}
putchar(ch);
}
fclose(f);
}
/* WAP TO READ THE DATA FROM KEYBOARD AND WRITE IT INTO A FILE */
#include<stdio.h>
main()
{
char ch;
FILE *fp;
clrscr();
fp=fopen("demo.txt","w");
printf("\nEnter Text:");
ch=getchar();
while(ch!=EOF)
{
putc(ch,fp);
ch=getchar();
}
fclose(fp);
}
/* WRITE A PROGRAM TO READ THE DATA FROM A FILE AND PRINT IT ON MONITOR */
#include<stdio.h>
main()
{
char ch;
FILE *fp;
clrscr();
fp=fopen("demo.txt","r");
if(fp==NULL)
{
printf("\nFILE OPENING ERROR");
exit();
}
printf("\nFile Contents Are:");
ch=getc(fp);
Page 173
while(ch!=EOF)
{
printf("%c",ch);
ch=getc(fp);
}
fclose(fp);
}
/* WRITE A PROGRAM TO APPEND THE DATA INTO A FILE */
#include<stdio.h>
main()
{
char ch;
FILE *fp;
clrscr();
fp=fopen("demo.txt","a");
printf("\nEnter Additional Data:\n");
ch=getchar();
while(ch!=EOF)
{
putc(ch,fp);
ch=getchar();
}
fclose(fp);
}
#include<stdio.h>
main()
{
char ch;
FILE *f1,*f2,*f3;
clrscr();
f1=fopen("demo1.txt","r");
f3=fopen("result.txt","w");
if(f1==NULL)
{
printf("\nFile Opening Error");
exit();
}
while((ch=fgetc(f1))!=EOF)
fputc(ch,f3);
fcloseall();
f2=fopen("demo2.txt","r");
f3=fopen("result.txt","a");
if(f2==NULL)
{
printf("\nFile Opening Error");
exit();
}
while((ch=fgetc(f2))!=EOF)
fputc(ch,f3);
Page 174
fcloseall();
f3=fopen("result.txt","r");
if(f3==NULL)
{
printf("\nFile Opening Error");
exit();
}
printf("\nMERGING CONTENTS ARE:\n");
while((ch=fgetc(f3))!=EOF)
printf("%c",ch);
fclose(f3);
}
/* WRITE A PROGRAM TO READ THE DATA FROM A FILE AND PRINT NUMBER OF
CHARACTERS, WORDS, DIGITS, LINES AND SPECIAL SYMBOLS */
#include<stdio.h>
main()
{
char ch;
FILE *fp;
int nc=0,nd=0,nw=1,nl=1,nsp=0;
clrscr();
fp=fopen("check.txt","r");
if(fp==NULL)
{
printf("\nFILE OPENING ERROR");
exit();
}
while((ch=getc(fp))!=EOF)
{
if((ch>='a'&&ch<='z') || (ch>='A'&&ch<='Z'))
nc=nc+1;
else if(ch>='0'&&ch<='9')
nd=nd+1;
else if(ch==' '||ch=='\t')
nw=nw+1;
else if(ch=='\n')
{
nw=nw+1;
nl=nl+1;
}
else
nsp=nsp+1;
}
printf("\n No of Characters:%d",nc);
printf("\n No of Digits:%d",nd);
printf("\n No of Words:%d",nw);
printf("\n No of Lines:%d",nl);
printf("\n No of Special Symbols:%d",nsp);
fclose(fp);
}
Input and Output operations on Files
Page 175
fgetc() and fputc() are character oriented functions that provides same functionality as getc()
and putc() functions.
fgetc() function: fgetc() function is used to read a character from a file that has been opened in
read mode. The general format of the fgetc() function is:
Syntax: ch = fgetc(FilePointer);
Where,
ch is character type variable.
Here,
File Pointer is opened in read mode, and the function read the data character by character
from the file and assigned to the variable ch. Whenever the end of the file has been reached, fgetc()
function will return an end-of-file marker EOF.
fputc() function: fputc() function is used to write a character into a file that has been opened in
write/append mode. The general format of the fputc() function is:
Where,
ch is character type variable.
Here,
FilePointer is opened in write/append mode and the function writes the data of ch into the file.
/* PROGRAM TO COPY THE CONTENTS OF ONE FILE INTO ANOTHER FILE CHARACTER BY CHARACTER*/
#include<stdio.h>
main()
{
char ch;
FILE *fp1,*fp2;
clrscr();
fp1=fopen("demo.txt","r");
if(fp1==NULL)
{
printf("\nFILE OPENING ERROR");
exit();
}
fp2=fopen("exam.txt","w");
while((ch=fgetc(fp1))!=EOF)
{
fputc(ch,fp2);
}
fclose(fp2);
fclose(fp1);
}
2. fgets() and fputs() functions:
fgets() and fputs() functions are string oriented functions that can be handled an entire line as
a string at a time.
fgets() function: fgets() function is used to read a set of characters as a string from a
given file. The general format of the fgets() function is:
Page 176
Syntax: fgets(char[], int, FilePointer);
Where,
The first argument is the character array where the string is stored.
The second argument is the maximum size of the string.
The third argument is the FilePointer of the file to be read.
The function returns a NULL pointer if the end of file has been reached.
fputs() function: fputs() function is used to write a string into a file. The general format of the
fputs() function is:
Where,
The first argument is the character array to be written into the file.
The second argument is the FilePointer of the file to write.
The function returns a non-negative value on successful completion; otherwise, it returns EOF.
/* PROGRAM TO COPY THE CONTENTS OF ONE FILE TO ANOTHER FILE LINE BY LINE */
#include<stdio.h>
#include<string.h>
main()
{
char ch[50];
FILE *fp1,*fp2;
clrscr();
fp1=fopen("check.txt","r");
if(fp1==NULL)
{
printf("\nFILE OPENING ERROR");
exit();
}
fp2=fopen("ptr.txt","w");
while((fgets(ch,sizeof(ch),fp1))!=NULL)
fputs(ch,fp2);
fclose(fp2);
fclose(fp1);
}
/* PROGRAM TO READ THE DATA FROM A FILE AND PRINT NUMBER OF LINES IN IT */
#include<stdio.h>
#include<conio.h>
main()
{
char ch[50];
FILE *fp;
int lines=0;
clrscr();
fp=fopen("check.txt","r");
if(fp==NULL)
{
Page 177
printf("\nFILE OPENING ERROR");
exit();
}
while((fgets(ch,sizeof(ch),fp))!=NULL)
{
lines=lines+1;
}
printf("\n No of Lines =%d",lines);
fclose(fp);
}
3. getw() and putw() functions:
getw() and putw() are number oriented functions are used to read and write integer values on
a given file.
getw() function: getw() function is used to read an integer value from a given file.
The general format of the getw() function is:
Syntax: getw(FilePointer);
This function receives FilePointer as an argument and returns next integer from the input file. It
returns EOF whenever end of file has been reached.
putw() function: putw() function is used to write an integer value into the specified file. The
general format of the putw() function is:
Syntax: putw(N,FilePointer);
Where,
N is an integer value to be written into the given file with FilePointer opened in write mode.
#include<stdio.h>
#include<conio.h>
main()
{
int item,n,i;
FILE *f1,*f2,*f3;
clrscr();
f1=fopen("input.dat","w");
printf("\nEnter how many numbers:");
scanf("%d",&n);
printf("\nEnter %d Numbers:",n);
for(i=1;i<=n;i++)
{
scanf("%d",&item);
putw(item,f1);
}
fclose(f1);
f1=fopen("input.dat","r");
if(f1==NULL)
Page 178
{
printf("\nFILE OPENING ERROR");
exit();
}
f2=fopen("even.dat","w");
f3=fopen("odd.dat","w");
while((item=getw(f1))!=EOF)
{
if(item%2==0)
putw(item,f2);
else
putw(item,f3);
}
fcloseall();
printf("\nEVEN NUMBERS ARE:");
f2=fopen("even.dat","r");
while((item=getw(f2))!=EOF)
printf("%6d",item);
fclose(f2);
printf("\nODD NUMBERS ARE:");
f3=fopen("odd.dat","r");
while((item=getw(f3))!=EOF)
printf("%6d",item);
fclose(f3);
}
4. fprintf() and fscanf() functions:
Most compilers support two functions namely fprintf() and fscanf() functions, that can handle
a group of mixed data simultaneously. The functions fprintf() and fscanf() perform I/O operations
that are identical to printf() and scanf() functions, except that they work on files.
fscanf() funcnton: fscanf() function is used to read mixed data simultaneously form a given file.
The general format of the fscanf() function is:
Where,
FilePointer associated with the file that has been opened for reading.
ControlString consists of format specification for the items in the list.
List may include variables, constants, strings etc.,
Function returns EOF marker whenever end of the file has been reached.
fprintf() function: fprintf() function is used to write mixed data simultaneously into a given file.
The general format of the fpritnf() function is:
Where,
FilePointer associated with the file that has been opened for writing.
ControlString consists of output format specification for the items in the list.
List may include variables, constants, strings etc.,
Page 179
/* WRITE A PROGRAM TO CREATE A FILE THAT CONTAINS INVENTORY DETAILS LIKE
PRODUCT NUMBER, PRODUCT NAME AND PRODUCT COST. READ THE SAME DATA
FROM THE FILE AND PRINT IT */
#include<stdio.h>
#include<conio.h>
struct product
{
int id;
char name[20];
float price;
}p;
main()
{
char flag='y';
FILE *f;
clrscr();
f=fopen("product.dat","w");
while(flag=='y')
{
printf("\nEnter product id:");
scanf("%d",&p.id);
fflush(stdin);
printf("\nEnter product name:");
gets(p.name);
printf("\nEnter product cost:");
scanf("%f",&p.price);
fprintf(f,"%d\t%s\t%f\n",p.id,p.name,p.price);
printf("\nDo you want add another record(y/n):");
fflush(stdin);
flag=getchar();
}
fclose(f);
f=fopen("product.dat","r");
if(f==NULL)
{
printf("\nFILE OPENING ERROR");
exit();
}
printf("\nPRODUCT DETAILS ARE:\n");
while((fscanf(f,"%d%s%f",&p.id,p.name,&p.price))!=EOF)
printf("\n%d\t%s\t%.2f",p.id,p.name,p.price);
fclose(f);
}
STANDARD DOS SERVICES / STREAMS
fopen() function is used to open a file in a specified mode. Ms-Dos also predefines pointers
for five standard files. To access these pointers, we need not use fopen() function. Those standard
file pointers are:
/* WRITE A PROGRAM TO READ DATA FROM STANDARD INPUT DEVICE AND PRINT IT
ON STANDARD OUTPUT DEVICE */
#include<stdio.h>
main()
{
char ch;
clrscr();
printf("\nEnter data:");
while((ch=fgetc(stdin))!=EOF)
fputc(ch,stdout);
}
/* WRITE A PROGRAM TO READ DATA FROM A FILE AND PRINT IT ON THE PRINTER */
#include<stdio.h>
main()
{
char ch;
FILE *f;
clrscr();
f=fopen("product.dat","r");
if(f==NULL)
{
printf("\nFile Opening Error");
exit();
}
while((ch=fgetc(f))!=EOF)
fputc(ch,stdprn);
}
FILE FORMATS
File formats can be categorized into two ways as: Text mode format and Binary mode
format. This classification arises at the time of opening the file.
When a file is opened either in “r”, “w” or “a” modes, default file format is text mode
format. If the user wants to open the file in binary format, explicitly necessary to specify as “rb”,
“wb”, or “ab”.
There are three main differences raised between a text file and binary files. Those are:
1. Handling of new lines
2. Representation of End-Of-File
3. Storage of numbers.
1. In text mode, a new line character is converted into the combination of carriage return – line
feed before being written into the disk.
Page 181
In binary mode, conversions not take place. A new line character is written into the disk as in
the original format.
2. In text mode, a special character is inserted after the last character in the file to mark the End-
Of-File. If this character is detected at any point in the file, then read function would return the EOF
signal to the program.
In binary format, there is no such special character present to mark the End-Of-File. The
binary mode files keep track of the End-Of-File from the number of characters present in the directory
entry of the file.
3. In text mode, while storing numbers in files, numbers are stored as string of characters.
Consider a number 4523.
In memory, it occupies 2 bytes. Whereas when the number placed on the disk, it would occupy 4
bytes as one byte per each character. Since, it depends on magnitude of the number.
In such case, large amount of data storage in a disk file is inefficient.
In binary mode, number would occupy same number of bytes on disk as it occupies in
memory unit. With this, the above number occupies only 2 bytes even on the disk file.
I/O Operations on Binary Files:
fread() and fwrite() functions are used to read and write data in binary format. The general
formats of fread() and fwrite() functions are:
#include<stdio.h>
Page 182
typedef struct
{
int rno;
char name[25],branch[5];
}student;
main()
{
int i,n;
student s[20];
FILE *f=fopen("st.txt","wb");
clrscr();
printf("\nEnter how many students:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nEnter student %d details:",i);
scanf("%d%s%s",&s[i].rno,s[i].name,s[i].branch);
fwrite(&s[i],sizeof(s[i]),1,f);
}
fclose(f);
f=fopen("st.txt","rb");
printf("\n Database Details Are:\n");
for(i=1;i<=n;i++)
{
fread(&s[i],sizeof(s[i]),1,f);
printf("\n%d\t%s\t%s",s[i].rno,s[i].name,s[i].branch);
}
fclose(f);
}
FILE ACCESSING TECHNIQUES (or) FILE TYPES
Every open file has an associated file position indicator, which describes where read and write
operations take place in the file. The position is always specified in bytes from the beginning of the
file.
When a file is opened in either read (or) write mode, the position indicator is always at
beginning of the file i.e., at position ‘0’. If the file is opened in append mode, the position indicator is
at the end of the file.
2. Random Access File Processing: In random access file processing, the file pointer can
change from one location to another location according to user requirements. Here, operations are
performed in random access manner. Most important functions used in random access file processing
are:
a) fseek()
b) ftell()
Page 183
c) rewind()
a) fseek() function: fseek() function is used to move the position indicator to a desired location
within the file. The general format of the fseek() function is:
Where,
OffSet is the number of bytes to be moved and it must be long integer. The value
may be positive of negative. If the OffSet value be positive, file pointer moves to
forward direction; otherwise, file pointer moves to backward direction.
Position specifies the starting position in the file to move. Position can take any one
of the following three values.
VALUE MEANING
0 Beginning of File
1 Current Position
2 End of File
When the operation is successful, fseek() function returns zero; otherwise, it return -1.
Examples:
b) ftell() function: ftell() function is used to return the current position of the file pointer in the
file. The general format of the ftell() function is:
Syntax: N = ftell(FilePointer);
Where,
N is a long integer variable.
Function returns current position (in bytes) as long integer value. If any error encountered, then the
function returns -1.
c) rewind() function: rewind() function is used to reset the file pointer to beginning of the
file. The general format of the rewind() function is:
Syntax: rewind(FilePointer);
#include<stdio.h>
main()
{
FILE *fp;
long n;
Page 184
char ch;
clrscr();
fp=fopen("win.dat","r");
if(fp==NULL)
{
printf("\nFile Opening Error");
exit();
}
while(1)
{
n=ftell(fp);
if((ch=fgetc(fp))==EOF)
exit();
printf("\n%c position is: %ld Byte",ch,n);
}
fclose(fp);
}
/* WRITE A PROGRAM TO PRINT THE CONTENTS OF A FILE IN REVERSE ORDER */
#include<stdio.h>
main()
{
FILE *fp;
long n,i;
char ch;
clrscr();
fp=fopen("den.txt","r");
if(fp==NULL)
{
printf("\nFile Opening Error");
exit();
}
fseek(fp,-1L,2);
n=ftell(fp);
printf("\nFile Contents in Reverse Order:\n");
for(i=1;i<=n+1;i++)
{
fseek(fp,-i,2);
putchar(fgetc(fp));
}
fclose(fp);
}
ADDITIONAL FUNCTIONS
1. fcloseall():
fcloseall() is a library function used to close all file streams opened explicitly by the
user. The general format of fcloseall() function is:
Example : fcloseall();
Page 185
Function returns integer value that shows number of closed files if successful; otherwise, it
returns EOF marker.
2. fflush():
fflush() is a library function used to flush the contents of output stream. The general
format of fflush() function is:
Example : fflush(stdin);
C was originally implemented for the UNIX operating system. Early versions of C support a
set of I/O functions that are compatible with UNIX. This set of I/O functions is sometimes referred as
Unix-like I/O System or Unbuffered I/O System.
When C was standardized, the Unix-like functions were not incorporated into the standard to
avoid redundancy.
Page 186