IP-Notes
IP-Notes
Introduction to Programming
(23A05301A)
(Common to All Branches of Engineering)
COURSE OBJECTIVES:
COURSE OUTCOMES:
After completion of the course, the student will be able to:
CO1: Understand basics of computers, the concept of algorithm and algorithmic thinking. (K2)
CO2: Analyze a problem and develop an algorithm to solve it. (K4)
CO3: Implement various algorithms using the C programming language. (K3)
CO4: Understand more advanced features of C language. (K2)
CO5: Develop problem-solving skills and the ability to debug and optimize the code. (K3)
TEXT BOOKS:
REFERENCE BOOKS:
1. www.learn-c.org
2. www.github.com
***
UNIT – I
***
COMPUTER Computer is an electronic device that takes data as input from input
devices, processes 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 known as information.
HISTORY OF COMPUTERS
The first mechanical calculating apparatus was the abacus, which was invented in
500 BC.
In 1823, Charles Babbage was introduced a programmable calculating machine.
J.W. Mauchly and S.P. Eckert introduced the first general-purpose electronic digital
computer in 1946. It was called the ENIAC (Electronic Numerical Integrator and
Calculator).
Desktop computers available from 1975 onwards. In 1981, IBM (International
Business Machines) used the 8088 microprocessor in the personal computer.
32-Bit microprocessor chips arrived from 1986. Intel Pentium systems was designed
in 1993, a highly improved personal computer was available at an affordable price.
From the year 2000 onwards there has been a tremendous effort to increase the speed
and computing capability of the processor resulting in the development of multi-core
processors.
The arrival of microprocessors triggered the development of desktop computers, in
the form of personal computers and portable computers like the laptops and tablets.
GENERATION OF COMPUTERS
The generation of a computer is determined by the technology it uses. There are five
generation of computers. Those are:
First generation computers use vacuum tubes as the electric components to perform
operations. The first successful electronic computer was introduced as ENIAC (Electronic
Numeric Integrated And Calculator).
A computer system can be divided into two parts-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. It includes all mechanical, electrical and electronic parts attached to
it. The most important hardware components are:
1. Input Devices
2. Output Devices
3. Central Processing Unit
4. Memory Unit
Register Unit
ROM RAM
Memory Unit
1. Input Devices:
Input devices are electronic equipment which communicating with the computer
system to submit data and instructions. The data and instructions are typed, submitted, or
transmitted to a computer through input devices.
2. Output Devices:
Output devices display information after processing the instructions to the computer.
The output information can be of visual or audio type depending on the type of output device
used. The most common output device is monitor or visual display unit.
CPU is formed with the combination of three functional units such as:
Arithmetic Logic Unit (ALU)
Control Unit (CU)
Register Unit (RU)
Arithmetic Logic Unit is the part of the CPU that performs arithmetic operations
such as addition and subtraction, logical operations such as comparison of two values etc.
Register unit is a high-speed storage device used to store data temporarily while
executing the instructions. It consists of different types of registers such as Program counter,
Instruction register used for several purposes. Program counter is a a fundamental
component of a computer's central processing unit (CPU). It is a special register that keeps
track of the memory address of the next instruction to be executed in a program. Instruction
register (IR) is the part of a CPU's control unit that holds the instruction currently being
executed or decoded.
Control unit coordinates the processing by controlling the transfer of data and
instructions between main memory and the registers in the CPU. It also coordinates the
execution of ALU to perform operations on data stored in particular registers.
4. Memory Unit:
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 is called contents of the cell. Data is stored in memory as binary
digits called bits.
a) Primary Memory
b) Secondary Memory
a) Primary Memory: Primary memory is the area where data and programs
are stored while the program is being executed along with the data. Primary memory is also
known as main memory.
RAM stores programs, 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. Therefore, 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.
Primary storage devices and secondary storage devices are available in different
storage capacities like Bytes, Kilobytes, Megabytes, Gigabytes and Terabytes.
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:
OPERATING SYSTEM
HARDWARE COMPONENTS
3. Packages: Packages are used to store large volume of data for future use.
1. Low-level languages
2. High-level languages
1. Low-level Languages
a) Machine language:
Machine language is formed with the combination of machine codes, which are
binary numbers as 0’s and 1’s. Machine language is also known as binary language. Machine
language is the language of the computer. Computer can understood only machine language.
Machine language is considered to be the first generation language (1GL).
Advantages:
Disadvantages:
b) Assembly language:
Assembly language is formed with the combination of simple English words known
as mnemonic codes like ADD, SUB, MUL etc., Assembly language programs are formed
with the co-ordination of Registers concept. Assembly language is considered to be the
second-generation language (2GL).
Advantages:
Disadvantages:
2. High-level Languages
High-level languages are formed with the combination of simple English sentences.
They always tried to improve program efficiency while designing the programs. i.e., they
allow the user to develop the program in simple context rather than the hardware technology.
Hence, high-level languages are easier to design programs compared to machine language
and assembly language. High-level languages are also called third generation languages
(3GL).
Advantages:
Readability, Portability
Easy debugging
Ease in the development of software
High-level languages are further classified into different types such as:
a) Procedural languages
b) Structured programming languages
c) Object-oriented languages
a) Procedural languages:
Program is divided into number of procedures and data can be moved from
one place to another place.
Program is divided into number of functions and data can be moved from
one function to another function.
User-defined functions are introduced.
c) Object-oriented languages:
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf(“ AUTONOMOUS ”);
}
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 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
process.
Assembler
Compiler
Interpreter
Data
Interpreter is also used as a translator for high- level language programs. It accepts
source program line by line and translates it into machine language, which is immediately
executed.
Interpreter loaded
Source program Result
computer
Data
Compiler and Interpreter both are translators used to convert the high-level
language program into machine code and vice versa.
ALGORITHM
Step-form Format
Pseudo-code Format
Flowchart Format
Nassi–Shneiderman diagram Format
1. Each algorithm will be logically enclosed by two statements START and STOP.
2. To accept data from user, the INPUT or READ statements are to be used.
3. To display any user message or the content in a variable, PRINT/WRITE/DISPLAY
statement will be used. The message will be enclosed within quotes.
4. ← symbol used to assign a value to the variable.
5. +, -, * and / symbols are used to indicate arithmetic operations such as addition,
subtraction, multiplication and division operations.
6. <, >, ≤, ≥, = and ≠ symbols are used to compare the given operand values.
7. AND, OR, NOT words used for conjunction, disjunction and negation operations.
Example:
Step 1: START
Step 2: Read two input values as X and Y
Step 3: Add X and Y values and store the result value in Z
Step 4: Print addition result value as Z
Step 5: STOP
Step 1: START
Step 2: INPUT X , Y
Step 3: Z←X+Y
Step 4: PRINT Z
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.
Step 1: START
Step 2: INPUT X , Y
Step 3: Sum ← X + Y
Step 4: PRINT Sum
Step 5: STOP
b) Selection algorithm:
Step 1: START
Step 2: INPUT X, Y values
Step 3: IF X > Y THEN
Max ← X
ELSE
Max ← Y
ENDIF
Step 4: PRINT Max
Step 5: STOP
c) Iteration algorithm:
Step 1: START
Step 2: INPUT N value
Step 3: Rev ← 0
Step 4: Repeat WHILE N > 0
K ← N MOD 10
Rev ← Rev * 10 + K
N ← N / 10
EndRepeat
Step 5: PRINT Rev
Step 6: STOP
FLOWCHARTS
A flowchart comprises a set of standard shaped boxes that are interconnected by flow
lines. Flow lines have arrows to indicate the direction of the flow of control between the
boxes. The activity to be performed is written within the boxes.
Flowcharts are usually drawn using standard symbols. Flowcharts play a vital role in
the programming of a problem and are quite helpful in understanding the logic of
complicated and lengthy problems. Once the flowchart is drawn, it becomes easy to write the
program in high-level language.
Symbol :
Example :
START STOP
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
WRITE ‘Hello’
STOP
Symbol : :
Example : Sum ← X + Y
CONNECTOR: 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/Rhombus”.
Symbol :
For this symbol, input is at one way and output is either of two ways.
Example :
Is x>0 F
SYMBOL DESCRIPTION
DATA BASE
SUB ROUTINE
MULTIDOCUMENTS
MERGE
START INPUT X, Y
SUM ← X + Y
Uses of Flowcharts:
The process of creating and running programs is falls into four stages as:
After typing the program in the editor, save the file in the disk. This program is
known as a source program. 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.
The compilation process consists of two steps: the analysis of the source program and the
synthesis of the object program.
The analysis phase uses the precise description of the source programming language.
A source program is described using lexical rules, syntax rules, and semantic rules.
Lexical rules specify the valid syntactic elements or words of the language. Syntax
rules specify the way in which valid syntactic elements are combined to form the statements
of the language. Semantic rules assign meaning to valid statements of the language.
First, the lexical analyzer takes successive line of a program and breaks them into
individual lexical items, namely identifier, operators and attaches a tag to each of these units.
It constructs a symbol table for each identifier and finds the internal representation of each
constant. In second stage, syntax analysis is done using techniques based on formal
grammar of the programming languages. In semantic analysis an intermediate code of the
final machine language is produced.
In final stage, code generator produces object code of the source program which is a
machine language program. The output machine language code is known as an 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
Program
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 a program is compiled and linked, each instruction and each item of data is
assigned an address. At execution time, the CPU finds instructions and data from these
addresses. For this, CPU uses Instruction register (IR) that holds the current instruction
being executed and Program Counter (PC) register that holds the address of the next
instruction to be executed in a program
In the beginning, CPU fetches and then executes the instruction found at this address.
Then PC increments the address to the next instruction. Based on the instructions, 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
Program
Input Data
PROBLEM-SOLVING STRATEGIES
In problem solving aspect, there are number of steps that can raise the level of
performance to obtain the solution of the given problem statement. In fact, there is no
universal method. Different strategies appear to work for different types of users. However,
some of the most common steps are:
There are many ways to solve most of the problems and many solutions.
Identify the number of possible solutions for the given problem statement.
The way of developing problem solving is the ability to view the problem
from a variety of ways.
Identify the similarities by comparing with other related problem statements.
In some cases assume that, we already have the solution to the problem and try
to work backwards to the starting conditions.
Divide-and-Conquer strategy,
Dynamic programming,
Greedy strategy,
Backtracking,
Branch-and-Bound etc.
1. Top-Down approach
2. Bottom-up approach
1. Top-down Approach
Top-down design is a process of breaking the overall problem into sub problems and
then subdivides each sub-problem until the lowest level of details has been reached.
In this procedure, the actual problem statement is at the top level. Divide the problem
into appropriate sub-problems based on the specified constraints. While dividing into sub-
problems, assure that each sub problem definition must be independent of each other. Divide
to that extent until the sub problem is not possible for further division. Finally, those sub
problems individually solved and combine to produce the original solution.
Problem Statement
Sub-Task 4 Sub-Task 5
Algorithm Algorithm
2. Bottom-Up Approach
Already existing facilities are taken into consideration as a model for a new design.
In bottom-up strategy, use existing computer as a model for the new program. When we try
to utilize the existing design in a proper way, it gives a better solution for the current problem
statement.
Module 1 - - - - - - -- Module N
Problem Statement
Apriori analysis
Posterior analysis.
Apriori analysis means, the analysis is done for the problem before it run on the
machine. Posterior analysis is done after running the problem in a specific programming
language.
The time complexity of an algorithm is the amount of computer time it needs to run
to its completion. The space complexity of an algorithm is the amount of memory space it
needs to run to its completion.
Time and space complexities are calculated based on the size of the input data. Based
on the size of the input data, analysis can be divided into three cases as:
Best case analysis: In best case analysis, problem statement takes minimum
number of computations for the given input parameters.
Based on the size of input requirements, complexities can be varied. Hence, exact
representation of time and space complexities is not possible. But they can be shown in
some approximate representation using mathematical notations known as asymptotic
notations. Those are:
The function f(n) = O(g(n)) iff there exist two positive constants c and n0 such that
f(n) ≤ c * g(n) for all n, n ≥ n0.
The graphical representation between n values on X-axis and f(n) values on Y-axis is as
follows:
Y
c*g(n)
Here, the functional value f(n) is always below the
estimated functional value c*g(n). Thus, the function n0
g(n) acts as upper bound value for the function f(n).
Hence, Big ‘Oh’ notation is treated as “Upper bounded f(n)
Function”.
f(n)
n X
Example:
From this,
c=4 g(n) = n and n0 = 2
Hence, the function 3n+2 = O(n) iff there exist two positive constants 4 and 2 such
that 3n+2 ≤ 4n for all n, n ≥ 2.
In these complexities,
O(1) means constant
O(n) means linear
O(log n) means logarithmic
O(n2) means quadratic
3
O(n ) means cubic
O(2n) means exponential.
O(1) < O(log n) < O(n) < O(n logn) < O(n2) < O(n3) < - - - - - - - < O(2n) .
The function f(n) = Ω(g(n)) iff there exist two positive constants c and n 0 such that
f(n) ≥ c * g(n) for all n, n ≥ n0.
The graphical representation between n values on X-axis and f(n) values on Y-axis is as
follows:
Y f(n)
n X
Example:
Consider f(n) = 3n+2
Assume that 3n+2 ≥ 3n
The function f(n) = Ө(g(n)) iff there exist three positive constants c1, c2 and n0 such
that c1 * g(n) ≤ f(n) ≤ c2 * g(n) for all n, n ≥ n0.
The graphical representation between n values on X-axis and f(n) values on Y-axis is as
follows:
Y
c2 * g(n)
Example:
From this,
c1 = 3 c2 = 4 g(n) = n and n0 = 2
Hence, the function 3n+2 = Ө(g(n)) iff there exist three positive constants 3,4 and 2
and n0 such that 3n ≤ 3n+2 ≤ 4n for all n, n ≥ 2.
The function f(n) = o(g(n)) iff there exist two positive constants c and n0 such that
f(n) < c * g(n) for all n, n ≥ n0.
(OR)
𝑓(𝑛)
The function f(n) = o(g(n)) iff Lim = 0
𝑔(𝑛)
n→∞
The function f(n) = ω(g(n)) iff there exist two positive constants c and n 0 such that
f(n) > c * g(n) for all n, n ≥ n0.
OR
𝑔(𝑛)
The function f(n) = ω(g(n)) iff Lim = 0
𝑓(𝑛)
n→∞
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 Waterfall model.
1. Analysis
2. Algorithm & Flowchart
3. Program Design
4. Compilation
5. Program Execution
6. Testing & Validation
START
Step 1: START
Step 3: sum ← x + y
sum ← x + y
Step 4: WRITE sum
Step 5: STOP
WRITE sum
STOP
3. Program Design: The flowchart and algorithm steps developed in the previous
phase are 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(“\n Enter Two Numbers =”);
scanf(“%d%d”,&X,&Y);
SUM = X + Y ;
printf(“\n Addition Result = %d”,SUM);
}
Example:
In C language, the above program is compiled by pressing either F9 or Alt+F9 keys.
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:
Logical Errors: These errors may occur due to incorrect usage of the
instructions in the program. These errors are detected during neither compilation nor
execution nor cause any stoppage to the program execution. They only produce unwanted
outputs.
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. 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.
***
B B Language
C C Language
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
2. C is a middle-level language.
Depending on the efficiency and performance, programming languages are
classified into two types as:
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.
C language contains a rich set of built-in functions and operators those are
used to design complex programs.
6. C is a core language.
In computing, C is a general purpose, block structured programming language.
A number of common and popular computer programming languages are based on C.
Having learnt C, it will be much easier to learn other languages such as C++, Java and
Perl.
C CHARACTER SET
A constant is a quantity that does not change during the program execution.
A variable is a quantity that can change during the program execution.
Example: 3X + Y = 20
Here, 3, 20 are constants and X, Y are variables.
KEYWORDS
The words which are predefined by the system compiler are called as keywords.
Keywords are also known as ”Reserved Words”. All keywords must in lower case
characters. 32 keywords are available in C language. Those are:
IDENTIFIER
The words which are defined by the user are called identifiers. Identifiers are treated
as user-defined words. An identifier is a name given to the variable, constant, array, structure
etc. Identifier names are assigned by the users according to their requirements based on the
problem statements.
Example: sum
X etc.
DATA TYPES
The type of the value stored in a variable is called its data type. In C language, data
types are classified into different types as:
Data Types
C language supports char, int, float and double data types as primitive data types that
are used for storing characters, integers and real values.
When variables are declared with its appropriate data types, compiler allocates
sufficient amount of memory for the variables based on the type of the language.
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.
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 variable. The
general format of declaring a variable is:
X P
Example: int X;
float P;
2 Bytes 4 Bytes
Multiple variables of the same data types can be declared in a single statement by
separating with comma operator as:
X
Example: int X = 40; 40
2 Bytes
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 called as C tokens. C language has
six types of tokens as:
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”. All keywords must in lower
case characters. 32 keywords are available in C language. Those are:
2. Identifiers: The words which are defined by the user are known as identifiers.
These words are treated as user-defined words. i.e., Names given to variables, constants,
arrays, structures etc., are often knows as identifiers.
3. Constants: A constant is a quantity that does not change during the program
execution. C language supports several types of constants as:
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.
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:
Example: 2179e-2
Character Constants: Character constant contains a single character enclosed within a pair of
single quotation marks. The character may be alphabet, digit and special symbol.
Example: HELLO
5. Operators: Operator is a symbol that tells the compiler to perform some action. C
language supports different operators: Arithmetic operators, Relational operators, Logical
operators, Increment & Decrement operators, Conditional operators etc.
6. Special Symbols: C language supports various special symbols that perform different
types of actions. Those symbols are used in various applications for different purposes based
on the type of problem statements.
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 according to user
requirements. Some of them are:
CONSTANT MEANING
‘\a’ Bell Sound Character
‘\n’ New Line Character
‘\f’ Form Feed Character
‘\r’ Carriage Return Character
‘\t’ Horizontal Tab Character
‘\v’ Vertical Tab Character
‘\0’ Null Character
COMMENTS
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”);
clrscr( );
getch( ); etc.
HEADER FILES
Syntax 1: #include<HeaderFileName>
Syntax 2: #include”HeaderFileName”
Example: #include<stdio.h>
#include “stdio.h”
Note: stdio.h (Standard Input Output Header File) is a header file that provides input
and output library functions.
clrscr(): It is a library function that is used to clear the screen contents. The general
format of clrscr() function is:
Syntax: clrscr();
Example: clrscr();
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:
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:
The scanf() statement requires ‘&’ operator called address operator. The role of the
address operator is to indicate the memory location of the variables.
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:
2. printf(“String”);
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.
%d - int
%c - char
%lf - double
%f - float
%u - unsigned int
%ld - long int
%o - octal
%x - hexa decimal
Note: In printf() library functions, it is possible to place any commas, blank spaces and
output format characters like escape sequence characters in the between the control strings to
display outputs in various formats.
printf(“HELLO”);
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.
Example:
***
Example: x + y = 10;
Here,
x, y and 10 are operands ; + and = are operators
1. Assignment operator
2. Arithmetic operators
3. Relational operators
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
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("\n Enter Two Numbers:");
scanf("%d%d",&x,&y);
sum = x + y;
sub = x - y;
mul = x * y;
div = x / y;
rem = x % y;
printf("\n Addition Value = %d",sum);
printf("\n Subtraction Value = %d",sub);
printf("\n Multiplication Value = %d",mul);
printf("\n Division Value = %d",div);
printf("\n Remainder Value = %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.
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("\n Result 1 = %d",14>78);
printf("\n Result 2 = %d",14<78);
printf("\n Result 3 = %d",25<=50);
printf("\n Result 4 = %d",25>=50);
printf("\n Result 5 = %d",100==100);
printf("\n Result 6 = %d",100!=100);
}
4. Logical Operators
C language supports logical operators as &&, || and ! Operators. Logical operators are
used to combine two or more relational expressions.
Any expression that forms with the combination of logical operators and operands is
termed as a logical expression. Logical expressions are also known as compound relational
expressions.
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.
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0
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).
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("\n Result 1 = %d",(14>78)&&(24<78));
printf("\n Result 2 = %d",(14>78)||(24<78));
printf("\n Result 3 = %d",!45);
}
++ and -- operators are called increment and decrement operators. These operators
are unary operators 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("\n Pre-Increment X Value = %d",x);
printf("\n Pre-Increment Y Value = %d",y);
y = x++;
printf("\n Post-Increment X Value = %d",x);
printf("\n Post-Increment Y Value = %d",y);
y = - -x;
printf("\n Pre-Decrement X Value = %d",x);
printf("\n Pre-Decrement Y Value = %d",y);
y = x - -;
printf("\n Post-Decrement X Value = %d",x);
printf("\n Post-Decrement Y Value = %d",y);
}
6. Conditional Operator
Here,
First Expression1 is evaluated. It produces either TRUE or FALSE.
If Expression1 outcome is TRUE, then Expression2 is evaluated and becomes result
of the total expression.
If Expression1 outcome is FALSE, then Expression3 is evaluated and becomes result
of the total expression.
#include<stdio.h>
#include<conio.h>
main()
{
int A,B,Max;
clrscr();
printf("\n Enter Two Numbers =");
scanf("%d%d",&A,&B);
Max = (A>B) ? A : B ;
printf("\n Maximum Number = %d",Max);
}
7. Bitwise Operators
C language supports bitwise operators as &, |, ^, ~, << and >> operators. These
operators are used to manipulate data of the operands at bit level i.e., operations are
performed on corresponding bits of the given operands. Bitwise operators can operate only
on integer quantities such as int, char, short int, long int etc.,
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.
OPERATOR MEANING
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
~ One’s Complement
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.
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
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 right 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("\n Left Shift Result = %d",x<<2);
x = 24;
printf("\n Right Shift Result = %d",x>>2);
}
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.
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("\n SIZE OF K = %d Bytes",sizeof(k));
printf("\n SIZE OF P = %d Bytes",sizeof(p));
printf("\n SIZE OF Z = %d Bytes",sizeof(z));
printf("\n SIZE OF T = %d Bytes",sizeof(t));
printf("\n SIZE OF INT = %d Bytes",sizeof(int));
printf("\n SIZE OF CHAR = %d Bytes",sizeof(char));
printf("\n SIZE OF FLOAT = %d Bytes",sizeof(float));
printf("\n SIZE OF DOUBLE = %d Bytes",sizeof(double));
printf("\n SIZE OF INT VALUE = %d Bytes",sizeof(100));
printf("\n SIZE OF CHAR VALUE = %d Bytes",sizeof('A'));
printf("\n SIZE OF FLOAT VALUE = %d Bytes",sizeof(23.45f));
printf("\n SIZE OF DOUBLE VALUE = %d Bytes",sizeof(456.678));
}
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("\n Enter X Value =");
scanf("%d",&x);
x + = 6;
printf("\n X 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 requires 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.,
c) Ternary operators: Ternary operator requires more than two operands for
implementing the specified operation.
Example: ? :
Highest precedence operator is evaluated first before the lowest precedence operator.
If two or more operators have same precedence, it follows associativity.
Example: Y = 4 + 10 * 2;
Y
= + * 24
Y = 4 + 20
= +
Y = 24
Example: 3*8/4%4
*/% L→R
24 / 4 % 4
/% L→R
6%4
%
2
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
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
#include<stdio.h>
#include<conio.h>
main()
{
int y;
clrscr();
y = 2 + 10 * 2;
printf("\n Result 1 = %d",y);
y = 3 * 8 / 4 % 4 * 5;
printf("\n Result 2 = %d",y);
}
The process of converting data items from one data type to another data type is called
type casting.
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. The general format of explicit type casting is:
In explicit type casting, there may be a loss of data while converting from higher data
type to lower data types.
Example:
z = x / y; z = (float) x / y;
z = 14/3; z = 14.000000 / 3;
z = 4.000000; z = 14.000000 / 3.000000;
z = 4.666667;
#include<stdio.h>
#include<conio.h>
main()
{
int x,y,z,total;
float Avg;
clrscr();
printf("\n Enter Three Values =");
scanf("%d%d%d",&x,&y,&z);
total = x + y + z;
Avg = (float) total / 3;
printf("\n Average Result = %f",Avg);
}
***
UNIT- II
Control Structures
Simple sequential programs Conditional Statements (if, if-else, switch), Loops (for, while,
do-while) Break and Continue.
***
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(“\n Result = %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.
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 = %d",y);
}
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
{
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("\n Enter Three Numbers =");
scanf("%d%d%d",&x,&y,&z);
if(x > = y)
{
if(x > = z)
printf("\n Maximum Number = %d",x);
else
printf("\n Maximum Number = %d",z);
}
else
{
if(y > = z)
printf("\n Maximum Number = %d",y);
else
printf("\n Maximum Number = %d",z);
}
}
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("\n Enter Three Numbers =");
scanf("%d%d%d",&x,&y,&z);
if(x > = y && x > = z)
printf("\n Maximum Number = %d",x);
else if(y > = z)
printf("\n Maximum Number = %d",y);
else
printf("\n Maximum Number = %d",z);
}
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.
Syntax: switch(Expression)
{
case value1: Block-I Statements
break;
.
.
.
case valuen: Block-n Statements
break;
Statements-X
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("\n Enter Your Choice = ");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\n RED COLOUR SELECTED");
break;
case 2:printf("\n GREEN COLOUR SELECTED");
break;
case 3:printf("\n BLUE COLOUR SELECTED");
break;
default: printf("\n INVALID 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
}
#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("\n VOWEL");
break;
default: printf("\n CONSONANT");
}
}
CONDITIONAL EXPRESSION
Here,
#include<stdio.h>
#include<conio.h>
main()
{
int A,B,Max;
clrscr();
printf("\n Enter Two Numbers = ");
scanf("%d%d",&A,&B);
Max = (A>B) ? A : B ;
printf("\n Maximum Number = %d",Max);
}
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
repeated until the test condition reaches to FALSE. The pre-test loop is also known as an
entry-controlled loop.
Condi FALSE
tion
TRUE
Statements
Statements
FALSE
Condi
tion
TRUE
i) while statement
ii) do-while statement
iii) for statement
i) while statement: While statement is used for repetitive execution of same 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.
#include<stdio.h>
#include<conio.h>
main()
{
int i,n;
clrscr();
printf("\n Enter how many numbers = ");
scanf("%d",&n);
printf("\n Natural 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);
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.
#include<stdio.h>
#include<conio.h>
main()
{
int i=1,n;
clrscr();
printf("\n Enter how many numbers = ");
scanf("%d",&n);
printf("\n NATURAL NUMBERS ARE = ");
do
{
printf(" %d",i);
i = i + 1;
}
while(i < = n);
}
iii) for statement: “for” is also a loop control statement used for repetitive execution of
statements. The general format of a for statement is:
Here,
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.
#include<stdio.h>
#include<conio.h>
main()
{
int i,n;
clrscr();
printf("\n Enter how many numbers = ");
scanf("%d",&n);
printf("\n NATURAL NUMBERS ARE = ");
for(i = 1 ; i < = n ; i++)
printf(" %d",i);
}
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.
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.
Example: 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.
#include<stdio.h>
#include<conio.h>
main()
{
int i,j,N;
clrscr();
printf("\n Enter how many Rows =");
scanf("%d",&N);
printf("\n RESULT FORMAT = \n");
for(i = 1; i <= N; i++)
{
printf("\n");
for(j = 1; j < = i; j++)
printf(" %d",j);
}
}
i) break statement
ii) continue statement
iii) goto statement
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.
#include<stdio.h>
#include<conio.h>
main()
{
int i,x,sum = 0;
clrscr();
for(i = 1 ; i < = 5 ; i++)
{
printf("\n Enter Number %d = ",i);
scanf("%d",&x);
if(x < 0)
break;
sum = sum + x;
}
printf("\n Total = %d",sum);
}
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.
#include<stdio.h>
#include<conio.h>
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 within 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 : _ _ _ ___
___ ---
/* Example program for FORWARD JUMP */ /* Example program for BACKWARD JUMP */
#include<stdio.h> #include<stdio.h>
main() main()
{ {
int i,x,sum=0; int i,x,sum;
clrscr(); clrscr();
for(i=1;i<=5;i++) Target:
{ sum=0;
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();
END
UNIT- III
Arrays and Strings
Arrays indexing, memory model, programs with array of integers, two-dimensional arrays,
Introduction to Strings.
***
ARRAYS
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 those are stored in m
successive memory locations”.
Index Values 0 1 2 3 4
K
#include<stdio.h>
#include<conio.h>
main()
{
int n,i,K[10];
clrscr();
printf("\n Enter how many elements = ");
scanf("%d",&n);
for(i = 0 ; i < n ; i++)
{
printf("\n Enter Element %d = ",i+1);
scanf("%d",&K[i]);
}
printf("\n Array Elements Are:");
for(i = 0 ; i < n ; i++)
printf(" %d",K[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};
2) While initializing elements, size may be omitted. In such cases, the compiler
allocates sufficient memory for all initialized elements.
main()
{
int K[5]={11,22,33,44,55}, i;
clrscr();
printf("\n Array Elements Are:");
for(i = 0 ; i < = 4 ; i++)
printf(" %d",K[i]);
}
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 those are stored in m x n successive memory locations”.
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.
size1specifies row size i.e., number of rows.
size2specifies column size i.e., number of columns.
0 1 2 3
K 1
#include<stdio.h>
#include<conio.h>
main()
{
int R,C,i,j,K[10][10];
clrscr();
printf("\n Enter how many rows = ");
scanf("%d",&R);
printf("\n Enter how many columns = ");
scanf("%d",&C);
printf("\n Enter Array Elements =");
for(i = 0 ; i < R ; i++)
{
for(j = 0 ; j < C ; j++)
scanf("%d",&K[i][j]);
}
printf("\n Matrix Elements Are = ");
for(i = 0 ; i < R ; i++)
{
printf("\n");
for(j = 0 ; j < C ; j++)
printf(" %d",K[i][j]);
}
}
1) Like one-dimensional arrays, double dimensional arrays can also be initialized by placing
a list of values enclosed within braces as:
2) List of values can also be initialized in the form of a matrix representation as:
3) While initializing list of values, size1 (Row Size) may be omitted. In such cases, the
compiler allocates sufficient memory for all initialized elements.
4) At the time of initializing, even one element is initialized; by default, remaining elements
are initialized with ‘0’s by the compiler.
#include<stdio.h>
#include<conio.h>
main()
{
int K[2][3] = {11,22,33,44,55,66},i,j;
clrscr();
printf("\n Array Elements Are:");
for(i = 0 ; i < 2 ; i++)
{
printf("\n");
for(j = 0 ; j < 3 ; j++)
printf(" %d",K[i][j]);
}
}
3. Multidimensional arrays
Multidimensional array uses three or more dimensions. 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 those are stored in m1xm2x-
- - - x mn successive memory locations”.
main()
{
int T,R,C,p,i,j,K[10][10][10];
clrscr();
printf("\n Enter how many Tables = ");
scanf("%d",&T);
printf("\n Enter how many rows = ");
scanf("%d",&R);
printf("\n Enter how many columns = ");
scanf("%d",&C);
printf("\n Enter Array Elements = ");
for(i = 0 ; i < T ; i++)
{
for(j = 0 ; j < R ; j++)
{
for(p = 0 ; p < C ; p++)
scanf("%d",&K[i][j][p]);
}
}
printf("\n Array Elements Are = ");
for(i = 0 ; i < T ; i++)
{
printf("\n \n");
for(j = 0 ; j < R ; j++)
{
printf("\n");
for(p = 0 ; p < C ; p++)
printf(" %d",K[i][j][p]);
}
}
}
2) List of values can also be initialized in the form of a table representation as:
3) While initializing list of values, size1 may be omitted. In such cases, the compiler
allocates sufficient memory for all initialized elements.
main()
{
int K[2][3][2]={1,2,3,4,5,6,7,8,9,10,11,12},i,j,p;
clrscr();
printf("\n Array Elements Are = \n\n\n");
for(i = 0 ; i < 2 ; i++)
{
printf("\n\n");
for(j = 0 ; j < 3 ; j++)
{
printf("\n");
for(p = 0 ; p < 2 ; p++)
printf(" %d",K[i][j][p]);
}
}
}
***
STRINGS
Note: Main problem with the scanf() function is that it terminates its input on the occurrence
of first white space.
#include<stdio.h>
#include<conio.h>
main()
{
char city[10];
clrscr();
printf("\n Enter City Name =");
scanf("%s",city);
printf("\n RESULT = %s",city);
}
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>
main()
{
char str[50];
clrscr();
printf("\n Enter a line of text =");
gets(str);
printf("\n RESULT =");
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 K;
clrscr();
printf("\n Enter a string = ");
gets(str);
K = strlen(str);
printf("\n STRING LENGTH = %d",K);
}
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.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\n Enter string 1 = ");
gets(str1);
strcpy(str2,str1);
printf("\n Result String = %s”,str2);
}
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();
Function is used to compare the given two strings without case consideration.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\n Enter string 1 = ");
gets(str1);
printf("\n Enter string 2 = ");
gets(str2);
if((strcmpi(str1,str2)) = = 0)
printf("\n BOTH STRIGNS ARE SAME");
else
printf("\n BOTH STRINGS ARE DIFFERENT");
}
Syntax: strrev(string);
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[10];
clrscr();
printf("\n Enter 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("\n Enter a String in Upper Case = ");
gets(str);
strlwr(str);
printf("\n Result String in Lower Case =");
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("\n Enter a String in Lower Case = ");
gets(str);
strupr(str);
printf("\n Result String in Upper Case =");
puts(str);
}
/* EXAMPLE PROGRAM */
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\n Enter string 1 = ");
gets(str1);
printf("\n Enter string 2 = ");
gets(str2);
strncat(str1,str2,3);
printf("\n Result string = %s”,str1);
}
/* EXAMPLE PROGRAM */
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\n Enter string 1= ");
gets(str1);
strncpy(str2,str1,3);
str2[3] = '\0';
printf("\n Result String = %s”,str2);
}
/* EXAMPLE PROGRAM */
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\n Enter string 1 = ");
gets(str1);
printf("\n Enter string 2 = ");
gets(str2);
if((strncmp(str1,str2,3)) = = 0)
printf(“\n Both Are Same”);
else
printf(“\n Both Are Different”);
}
/* 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”);
}
INITIALIZATION OF STRINGS
Here, collection of characters is placed within double quotation marks and termed as a
string constant.
Example : char str[50] = “Language in 1972”;
main()
{
char str[50] = "Language in 1972";
clrscr();
printf("\n Result 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.
StringName is name of the string that follows same rules as valid identifier.
Size1 represents maximum number of strings and size2 represents maximum number
of characters in each string.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char x[15][15];
int i,j,n;
clrscr();
#include<stdio.h>
#include<conio.h>
main( )
{
char x[3][10]={ “India” , “Pakistan” , “Srilanka”};
clrscr();
printf(“\n List of Strings Are =\n”);
for(i=0;i<3;i++)
puts(x[i]);
}
3. 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()
{
char x[10] = "2009";
int k;
clrscr();
k = atoi(x)+6;
printf("\n RESULT VALUE = %d",k);
}
2. 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";
long int k;
clrscr();
k = atol(x)+6;
printf("\n RESULT VALUE = %ld",k);
}
3. 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";
float k;
clrscr();
k = atof(x)+6;
printf("\n RESULT VALUE = %f",k);
}
4. itoa() function: itoa() function converts an integer value into a string. The
general format of the itoa() function is:
#include<stdlib.h>
main()
{
char x[10];
int k = 49;
clrscr();
printf("\n Octal Format = ");
itoa(k,x,8);
puts(x);
printf("\n Hexadecimal Format = ");
itoa(k,x,16);
puts(x);
}
5. ltoa() function: ltoa() function converts a long integer value into a string. The
general format of the ltoa() function is:
Syntax: char * ltoa(long int , char[] , int);
Where,
First argument is a long integer value used for conversion.
Second argument is a string used to store the conversion value.
Third argument is an integer value that represents format of conversion such as
decimal, octal and hexa-decimal format.
#include<stdlib.h>>
main()
{
char x[10]; long int k=49;
printf("\n Hexadecimal Format = ");
ltoa(k,x,16);
puts(x);
}
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:
Syntax : int rand();
Function returns a pseudorandom integer value between 0 and 32,767.
UNIT- IV
Pointers & User Defined Data types
Pointers, dereferencing and address operators, pointer and address arithmetic, array
manipulation using pointers, User-defined data types-Structures and Unions.
***
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("\n Address of x = %u",&x);
x = 10; 65524
printf("\n Value 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.
Initializing Pointers: Once a pointer variable has been declared, it can be initialized
using an assignment operator as:
Here, address of the variable x is stored in ptr. With this, a link is formed from
pointer variable to ordinary variable.
65592 65594
10 65592
x ptr
A pointer variable can also be initialized at the time of its declaration itself.
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("\n Address of x is = %u",&x);
printf("\n Address of ptr is = %u",&ptr);
x = 10;
printf("\n x value using x = %d",x);
ptr = &x;
printf("\n Value in p = %u",ptr);
printf("\n x value using ptr = %d",*ptr);
}
/* Program to demonstrates every pointer variable occupies same (2 bytes) amount of memory
space */
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(q));
printf(“\n Memory Size of Float Pointer Variable = %d Bytes”,sizeof(r));
printf(“\n Memory Size of Double Pointer Variable = %d Bytes”,sizeof(s));
}
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(“\n Enter Two Values =”);
scanf(“%d%d’,&x,&y);
printf("\n Before Passing to the Function Values Are = %d \t %d",x,y);
change(x,y);
printf("\n After Passing to the Function Values Are = %d \t %d",x,y);
}
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>
main()
{
int x,y;
clrscr();
printf(“\nEnter Two Values =”);
scanf(“%d%d’,&x,&y);
printf("\n Before Passing to the Function Values Are = %d \t %d",x,y);
change(&x , &y);
printf("\n After Passing to the Function Values Are = %d \t %d",x,y);}
}
Valid Operations:
p1 < p2 , p1 > p2, p1 <= p2, p1 >= p2, p1 == p2, p1 != p2 are valid operations.
Invalid Operations:
#include<stdio.h>
main()
{
int *p1,*p2,x,y;
clrscr();
p1 = &x;
p2 = &y;
x = p2 - p1;
printf("\n x value = %d",x); /* 1 */
p1 = p1 + 2;
printf("\n p1 value = %u",p1); /* 65526 */
p2 = p2 - 1;
printf("\n p2 value = %u",p2); /* 65522 */
}
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:
ptr = &X;
ptr = &Y;
For accessing value of the variable with the pointer variable, type casting must be
placed to refer the specific data item.
#include<stdio.h>
#include<conio.h>
main()
{
int x = 10;
double y = 3.45678;
void *ptr;
clrscr();
ptr=&x;
printf("\n Value 1 =%d",*(int *)ptr);
ptr=&y;
printf("\n Value 2 =%lf",*(double *)ptr);
}
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. 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.
main()
{
int *p;
clrscr();
p = NULL;
printf("\n Value = %d",*p);
}
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
K 10 20 30 40 50 Element Values
Base Address
Here,
K = &K[0] = &K all are referred to the address location 1000. Hence, in C
language array name itself acts a pointer (Address constant).
Note: A slight difference between a pointer variable and array name is, pointer is a
variable that can appear on the left side of an assignment operator, whereas the array name
acts as an address constant and cannot be appear on the left side of the assignment operator.
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.
#include<stdio.h>
#include<conio.h>
main()
{
int x[10],i,n,*p;
clrscr();
p = x;
printf("\n Enter how many numbers = ");
scanf("%d",&n);
printf("\n Enter %d Numbers = ",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\n Array Elements Are = ");
for(i=0;i<n;i++)
printf(" %d",*(p+i));
}
/* PROGRAM TO READ A DOUBLE DIMENSIONAL ARRAY AND PRINT IT USING POINTERS */
#include<stdio.h>
#include<conio.h>
main()
{
int x[10][10],i,j,m,n,(*p)[10];
clrscr();
printf("\n Enter how many Rows = ");
scanf("%d",&m);
printf("\n Enter how many Columns = ");
scanf("%d",&n);
p = x;
printf("\n Enter Array Elements = ");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",*(p+i)+j);
}
printf("\n Array Elements Are = ");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf(" %d",*(*(p+i)+j));
}
}
ARRAY OF POINTERS
Array of pointers are used to define more than one pointer variable that can points to
same data type variables. The general format of declaring array of pointers is:
Where,
Datatype specifies type of the data that can be pointed by each pointer variable.
Ptrvariable is name of the pointer variable that follows same rules as a valid identifier.
Size represents maximum number of elements.
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("\n Elements Are = ");
for(i=0;i<3;i++)
printf(" %d",*p[i]);
}
A string is an array of characters that terminated with a null character ‘\0’. String
means a character array itself; name of the string refers to base address of the array. Hence,
string address can be stored in pointer variable so that string contents can also be accessed
with the pointer variable.
main()
{
char str[50]="KAVALI",*p;
int i;
clrscr();
p = str;
printf("\n Result string with STR = %s”,str);
printf(“\n Result string with P =%s”,p);
}
Note: A string constant is like an array name by itself, it is treated by the compiler as
a pointer. Here, base address of the location can also be stored in the pointer variable.
/* EXAMPLE PROGRAM */
#include<stdio.h>
#include<conio.h>
main()
{
char s[50]="KAVALI",*p="NELLORE";
int i;
clrscr();
printf("\nResult 1:");
puts(s);
printf("\nResult 2:");
puts(p);
}
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:
/* 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("\n Enter How Many Values = ");
scanf("%d",&n);
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.
#include<stdio.h>
#include<conio.h>
main()
{
int x[10],i,n;
clrscr();
printf("\n Enter How Many Values = ");
scanf("%d",&n);
printf("\n Enter %d Elements = ",n);
for(i=0;i<n;i++)
scanf("%d",&x[i]);
printf("\n Before Passing To Function Array Values Are = \n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
sort(x,n);
printf("\n After Passing To Function Array Values Are = \n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
}
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("\n Before Sorting Elements Are = ");
for(i=0;i<5;i++)
printf(" %d",x[i]);
k = sort(x,5);
printf("\n After Sorting Elements Are = ");
for(i=0;i<5;i++)
printf(" %d",*(k+i));
}
A pointer variable that holds address of another pointer variable is known as pointer-
to-pointer. For this, add an asterisk symbol for each level of reference.
Here,
x is an ordinary variable that holds an ordinary value.
p is a pointer variable that holds address of an ordinary variable.
q is a pointer-to-pointer variable that holds address of a pointer variable.
x p q
10 65300 65302
#include<stdio.h>
#include<conio.h>
main()
{
int x = 10,*p,**q;
clrscr();
p = &x;
q = &p;
printf(“\n Value with x is = %d”,x);
printf("\n Value with p is = %d",*p);
printf("\n Value with q is = %d",**q);
}
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.
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.
1. malloc() function: malloc() function is used to allocate memory for the variables
at run time. The general form of malloc() function is:
Here, 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 variable. By
default memory location is filled with garbage values. For this, memory allocation will be:
P Garbage Values
10 BYTES
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
main()
{
int *p,i,n;
clrscr();
printf("\n Enter how many numbers = ");
scanf("%d",&n);
p = (int*)malloc(n*sizeof(int));
printf("\n Enter %d Elements = ",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\n Array 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.
Here, calloc() function allocates multiple blocks of storage space with each of same
size and by default all locations are initialized with ‘0’s. If there is not enough space to
allocate, then it returns a NULL pointer.
P 0 0 0 0 0
10 BYTES
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
main()
{
int *p,i,n;
clrscr();
printf("\n Enter how many numbers = ");
scanf("%d",&n);
p = (int*)calloc(n,sizeof(int));
printf("\n Enter %d Elements = ",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\n Array Elements Are = ");
for(i=0;i<n;i++)
printf(" %d",*(p+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.
Where,
ptrvariable is a pointer variable of type casttype.
Here, realloc() 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.
#include<stdio.h>
#include<alloc.h>
main()
{
int *p,i,n;
clrscr();
printf("\n Enter how many numbers = ");
scanf("%d",&n);
p = (int*)malloc(n*sizeof(int));
printf("\n Enter %d Elements = ",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
p = (int*)realloc(p,(n+2)*sizeof(int));
printf("\n Enter %d Elements = ",n+2);
for(i=0;i<n+2;i++)
scanf("%d",p+i);
printf("\n Array 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);
POINTER TO FUNCTION
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("\n Address of printf function is = %u",printf);
printf("\n Address of scanf function is = %u",scanf);
printf("\n Address of clrscr function is = %u",clrscr);
}
#include<stdio.h>
#include<conio.h>
void show();
main()
{
clrscr();
show();
printf("\n Address of the Function = %u",show);
}
void show()
{
printf("\n Function 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);
printf("\n Result = %d",z);
}
USES OF POINTERS
VARIABLE POINTER
4. For ordinary variables compiler 4. For any type pointer variables compiler
allocates memory based on their data allocates only 2 bytes of memory.
types.
Example: int x; Example: int *p;
char y; char *q;
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.
#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);
} }
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]);
}
***
PBR VITS (Autonomous) Page 117
I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER
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:
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.
a) getchar() Function:
getchar() library function is used for reading a single character from the
keyboard. The general format of getchar() function is:
Where,
VariableName is a valid identifier of char data type.
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("\n Enter A Character = ");
ch = getchar();
printf("\n Result 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:
Where,
VariableName is a valid identifier of char data type.
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("\n Enter A Character = ");
ch = getch();
printf("\n Result Character = %c",ch);
}
c) getche() Function:
getche() library function is used for reading a single character from the keyboard.
The general format of getche() function is:
Where,
VariableName is a valid identifier of char data type.
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.
main()
{
char ch;
clrscr();
printf("\n Enter A Character = ");
ch = getche();
printf("\n Result Character = %c",ch);
}
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.
putchar() library function information is available in stdio.h header file.
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
clrscr();
printf("\n Enter A Character = ");
ch = getchar();
printf("\n Result Character = ”);
putchar(ch);
}
b) 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.
putchar() library function information is available in conio.h header file.
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
clrscr();
printf("\n Enter A Character = ");
ch = getchar();
printf("\n Result 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:
Where,
The control string consists of format of data being received. It forms with the
combination of % symbol followed by the conversion character of different data
types.
scanf() function requires & operator called address operator to locate memory
location of the identifier to store values.
scanf() library function information is available in stdio.h header file.
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.
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:
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.
7 4 9 2
Example : printf(“%6d”,7492);
iv. It is possible to add zero’s at blank spaces by placing a ‘0’ before the field
width specifier.
0 0 7 4 9 2
Example : printf(“%06d”,7492);
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.
Syntax : %W.Pf
Where,
W specifies the minimum number of positions that used for displaying the
value.
P indicates the number of digits to be display after the decimal point.
While printing the value is rounded to P decimal places and printed as right
justified.
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);
L A B @ 2 0 1 5
***
STRUCTURE
Structure is a user defined data type and can be defined as “It is a collection of non-
homogeneous / heterogeneous / different data elements that can be grouped together under a
common name”.
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 :
B1 Pages :
Price :
16 Bytes
‘.’ 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>
struct Book
{
char BName[50];
int Pages;
float Price;
};
main()
{
struct Book B1;
clrscr();
printf("\n Enter Title of the Book = ");
gets(B1.BName);
printf("\n Enter Number of Pages = ");
scanf("%d",&B1.Pages);
printf("\n Enter Cost of the Book = ");
scanf("%f",&B1.Price);
printf("\n BOOK TITLE = %s",B1.BName);
printf("\n NUMBER OF PAGES = %d",B1.Pages);
printf("\n BOOK COST = %.2f RS",B1.Price);
}
Note: Structure declaration and definition can also be combined into a single statement. For
this, use the syntax as:
#include<stdio.h>
#include<conio.h>
struct Date
{
int Day,Month,Year;
}K;
main()
{
clrscr();
printf("\n Enter Current Day = ");
scanf("%d",&K.Day);
printf("\n Enter Current Month = ");
scanf("%d",&K.Month);
printf("\n Enter Current Year = ");
scanf("%d",&K.Year);
printf("\n TODAY DATE = %d / %d / %d",K.Day, K.Month ,K.Year);
}
INITIALIZATION OF 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
{
int pid;
char pname[10];
float price;
};
main()
{
struct product s1 = {111,"soap",25.00};
clrscr();
printf("\n Product Code = %d\n”,s1.pid);
printf(“\n Product Name = %s\n”,s1.pname);
printf(“\n Product 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 s1 and s2 are two structure variables of the same structure type,
and then the details of s1 are copied into s2 as:
s2 = s1;
Here,
Each individual member of s1 is copied into individual member of s2.
#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("\n Original structure is = ");
printf("\n %d \t %s \t %.2f",s1.pid,s1.pname,s1.price);
s2 = s1;
printf("\n Copied structure is = ");
printf("\n %d \t %s \t %.2f",s2.pid,s2.pname,s2.price);
}
Comparison:
Direct comparison of one structure variable with another structure variable using
relational operators is not possible.
i.e., Let s1 and s2 are two structure variables of the same structure type, and then the
comparisons like
s1>s2, s1<s2, s1<=s2, s1>=s2, s1==s2 and s1!=s2 are invalid operations.
#include<stdio.h>
#include<string.h>
struct product
{
int pid;
char pname[10];
};
main()
{
struct product s1,s2;
clrscr();
printf("\n Enter Product 1 id = ");
scanf("%d",&s1.pid);
fflush(stdin);
printf("\n Enter Product 1 Name = ");
gets(s1.pname);
printf("\n Enter Product 2 id = ");
scanf("%d",&s2.pid);
fflush(stdin);
printf("\n Enter Product 2 Name = ");
gets(s2.pname);
if((s1.pid = = s2.pid)&&((strcmp(s1.pname,s2.pname)) = = 0))
printf("\n BOTH ARE SAME PRODUCTS ");
else
printf("\n DIFFERENT PRODUCTS ");
}
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,
#include<stdio.h>
#include<conio.h>
struct student
{
char name[50],branch[10];
int sub1,sub2;
}s[100];
main()
{
int i,j,n;
clrscr();
printf("\n Enter how many students = ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fflush(stdin);
printf("\n Enter student %d Name = ",i);
gets(s[i].name);
fflush(stdin);
printf("\n Enter student %d Branch = ",i);
gets(s[i].branch);
printf("\n Enter Marks in Two Subjects = ");
scanf("%d%d",&s[i].sub1,&s[i].sub2);
}
Array of structures can be initialized at the time of its declaration by a list of values
placed within pair of braces. The general format of initializing array of structures is:
#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”, “AI”,45,78,89} };
main()
{
int i;
clrscr();
printf(“\n Students Details Are = \n”);
for(i=0;i<2;i++)
printf(“\n %s\t%s\t%d\t%d\t%d”,s[i].name,s[i].branch,s[i].sub1,s[i].sub2,s[i].sub3);
}
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("\n Enter Name of the Employee = ");
gets(st.name);
printf("\n Enter Date of Joining = ");
scanf("%d%d%d",&st.Join.d,&st.Join.m,&st.Join.y);
printf("\n Enter Salary of the Employee = ");
scanf(“%f”,&st.salary);
printf("\n EMPLOYEE NAME = %s",st.name);
printf("\n SALARY = %.2f RS",st.salary);
printf("\n JOIN DATE = %d / %d / %d",st.Join.d,st.Join.m,st.Join.y);
}
#include<stdio.h>
#include<conio.h>
struct Employee
{
char name[25];
struct Date
{
int d,m,y;
}Join;
float salary;
}st = {“Ravi Kumar”,10,6,2014,23456.25};
main()
{
clrscr();
printf("\n EMPLOYEE NAME = %s",st.name);
printf("\n SALARY = %.2f RS",st.salary);
printf("\n JOIN 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 the 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:
#include<stdio.h>
struct Account
{
int Acno;
float AcBalance;
}S = {111,35000.75}, *P;
main()
{
clrscr();
P = &S;
printf("\n ACCOUNT INFORMATION IS = ");
printf("\n %d \t %.2f Rs",P→Acno,P→AcBalance);
}
A structure can also be passed as an argument to a function in three ways. Those are:
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("\n Before Passing = ");
printf("\n %s \t %d \t %.2f",s.name,s.matches,s.avg);
change(s.matches);
printf("\n After Passing = ");
printf("\n %s \t %d \t %.2f",s.name,s.matches,s.avg);
}
void change(int K)
{
K = 421;
}
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 variable.
#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("\n Before Passing = ");
printf("\n %s \t %d \t %.2f",s.name,s.matches,s.avg);
change(s);
Then if we made any changes inside the function on structure, those changes are
recognized by outside function. So that, all changes are effected on the original structure
variable.
#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("\n Before Passing = ");
printf("\n %s \t %d \t %.2f",s.name,s.matches,s.avg);
change(&s);
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.
PBR VITS (Autonomous) Page 139
I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER
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, tag of the structure is
optional.
Complex k;
#include<stdio.h>
#include<conio.h>
typedef struct
{
float real,imag;
}Complex;
main()
{
Complex k;
clrscr();
printf("\n Enter Real Part = ");
scanf("%f",&k.real);
printf("\n Enter Imaginary Part = ");
scanf("%f",&k.imag);
printf("\n Complex Number is = %.2f + i %.2f",k.real,k.imag);
}
SELF-REFERENTIAL STRUCTURE
A structure in which, at least one member that points to same structure type is referred
to as a self-referential structure. The general format of self-referential structure is:
BIT FIELDS
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>
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);
}
Note: 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>
struct day
{
unsigned int d:5;
:1;
unsigned int m:4;
:1;
unsigned int y:5;
}val;
main()
{
val.d=16;
val.m=10;
val.y=15;
clrscr();
printf("\nCurrent Date =%u / %u / %u",val.d,val.m,val.y);
}
UNION
Union is also a user-defined data type that 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.
Memory is allocated for the union only at the time of creating union variable. The
general form of creating union variables is:
10 Bytes
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 : K . balance;
#include<stdio.h>
#include<conio.h>
union Account
{
int acno;
char actype[10];
float acbalance;
};
main()
{
union Account K;
clrscr();
printf("\n Enter Account Number = ");
scanf("%d",&K.acno);
printf("\n Account Number = %d",K.acno);
fflush(stdin);
printf("\n\n\n Enter Account Type = ");
gets(K.actype);
printf("\n Account Type = %s",K.actype);
printf("\n\n\n Enter Balance Amount = ");
scanf("%f",&K.acbalance);
printf("\n Balance Amount = %.2f RS",K.acbalance);
}
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.
3. A union may be a member of a structure and structure may by a member of union.
These concepts are referred as union of structures and structure of unions.
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:
The first argument of main() function argc is an integer argument called argument
counter, that counts number of arguments passed at the command prompt.
The second argument argv is called argument vector; which is an array of pointer to
strings. Arguments are stored in terms of strings.
The arguments passed at the command prompt are stored in argv[0], argv[1] and so
on. Here, argv[0] is reserved for to store name of the executing program.
main() function returns an integer value on successful completion.
#include<stdio.h>
#include<conio.h>
#include<string.h>
***
UNIT- V
Functions & File Handling
Introduction to Functions, Function Declaration and Definition, Function call Return Types
and Arguments, modifying parameters inside functions using pointers, arrays as parameters.
Scope and Lifetime of Variables, Basics of File Handling.
***
FUNCTIONS
A function is a self-contained program segment that carries out some specific, well-
defined task. C program consists of one or more functions. One of these functions must be
called by main() function. Program execution will always begin by carrying out the
instructions in the main() function. Additional functions will be subordinate to the main()
function.
If a program contains multiple functions, their definitions may appear in any order
and they must be independent of one another i.e., one function definition can’t be embedded
within another.
Advantages:
FUNCTION TYPES
C functions are classified into two types as Library functions and User-defined
functions.
a) Library functions: Functions those are predefined by the system compiler are
known as library functions.
For all the library functions, definitions and necessary information is available in
header files.
ctype.h header file provides several library functions used for character testing and
conversion operations. Some of the important library functions are:
1. isalnum(): Syntax: isalnum(ch)
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.
Function determines whether the given argument is digit or not. If the character is
digit, it returns a non-zero value that represents TRUE; otherwise, it returns ‘0’ that
represents FALSE.
Function determines whether the given argument is space or not. If the character is
space, it returns a non-zero value that represents TRUE; otherwise, it returns ‘0’ that
represents FALSE.
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
main()
{
char ch;
clrscr();
printf(“\n Enter A Character = “);
scanf(“%c”,&ch)
if(isalpha(ch))
printf(“\n Given Character is An Alphabet”);
else
printf(“\n Given Character is not an Alphabet”);
}
math.h header file provides several library functions used for mathematical operations.
Some of the important library functions are:
Function receives a double type argument and returns the cosine value as double.
Example:: printf(“Result = %lf”, cos(45));
Function receives a double type argument and returns the tangent value as double.
Example: printf(“Result = %lf”, tan(45));
Function receives a double type argument and returns the natural logarithm (base e)
value as double.
Example: printf(“Result = %lf”, log(10));
Function receives a double type argument and returns the logarithm (base 10) value as
double.
Example: printf(“Result = %lf”, log10(10));
Function receives a double type argument and returns the square root value as double.
Function receives two double type arguments and returns the d1 raised to the d2
power value as double.
Function receives a double type argument and returns the e to the power d value as
double.
Example: printf(“Result = %lf”, exp(4));
Function receives a double type argument and returns the value rounded up to the next
lowest integer as double.
Function receives a double type argument and returns the value rounded down to the
previous highest integer as double.
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
int x,n,i;
double Sum,Term;
clrscr();
printf("\n Enter How Many Terms = ");
scanf("%d",&n);
printf("\n Enter X Value = ");
scanf("%d",&x);
Sum = 1.0;
for(i=1;i<n;i++)
{
Term = pow(x,i);
Sum = Sum + Term;
}
printf(" Expression Result = %lf",Sum);
}
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 statement is:
Where, value1,value2, - - -, valuen 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);
Where,
arg1, arg2, --- , argn arguments are known as “formal / temporary arguments”.
List of values passed from the function call are temporarily stored in these formal
parameters.
Variables declared in the function definitions are called local variables.
After completing implementation of the function, it should return a value to the
calling function with a return statement.
#include<stdio.h>
#include<conio.h>
int Fact(int);
main()
{
int P,K;
clrscr();
printf("\n Enter a Value = ");
scanf("%d",&K);
P = Fact(K);
printf("\n Factorial Value = %d",P);
}
int Fact(int N)
{
int i , f = 1;
for(i = 1 ; i < = N ; 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 such as:
Case 1: In this case, calling function does not send any data to the called function.
Similarly, after implementation of the function, called function does not return any value to
the calling function.
Note: i) If the function does not return any value, return type must be void.
iii) Default return type of a function is int.
/* Example program for functions without arguments and without return value */
#include<stdio.h>
#include<conio.h>
void sum();
main()
{
clrscr();
sum();
}
void sum()
{
int x,y,z;
printf("\n Enter Two Values = ");
scanf("%d%d",&x,&y);
z=x+y;
printf("\n Result = %d",z);
}
Case 2: In this case, calling function send data to the called function. After
implementation of the function, called function does not return any value to the calling
function.
/* Example program for functions with arguments and without return value */
#include<stdio.h>
#include<conio.h>
void sum(int,int);
main()
{
int x,y;
clrscr();
printf("\n Enter Two Values = ");
scanf("%d%d",&x,&y);
sum(x,y);
}
void sum(int p,int q)
{
int z;
z=p+q;
printf("\n Result = %d",z);
}
Case 3: In this case, calling function does not send data to the called function. After
implementation of the function, called function returns value to the calling function.
/* Example program for functions without arguments and with return value */
#include<stdio.h>
#include<conio.h>
int sum();
main()
{
int p;
clrscr();
p = sum();
printf("\n Result = %d",p);
}
int sum()
{
int x,y,z;
printf("\n Enter 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 for functions with arguments and with return value */
#include<stdio.h>
#include<conio.h>
int sum(int,int);
main()
{
int x,y,z;
clrscr();
printf("\n Enter Two Values:");
scanf("%d%d",&x,&y);
z = sum(x,y);
printf("\n Result = %d",z);
}
The data flow between the calling and called functions can be divided into three
strategies as:
NESTED FUNCTIONS
#include<stdio.h>
#include<conio.h>
void fun1();
void fun2();
main()
{
clrscr();
printf("\n MAIN FUNCTION STARTS");
fun1();
printf("\n MAIN FUNCTION ENDS");
}
void fun1()
{
printf("\n FUNCTION 1 STARTS");
fun2();
printf("\n FUNCTION 1 ENDS");
}
void fun2()
{
printf("\n FUNCTION 2 STARTS");
printf("\n FUNCTION 2 ENDS");
}
RECURSION
A function calls itself is known as recursion and the function is called as recursive
function.
Example: main()
{
----
----
main();
----
----
}
1. Direct recursion
2. Indirect recursion
2. Indirect recursion: A function calls another function, which initiates to call of the initial
function is known as indirect recursion.
Advantages:
3. main program can consist of a series of function calls rather than countless lines of
code. It can be executed any number of times.
4. Well-defined and written functions may be reused in multiple programs.
5. Error detection and correction is an easy process in simple functions.
6. Large projects can be divided into small parts for easy processing with the help of
functions.
7. The main advantage of recursion is to reduce the length of the code.
Disadvantages:
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(“\n Enter a Value = ”);
scanf(“%d”,&K);
P = Fact(K);
printf(“\n Factorial 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 are 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();
#include<stdio.h>
#include<conio.h>
void change();
int x = 10;
main()
{
clrscr();
printf(“\n Value 1 = %d”,x);
change();
printf(“\n Value 2 = %d”,x);
}
void change()
{
x = x + 10;
printf(“\n Value 3 = %d”,x);
x = x + 10;
}
STORAGE CLASSES
Storage class deals with scope and lifetime 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 those
are used with data type in the declaration statement of a variable. Hence, the storage classes
are termed as:
Automatic Storage class
External Storage class
Static Storage class
Register 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.
main()
{
auto int x=100;
clrscr();
printf(“\n Result Value = %d”,x);
}
PBR VITS (Autonomous) Page 161
I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER
Variables declared outside the function with the keyword ‘extern’ are termed as
external variables. The general format of an external variable is:
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf(“\n Result Value = %d”,x);
}
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:
Depending on the place of declaration, static variables are classified into two types as:
Internal static variables: Variables declared inside the function with ‘static’
access specifier are known as internal static variables.
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.
main()
{
static int x=10;
clrscr();
printf(“\n Result Value = %d”,x);
}
External static variables: Variables declared outside the function with ‘static’
access specifier are known as external static variables.
These variables are available to all functions. The scope of external static variable is
only in that file and the lifetime is global.
#include<stdio.h>
main()
{
clrscr();
printf(“\n Result Value = %d”,x);
}
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.
main()
{
register int x=10;
clrscr();
printf(“\n Result Value = %d”,x);
}
SYMBOLIC CONSTANTS
Symbolic constant is a constant representation that does not change during program
execution. #define statement is used for defining symbolic constants. The general format of
defining a symbolic constant is:
Rules:
i. Symbolic names have the same form as a valid identifier.
ii. No blank space between # and define.
iii. #define statements must not end with a semicolon.
iv. Symbolic names are not declared with data types.
#include<stdio.h>
#define PI 3.14159
main()
{
double R, Area;
clrscr();
printf(“\n Enter Radius of the Circle = ”);
scanf(“%lf”,&R);
Area = PI * R * R;
printf(“\n Area of the Circle = %lf”,Area);
}
TYPE QUALIFIERS
C provides three type qualifiers const, volatile and restrict that describes nature of
the identifiers to the compiler. Here, const and volatile qualifiers can be applied to any
variables, but restrict qualifier can be applied only on pointer variables.
Constant variable
main()
{
const int K = 10;
clrscr();
printf(“\n Result = %d”,K);
}
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.
main()
{
volatile int K = 10;
clrscr();
printf(“\n Result 1= %d”,K);
K = 20;
printf(“\n Result 2= %d”,K);
}
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.
#include<stdio.h>
#include<conio.h>
#define PI 3.14159
main()
{
float R = 3.97,A;
clrscr();
A = PI * R * R;
printf(“\n AREA OF THE CIRCLE IS = %f”,A);
}
In this source program, pre-processor replaces the macro name PI with a single macro
value as 3.14159. Now, it works as:
main()
{
float R = 3.97,A;
clrscr();
A = 3.14159 * R * R;
printf(“\n AREA OF THE CIRCLE IS = %f”,A);
}
In this type of macro’s, the macroname is replaced with a single macrovalue. Hence,
such type of macro substitution is referred as simple macro substitution.
ii) Macro can also have arguments and is possible to replace for a single
statement. Such type of macro substitution is known as argument macro
substitution.
#include<stdio.h>
main()
{
float R = 3.97,A;
clrscr();
A = area (R);
printf(“\n AREA OF THE CIRCLE IS = %f”,A);
}
In this program, preprocessor replaces the macro area(x) with 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(“\n AREA OF THE CIRCLE IS = %f”,A);
}
iii) 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
except the last line while defining the macro.
/* EXAMPLE PROGRAM */
#include<stdio.h>
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
#endif Terminates the conditional command
#include<stdio.h>
#define vax 1
#define sun 0
main()
{
clrscr();
#if vax
printf(“\n TRUE ”);
#else
printf(“\n FALSE”);
#endif
}
***
STREAM
A stream is a sequence 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:
1. Console I/O Functions : Functions to receive input from keyboard and display
on monitor
3. Port I/O Functions : Functions to perform I/O operations on various ports of the
computer.
Console I/O functions always use the terminals keyboard and screen as the target
place.
Console I/O functions can further classified into two categories as formatted and un-
Formatted console I/O functions.
scanf() getch()
printf() getche()
getchar()
putch()
putchar()
gets()
puts()
These functions work on console effectively as long as the data is small. Console
representation is not suitable to manage large volume of data.
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 in terms of files.
FILES
File stream is a sequence of bytes, which is used to read and write data on files.
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:
Where,
MODE MEANING
r Open the file for reading only
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.
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/append 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("\n FILE 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:
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.
2) feof() Function:
feof() is a library function 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.
Syntax : perror(“string”);
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>
#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 Occurred:");
exit();
}
putchar(Ch);
}
fclose(f);
}
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.
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
FILE *fp1,*fp2;
clrscr();
fp1 = fopen("demo.txt","r");
if(fp1 = = NULL)
{
printf("\n FILE OPENING ERROR");
exit();
}
fp2 = fopen("exam.txt","w");
while((ch = fgetc(fp1)) != EOF)
{
fputc(ch,fp2);
}
fclose(fp2);
fclose(fp1);
}
fgets() and fputs() functions are string oriented functions that can be handled an
entire line as a string at a time.
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.
#include<stdio.h>
#include<string.h>
main()
{
char ch[50];
FILE *fp1,*fp2;
clrscr();
fp1 = fopen("check.txt","r");
if(fp1 = = NULL)
{
printf("\n FILE OPENING ERROR");
exit();
}
fp2 = fopen("ptr.txt","w");
while((fgets(ch,sizeof(ch),fp1))!=NULL)
fputs(ch,fp2);
fclose(fp2);
fclose(fp1);
}
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)
{
printf("\n FILE 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("\n EVEN NUMBERS ARE:");
f2 = fopen("even.dat","r");
while((item = getw(f2))!=EOF)
printf("%6d",item);
fclose(f2);
printf("\n ODD NUMBERS ARE:");
f3 = fopen("odd.dat","r");
while((item = getw(f3))!=EOF)
printf("%6d",item);
fclose(f3);
}
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.,
#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("\n Enter product id:");
scanf("%d",&p.id);
fflush(stdin);
printf("\n Enter product name:");
gets(p.name);
printf("\n Enter product cost:");
scanf("%f",&p.price);
fprintf(f,"%d\t%s\t%f\n",p.id,p.name,p.price);
printf("\n Do you want add another record(y/n):");
fflush(stdin);
flag = getchar();
}
fclose(f);
f = fopen("product.dat","r");
if(f = = NULL)
{
printf("\n FILE OPENING ERROR");
exit();
}
printf("\n PRODUCT 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);
}
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:
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
clrscr( );
printf("\nEnter data:");
while((ch = fgetc(stdin))!=EOF)
fputc(ch,stdout);
}
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.
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.
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.
fread() and fwrite() functions are used to read and write data in binary format. The
general formats of fread() and fwrite() functions are:
Here,
The first argument is address of the argument.
The second argument is size of the argument in bytes.
The third argument is number of arguments read or write at one time.
The final argument is the FilePointer.
#include<stdio.h>
#include<conio.h>
main()
{
int x;
float y;
char z='\n';
FILE *fp;
clrscr();
fp=fopen("Exam.txt","w");
printf("\n Enter One Integer and One Floating Number:\n");
scanf("%d%f",&x,&y);
fprintf(fp,"%d\n%f",x,y);
fclose(fp);
fp=fopen("Del.txt","wb");
fwrite(&x,sizeof(x),1,fp);
fwrite(&z,sizeof(z),1,fp);
fwrite(&y,sizeof(y),1,fp);
fclose(fp);
}
#include<stdio.h>
#include<conio.h>
typedef struct
{
int rno;
char name[25],branch[5];
}student;
main()
{
int i,n;
student s[20];
FILE *f = fopen("st.txt","wb");
clrscr( );
PBR VITS (Autonomous) Page 184
I B.TECH (R23) [ INTRODUCTION TO PROGRAMMING ] 2023-24, I SEMESTER
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.
1. Sequential File Processing: In sequential file processing, the file pointer moves
character by character without skipping data. i.e., read or write operations performed
sequentially. getc(), putc(), fgets(), fputs() etc., functions support sequential file processing.
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.
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;
char ch;
clrscr();
fp = fopen("win.dat","r");
if(fp = = NULL)
{
printf("\n File 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);
}
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:
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:
THE END
PBR VITS (Autonomous) Page 187