Pop Notes 2024
Pop Notes 2024
A computer is an electronic device that is used for information processing. It accepts data and
instructions, stores it in its memory, processes and gives the results to the user. The term compute
is derived from Latin word ‘Compute’ which means to calculate. Therefore, the computer is a
calculation machine.
The computers that we see and use in our day to day life are digital computers. They are called
so because they use numbers to represent any piece of information. Digital computers work on
the principle of programmed instructions which give the computers a purpose and instruct what
to do.
Capabilities of a computer
1] Huge data storage: A computer can store large amount of data and instructions in its memory.
2] Input and Output: A computer receives data and instructions as input and display output after
execution.
3] Processing: It processes the data entered by the user. Processing means performing the
necessary operations such as arithmetic or logical operations on the data.
Characteristics of computer
2] Accuracy: It gives accurate result for correct input data. Here accuracy means the correctness
of processed data. If the input data is erroneous, the output will not be correct.
4] Versatility: Computers are used in all fields like teaching, training, simulations, media and
entertainment etc.
5] Diligence: It does not feel tired. It can be used for hours, days or months.
1
History of development of computers
1] Abacus: This is the first recorded computer. It was invented in china and used by Greeks,
Romans and Japanese.
2] Napier’s Bones: A mathematician John Napier introduced the concept of logarithms. He used
a set of bones to perform multiplication. Each bone was carved with numbers on it. These
numbers were so carved with numbers on it. These numbers so carved that by keeping them side
by side, the product of numbers could be obtained. Hence the name Napier’s bones.
3] Slide rule: It consists of 2 scales, one of which slides over the other, It was so designed that
whenever one scale slides over the other, The alignment of one on the other gave the result of
basic arithmetic operations.
4] Pascale in: It was made up of counter wheels. This was capable of performing addition,
subtraction, multiplication and division.
5] Rotating wheel calculator: It was designed based on the principle of counter wheels.
6] Jacquard’s loom: A textile manufacturer, invented this machine to automatically control the
weaving loom.
8] Analytical Engine: Charles Babbage developed the analytical engine. This machine consisted
of five functional units such as input unit, memory unit, arithmetic unit, control unit and output
unit. The architecture of the modern digital computer resembles the analytical engine and hence
Charles Babbage is called the father of computers.
9] Mark I: It was capable of performing a sequence of arithmetic operations. The time needed to
perform multiplication and division was considerably reduced in this machine.
11] EDVAC: John Von Neumann Proposed a new concept of a large internal memory to store
instructions and data. This is known as the stored program concept. The first computer developed
on the principle of stored program concept was EDVAC. It is an acronym for Electronic Discrete
Variable Automatic computer.
12] UNIVAC- I: It is an acronym for universal automatic computer I. It was used for scientific
and commercial applications.
2
Generations of computers:
1] Non electronic generation: These are also referred to as the zero generation computers. They
were developed before the semiconductor revolution.
2] Electronic generation: Computer developed after 1946 are categorized into five generations.
Since they are mainly built with electronic circuitry, They are called the electronic generation
computers.
First generation computers: These were built with vacuum tubes. Their speed was
−3
10 sec.
Second generation computers: These were built with diodes and transistors. Their speed
was 10−6 sec.
Third generation computers: These were built with integrated circuits(IC’s). Their speed
was 10−9 sec.
Fourth generation computers: These were built with Large scale integration(LSI). Their
speed was 10−9 to 10−12 sec.
Fifth generation computers: The development of super computers was the key motivation
of the fifth generation computers. These were developed with Super Large scale
Integration(SLSI).
3
Block diagram of a computer
Input device: This is used to read data and instructions into computer. The different input
devices are keyboard, mouse, joystick, light pen etc. Keyboard is the most commonly used input
device.
System unit: This is responsible for storing and processing of data and instructions. The system
unit consists of CPU and memory devices. The term CPU stands for Central Processing
Unit(CPU). The CPU is main unit of computer system. Which performs all arithmetic and logical
operations. It is considered as brain of computer system. The data and instructions given by the
user are processed in this unit. The CPU consists of Control unit(CU) and Arithmetic and Logic
unit(ALU).
The control unit is an important unit in a computer. It controls and coordinates the activities of all
the units of a computer system. The functions of control unit are
4
The arithmetic and logic unit performs all arithmetic operations such as addition, subtraction,
multiplication division and modulus. It also performs logical operations such as AND, OR and
NOT.
Memory devices: Memory devices are used to store data and instructions given by the user. The
computer memory is measured in terms of bits, bytes and words. A bit is a binary digit, It can
store either 0 or 1. A byte is a sequence of 8 bits. A word is a combination of 2 bytes. The
computer memory is classified into:
1] CPU registers
2] Primary memory
3] Secondary memory
4] Cache memory
The CPU registers hold a limited amount of memory during execution. They are inside the CPU.
The main memory is the primary memory, Which holds data and instructions. The main memory
is a temporary memory that holds data and instructions till power supply is there. But the
secondary memory is a permanent memory, which holds data and instructions as long as user
wants. The cache memory is a high speed memory and present in between CPU and memory.
Unlike the main memory and secondary memory, the user cannot access the cache memory.
Output devices: Once the data and instructions are processed, the result can be displayed on
output devices. The monitor is the most commonly used output device. The other output devices
are printer, LCD’s, speakers and disks.
Categorization of computers
1] Principle of working
1] Analog computers
2] Digital computers
3] Hybrid computers
5
Analog computers takes input which is continuous in nature such as temperature, pressure and
voltage.
Digital computers reads input which is discrete in nature such as graphical data.
Hybrid computers are the combination of both analog and digital computers. The hybrid
computers accept both analog and digital data as input.
Due to the advancement in the technology, the size , shape, processing power and price of the
computers are changing every year. Based on these factors, computer are categorized into:
Computers for individual users: Computers for individual users are used by only person at a
time. There are 6 types of computers in the individual users category. They are
1) Desktop computers
2) Workstations
3) Notebook computers
4) Tablet PC’s
5) Handheld computers
6) Smart phones
Computers for organizations: Computers for organizations can be used by more than 1 person
at a time. Such computers are classified as
1) Network servers
2) Mainframe computers
3) Mini computers
4) Super computers
6
There are four parts in a computer system . They are,
Information processing cycle is a process that the computer follows in inputting data,
processing, outputting data and storing data. There are four steps in an information processing
cycle. They are
1) Input
2) Processing
3) Output
4) Storage
Input: Input is nothing but the data and instructions given to computer. In this phase , the
computer accepts data and instructions from the user. Input devices are used to accept and pass
the same to processing stage.
Processing: In this stage, the data and instructions given by the user are processed. The system
unit of a computer is responsible for processing. In system unit, both arithmetic and logical
operations are carried out to produce desired results.
Output: Output is nothing but the result. In this stage, the user can display the result. The results
may be in the form of text, number, audio, image etc.
Storage: The data and instructions should be stored for future use. The memory unit is
responsible for storage.
7
1. Problem definition
2. Analysis
3. Design
4. Coding
5. Running the program
6. Debugging
7. Testing
8. Documentation
Problem definition
In this step, the problem solver should understand what is the input need to be given , what is
output we get and what is operation need to be performed.
Analysis: The given problem must be analyzed before it is solved. It involves finding type of
input we need to give and also finding the type of operation we need to perform, that is whether
it is arithmetic or logical operation.
Design: It is to write the blue print of solution. Algorithms ,flowcharts and pseudo code are some
of the design techniques.
The word algorithm is named by the mathematician name “Abu Jafar Mohammed Ibn Musa Al
Khowarizmi” the last two words of name took different pronunciations over the period such as
‘Alkhowarizm’,’Algorism’ and finally it became “Algorithm”.
Characteristics of an algorithm
2]Output: It should produce at least one output, output is nothing but the result.
Algorithmic Notations
8
While writing algorithms, the following notations need to be followed.
1] Name of the algorithm: Give meaningful name for an algorithm, which specified the problem
to be solved.
4] Termination: It specifies the end of the algorithm. It generally a stop statement and it should
be the last instruction of algorithm.
Area= 3.14*r*r
Stop
Example 2: Write an algorithm to perform the basic arithmetic operations such as addition,
subtraction, multiplication and division.
Step 1: Read A, B
Sum= A + B
Difference= A – B
Product= A * B
Quotient= A/B
9
Print “ sum of A and B=”, sum
Stop
Step 1: Read l, b
Area= l*b
Stop
Example 4: Write an algorithm to calculate the simple interest and compound interest for the
amount deposited ( P ) for some years ( T ) for the rate of interest ( R ).
Read P, R, T
P∗R∗T
SI=
100
Stop
Step 1: Read A, B
If (A>B) then
else
Stop
Read A, B, C
if (A>B) go to step 4
if (B>C) then
print “ B is largest”
else
print “ C is largest”
11
Step 4: [ compare A and C]
if (A>C) then
print “ A is largest”
else
print “ C is largest”
Stop
Example 7: Write an algorithm to compute the sum of first N natural numbers and their mean.
Read N
sum=0
∑¿
Mean= n
¿
Step 5: [print contents of sum and mean]
Stop
12
Flowcharts
Rectangle processing
Arrows Connections
Example 1: Draw a flowchart to find the area of triangle when its three sides are given.
13
Example 2: Draw a flowchart to find the largest of 3 numbers
14
Example 4: Draw a flowchart to find the roots of a quadratic equation a x 2+ bx+ c=0
Read N
Step 2: [Initialization]
15
Temp =N
Step 3: [Repeat until N greater than zero and compute the reverse]
Reverse = 0
Temp =N
While ( N>=0)
Digit= N mod 10
Reverse= Reverse*10+digit
N=N/10
Stop
16
Pseudo code: A Pseudo code is neither an algorithm nor a program. It consists of English like
statements which performs specific operations. In pseudo code, the program is represented in
terms of words and phrases, but the syntax is not followed.
Easy to read
Easy to understand
Easy to modify
Read a , b
Sum = a + b
Diff= a – b
Product= a * b
Quotient= a/ b
End
Coding: The process of writing program called coding. The computer does not process
algorithm or a flow chart, but executes the program. A program is a set of instructions to solve a
problem by computer.
Running the program : The program will be executed in the CPU. This phase of problem
solving involves 3 steps.
The user writes program and store it in memory. All the instructions stored in the memory, are
read one by one by the CPU, understand it. Then it will perform specified operations. The result
of operations is stored in memory again. And also the result is displayed in output devices.
Debugging: Bug is nothing but error or mistake. The process of detecting and correcting errors
in the program is called debugging. The term debug was introduced after detecting a bug in
Mark-I, by Admiral Gracehopper. She removed the bug from the machine and wrote in a The
Mark - I was debugged today”.
Syntax error: This type of errors will occur when we don’t follow syntax while writing
programs. On encountering these errors the compiler displays an error message specifying the
line number where the error has occurred. It is easy to debug these errors. For example, the
syntax of initializing a variable in c is
Variable = expression;
Logical errors: Logical errors occur during coding process. When the programmer writes a
program, he must take care of correct operations to be performed. Even though logical errors are
there in a program, the program will get executed, but it will give unexpected results. It is very
difficult to debug such as errors, because compiler doesn’t display them. We can eliminate such
errors through execution of program by giving inputs.
Runtime errors: These errors when we execute instructions which have ambiguity. These errors
may occur due to errors in program like divide by zero or due to device errors, keypunch errors,
incorrect data input etc. The computer will print these error messages.
Testing: The process of executing the program to test the correctness of outputs is called testing.
The program is tested by executing with different sets of data. We can find logical errors using
the process.
Internal documentation
External documentation
18
External documentation: This documentation is an executable statement in a program. It
may be a message to the user to give inputs. These can be written using output statements. It
makes the program more attractive and interactive. Some examples are,
19
Introduction to Programming
Importance of C
C became very popular compared to other programming languages introduced before C like
BASIC, COBOL, FORTRAN etc. The increasing popularity of C is due to its desirable
qualitiesThey are
1) C has rich set of built in functions and operators which can be used to write any complex
program.
2) Programs written in C are efficient and fast C is many times faster than BASIC.
3) They are only 32 keywords in ANSI C.
4) C is portable language. This means that C programs written in one computer can be run
on another computer with little or no modification.
5) C language is well suited for structured programming, this requires the programmer to
think of a problem in terms of functions.
6) C has the ability to extend itself. A C program is basically a collection of functions that
are supported by C library. We can add our own functions to C library.
The documentation section consists of a set of comment time giving the name of the program the
author name and other details,
The link section provides instructions to the complier to link functions from system library
likestdio.h,stdlib.h etc
These are some variables that are used in more than one function. Such variables are called
global variables and are declared in the global declaration section.
Executing a C program
21
Constants variables and data types
Character set
The group of characters which are used to program is called characters set. The characters in C
are grouped into following categories.
Special characters
Trigraph characters:- Many non English keyboards do not support all the characters which are
mentioned above. So ANSI C introduces the concept of trigraph characters to provide a way to
use these characters in a program, which are not available in keyboard.
C tokens
The smallest units of a program are called tokens C token are categorized into six types They are
23
Keywords and identifiers
Each C word can be categorized as keyword or an identifiers. Keywords are the words which
have special meaning and which should not be changed. There are totally 32 keywords in C.
They are
Volatile while
These are user defined names and consists of letters, digits and underscore.
Constants
Constants are the values which do not change throughout execution of program. C supports
several types of constants.They are
24
Integer Constants
An integer constants is a number which consist of sequence of digits. Integers constants are into
3 types
Decimal integer constants consist of set of digits, 0 through 9. These constants may be positive
or negative. Valid example of decimal inters constants are
12 -- 125 12468—96
Embedded space, commas and special characters should not be used. For example
12 60 20,000 5$85
are invalid
An octal integer constants consists of any combination of digits from the set 0 through 7, with a
leading 0. For example
Real constants
Real constants are numbers which have fractional part. Real constants can be positive or
negative. For example
Its is possible to omit digits before decimal points or digits after decimal point for example
A real number can also be expressed as exponential (or)scientific notation. The general syntax of
scientific notation is
The mantissa is either a real number expressed in decimal notation or an integer. The exponent is
an integer number with an optional plus or minus sign. Examples are
A single character constant contains a single character enclosed within a pair of single quotes.
For example
Character constants are associated with integer values called ASCII values. For example
Print(“%c”, ‘97’)
A string constant is a sequence of characters enclosed in double quotes. The characters may be
letters,digits,special characters and so on. Examples are
The characters constant ‘x ’is not same as string constants “x” the string constants are not
associated with integer values.
C supports some special backslash character constants that are used in output functions. They are
also called escape sequences. They are
Variables
A variable is name of memory location where we can store data. A variable may take different
values at different times throughout program execution. The programmer should give meaningful
name for a variable.
Data Types
Integer
character
Signed unsigned
Char
Int unsigned int
Signed char
Short int unsigned short
int Unsigned char
Integer types
Integers are where numbers. Generally, integers occupy 2 bytes or 4 bytes to store a number,
depending on the computer . The integers can be signed or unsigned. If we declare int, by default
computer assumes it as signed integer, Where we can store both positive and negative numbers.
A signed integer uses 1 bit for sign and remaining bits to store number. If an integer takes 2
bytes, then the range of values can be stored are -32768 to 32767( that is −215 to 215 -1) for
signed integer.
28
C has 3 classes of integer storage namely short int, int and long int. Short int takes half the size
of int and long int takes double the size of memory to store number. Signed and unsigned are
called qualifiers.
Short int
int
Long int
Integer types
Float uses 4 bytes to store numbers, with 6 digits of precision. Floating numbers are numbers
which have fractional part . If the accuracy provided by float is not sufficient, the type double
can be used to store number, which uses 8 bytes giving a precision of 14 digits. If the accuracy
provided by double is not sufficient, then we can use long double. Long double takes 10 bytes to
store a number.
float
double
Long double
Character types
A single character can be defined using char data type. Char takes 1 byte of memory. The
qualifier signed or unsigned char can be explicitely applied to char. The signed chars have range
of values 0 to 255, signed chars have range of values -128 to 127.
Void types
Declaration of variables
The declaration of variables must be done before they are used in the program. The syntax for
declaring a variable is data-type v1,v2,…….vn;
int amount;
float SI,CI;
double area:
typedef is a keyword which is used to give new name to existing data type, the syntax is
type is name of existing data type, identifier is the new name given to existing data type. For ex
30
typedef float fraction;
whole_number a, b;
fraction x, y;
typedef cannot create new data type. The main advantage of typedef is that we can give
meaningful names to data types which increases the readability of program.
The another user defined data types is enumerated data type, the syntax is
The identifier is a user defined enumerated data type. enum is used to give meaningful names to
integer constants. For ex
The compiler automatically assigns integer digits beginning with 0 to all enumeration constants.
That is the enumeration constant Monday is assigned with 0, Tuesday is assigned with 1 and so
on.
Here the constant Monday is assigned with value 10. The remaining constants are assigned
values that increase successively by 1. We can also define like
then Tuesday will be assigned with 11 and Thursday will be assigned the value 26.
Day week-day=Monday;
Variables in C can have not only data types but also storage class that provides information about
lifetime of variables. In C, there are 4 storage classes. They are
1. Auto: Local variable can be used only within the function/block in which it is declared.
2. Static: These variables will retain values even after completion of function execution.
3. Extern: Variable declared I one file can be used in another file using extern storage class.
31
4. Register: Variables stored in registers.
NOTE: static and extern variables are automatically initialized to zero. Auto variables
have garbage values before initialization.
Symbolic constants
We can use constants in a program. These constants may appear in a number of places in
program. One example is 3.412, representing the mathematical constant ‘ pi’, we face
two problems in writing programs which contains constant values. They are
1] problem in modification of program
2] problem in understanding the program
Modifiablity
If we want to change value of pi from 3.14 to 3.14159 to improve accuracy, then we need
to search whole program for the usage of pi value and the we need to change the value
explicitely.
Understadibility
When a numeric value appears in a program, its use is not always clear, especially when
the same value means different things to different places. For ex, if we use 3.14 value in
our program, it may not be value of pi always. So if we give meaningful names to values,
then it increases understadibility.
We may want to declare certain variables as constants in a program. It can be done qualifier
const at the time of declaration. For ex
Const is a keyword which tells the compiler that the value of intrest_rate should not be modified
by program.
Reading a character
The simplest of all input/output operations is reading a character from the standard input unit
(keyword) ad writing it to standard output unit(monitor). The character can be read using the
function getchar( ). The general syntax of getchar( ) is
Variable_name is valid c name that has been declared as char type. For ex
Char d;
d = getchar( );
33
getchar( ) function reads a character from user ad stores it in the variable d.
writing a character
Like getchar( ), putchar( ) function is used to write character to output device. The syntax is
putchar (variable_name);
d=’a’
putchar( d);
#include<studio.h>
# include<stdlib.h>
int main( )
char d;
d = getchar( );
return 0; K
Formatted input
Formatted input refers to an input data that has been arranged in a particular format. scanf( )
function is used to read input from user. The general syntax of scanf( ) is:
scanf( “control string”, V1,V2,….Vn); The control string specifies the format in which data is to
be read and V1,V2,…..Vn specify the address of locations where data obtained be stored.
control string and variables are separated by commas.
34
Inputting Integer numbers
The % indicates a conversion specification, w is a width specified and d indicates integer data to
be read. For ex
scanf(“%d”, &a);
%2d indicates read 2 digits integer number, %4d indicates read 4 digits integer number. Store
first number in address of a and second number in address of b.
An input field may be skipped by specifying * in the place of field width. For ex
If the input given is 123 456 789 .Then it will assign 7 it will assign 123 to a, 456 will be skipped
and it will assign 789 to b.
By default, space is used as separated between two inputs. If we want to change default
separator, then we can specify it in control string like
The data type character d may be replaced by l to read long integers and h to read short integers.
{ output
int a, b , c ,d;
35
printf(“ enter 2 numbers”); enter 2 numbers
return 0;
The control string used to read float umbers is %f. For ex,
If the number needs to be read in scientific rotation, then control string can be used is %e like
scanf(“%e”, &a);
If the number to be read is of double type, then the specification should be %lf instead of %f.
scanf(“%c”, &d);
int main( )
char name[10];
36
printf(“name=%s”, name); vinay
By using %S we cannot read multiple words, because %S consider space as end of input. For
that we can write
scanf(“[a-z]”, name);
It indicates that read the input which contains any character between a to z and space.
scanf(“[^$,+]”,name);
If we use ‘^ ‘symbol, it indicates, accept input which should not contain any character which are
specified in square brackets.
Code Meaning
%c Reads a single character
%d Reads a decimal integer
%e Reads float value in scientific rotation
%f Reads a floating point value
%h Reads a short integer
%o Reads an octal integer
%s Reads a string
%u Reads an unsigned decimal integer
%x Reads a hexadecimal integer
%[. .] Reads a string of words
Formatted output
It is desirable that the outputs are produced in such a way that they are understandable and are in
an easy to use form. printf( ) function is used to print output on monitor. The general syntax of
printf ( ) is
The control string indicates how many to be printed and what are its types. The variables
V1,V2…Vn are printed according to specification of control string. The variables should match
in number, type and order with format specifications.
Format output
printf(“%d”, 1286); 1 2 8 6
printf(“%6d”, 1286); 1 2 8 6
printf(“%2d”, 1286); 1 2 8 6
printf(“%06d”, 1286); 0 0 1 2 8 6
printf(“%-6d”, 1286); 1 2 8 6
If the width specifier is less than number of digits of a number, the complete number will be
printed. To force left justification, we can use ‘-‘ sign. The digit (or) character before width
specifier is called fill character and is used to fill empty spaces.
The integer w indicates the minimum number of positions that are to be used for the display of
value and the integer p indicates the number of digits to be printed after decimal point.
Format output
Printf(“%f”, 57.7864); 5 7 . 7 8 6 4
5 7 . 7 8 6 4 Printf(“%7.4f”, 57.7864);
The subprogram section contains all user defined functions. All sections, expect the main
function section and link section may be absent when they are not required.
Programming style
38
unlike some other programming languages( COBOL, FORTRAN etc) C is a free form language.
That is the C compiler does not care, where on the line we begin typing.
We must develop the habit of writing programs in lower case letters. C program statements are to
be written in lowercase letters.
Since C is a free form language, we can group statements on one line. For example
A = b;
X = y + 1;
A = b; x = y + 1;
Main()
Printf(“hello”);
main( ) { Printf(“hello”);}
however, this style make the program more difficult to understand and should not be used.
39
UNIT 2
1. if statement
2. switch statement
3. conditional operator statement
4. goto statement
these statements are popularly known as decision making statements. Since these statements
control the flow of execution, they are also known as control statements.
The if statement is basically a two way decision statement. The if statement may be implemented
in different forms. They are
1. simple if statement
2. if else statement
3. nested if else statement
4. else if ladder
Simple if statement
if (condition)
{
Statement- block;
}
Statement-x;
The statement-block may be single statement or group of statements. If the test expression or
condition is true, then the statements-block will be executed. If the condition is false, then
statement-block will be skipped. When the condition is true, both statement- block and
statement-x will be executed.
40
condition
false
true
Statement-block
Statement-x
if (condition)
{
true block statements;
}
else
{
false block statements;
}
Statement-x;
If the condition is true, then the true block statements will get executed. If the condition
evaluates to false, then the false block statements will get executes. In either case, either true
block statements or false block statements will get executed but not both. But in both the cases,
statements-x will get executed.
41
Nested of if else statements
When more conditions need to be evaluated, then we can use nested if else statement. The if
else statement written inside another if is called nested if statement. There is no limit on
number of levels of nesting. The general syntax of nesting of nesting of if else statement is
if (condition)
{
if (condition 2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
Statement-x;
If condition1 evaluates to true, then it will evaluate condition2. If condition2 evaluates to true,
then statements 1 will get executed. If condition2 evaluates to false, then statements 2 will get
executed.
If condition1 evaluates to false, then statements 3 will get executed. In all cases, statements-x
will get executed.
42
The else if ladder
The other way to evaluate multiple conditions is else if ladder. The general syntax of else if
ladder is
if (condition 1)
{
Statement-1;
}
else if (condition 2)
{
Statement-2;
}
else if (condition 3)
{
Statement-3;
}
else
{
Statement-4;
43
}Statement-x;
If condition1 evaluates to true, then statements 1 will get executed. If condition2 evaluates to
true, then statements 2 will get executed. If condition3 evaluates to true, then statements3 will
get executed.
If condition1 evaluates to false, then condition2 will get evaluated. If condition2 evaluates to
false, then condition3 will get evaluated. If condition3 evaluates to false, then statement 4 will
get executed. In all cases, statement-x will get executed.
Switch statement
In a program, one output of many alternatives need to be selected, then we can use else if
ladder. But the complexity of such a program increases when the number of alternatives
increases. Fortunately, C has built in multi way decision statement known as a switch.
The switch statement tests the value of given variable (or expression) against a list of case values
and when a match is found, a block of statements associated with that case is executed.
The general syntax of switch statement is
Switch (expression)
{
Case value-1:
block-1
44
break;
Case value-2:
block-2
break;
……………..
……………..
default:
default-block
break;
Statement-x;
The expression is an integer expression or characters. Value-1, value-2 are constants or constant
expressions and are known as case labels. Each of these values should be unique within a switch
statement. block 1, block 2 etc are statement lists and may contain zero or more statements.
There is no need to put braces around these blocks. Note that case labels end with a colon(:).
When a switch is executed, the value of the expression is successfully compared against the
values value1, value 2 etc. If a case is fund whose value matches with the value of the
expression, then the block of statements that follow the case are executed.
The break statement at the end of each block signals the end of a particular case and causes an
exit from the switch statement, transferring the control to the statement-x following the switch
The default is an optional case. When present, it will be executed if the value of the expression
does not match with any of the case values. If not present, no action takes place if all matches
fail and the control goes to the statement-x.
45
The ?: operator
C has an operator for two way selection. This operator is a combination of ? and : and takes 3
operands. The operator is popularly known as conditional operator. The general syntax of
conditional operator is
The conditional expression is evaluated first, if the result is true, then it executes statements1. If
the result of expression is false, then it executes statement 2. For ex
int y = ( x>0) ? 1 : 0;
If value of x is greater than 0, then 1 will be assigned to y. If value of x is not greater than 0,
then 0 will get assigned to y.
The conditional operator may be nested for evaluating more complex assignment decisions. For
ex
46
C supports the goto statement to branch from one point to another in the program. The goto
requires a label in order to identify the place where the branch is to be made. A label is any valid
variable name and must be followed by a colon. The label is placed immediately before the
statement where the control is to transferred. The general syntax of goto and label statements are
The label: can be anywhere in the program either before or after the goto label; statement.
During program execution, when a statement like
goto begin;
is met, the flow of control will jump to the statement immediately following the label begin:.
This happens unconditionally.
Note that a goto breaks the normal sequential execution of the program. If the label: is before the
statement goto label; a loop will be formed and some statements will be executed repeatedly.
Such a jump is known as a backward jump. If the label; is placed after the goto label; some
statements will be skipped and the jump is known as forward jump.
Goto statement can also be used to transfer the control out of a loop where certain peculiar
conditions are encountered.
One of the classic problems encountered when we start using nested if else statements is the
dangling else. This occurs when a matching else is not available for an if. The solution to this
problem is, always match an else to the most recent unmatched if in the current block. In some
cases , it is possible that the false condition is not required. In such situations else statement may
be committed.
If the set of instructions are executed repeatedly then we call it as looping. In looping, a sequence
of statements are executed until some conditions for termination of the loop are satisfied. A
program loop therefore consists of two segments, one known as the body of the loop and the
47
other known as the control statement. The control statement tests certain conditions and then
directs the repeated execution of the statements contained in the body of the loop.
Depending on the position of the control statement in the loop, the loop can be classified as entry
controlled loop and exit controlled loop. In the entry controlled loop, the condition is tested,
before executing loop statements. If the condition evaluates to false, then loop statements will
not be executed. In exit controlled loop, the condition is tested at the end of the loop and the loop
statements are executed unconditionally for the first time. The entry controlled and exit
controlled loops are known as pre test and post test loops respectively.
The test conditions should be carefully stated in order to perform the desired number of loop
executions. When the condition evaluates to false, the control comes out of the loop. In case, it
does not do so, the control sets up an infinite loop and the body is executed over and over again.
The test may be either to determine whether the loop has been repeated the specified number of
times or to determine whether a particular condition has been met.
48
The C language provides three constructs for performing loop operations. They are
Sentinel loops
Based on the nature of control variable and the kind of value assigned to it for testing the control
expression, the loops can be classified into 2 categories.
When we know in advance exactly how many times the loop will be executed, we can counter
controlled loop. We use a control variable known as counter. The counter must be initialized,
tested and updated properly for the desired loop operations. The number of times we want to
execute the loop may be a constant or a variable that is assigned a value. A counter controlled
loop is sometimes called definite repetition loop.
In a sentinel controlled loop, a special value called a sentinel value is used to change the loop
control expression from true to false. For example, when reading data we may indicate the “end
of data” by a value , like -1 to 999. The control variable is called sentinel variable. A sentinel
controlled loop is often called indefinite repetition loop because the number of repetitions is not
known before the loop begins executing.
While(condition)
{
Body of the loop
}
The while is an entry controlled loop statement. The test condition is evaluated and if the
condition is true, then the body of the loop is executed. After execution of the body the test
condition is once again evaluated and if it is true, the body is executed once again. The process
of repeated execution of the body continues until the test condition finally becomes false and the
control is transferred out of the loop. On exit, the program continues with the statement
immediately after the body of the loop.
The body of the loop may have one or more statements. The braces are needed only if the body
contains two or more statements.
The do statement
49
It is an exit controlled loop. It might be necessary to execute the body of the loop before the test
is performed. Such situations can be handled with the help of the do statement. The general
syntax is
do
{
body of the loop
}
While( condition);
On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the
end of the loop, the test condition in the while statement is evaluated. If the condition is true, the
program continues to evaluate the body of the loop once again. This process continues as long as
the condition is true. When the condition becomes false, the loop will be terminated and he
control goes to the statement that appears immediately after the while statement.
The for loop in C has several capabilities that are not found in other loop constructs. For example
more than one variable can be initialized at a time in the for statement. That is
The initialization section has two parts i=0, p=1 separated by comma.
50
Like the initialization section, the increment section may also have more than 1 part. For
example
The third feature is that the test condition may have any compound relation and the testing need
not be limited only to the loop control variable. For example
The loop uses compound test condition with the counter variable i and sentinel variable sum.
Another unique aspect of for loop is that one or more sections can be omitted if necessary. For
example
m =5;
for(; m!=100)
{
m=m+2;
}
Both the initialization and increment sections are omitted in the above for statement. The
initialization has been done before the for statement and the control variable is incremented
inside the for loop. In such cases, the sections are left blank. However, the semicolons separating
the sections must present. If a test condition is not present, the for statement sets up an infinite
loop. Such loops can be broken using break or goto statements in the loop.
We can set up time delay loops using null statements as follows.
for(j=1000; j>0; j=j-1)
;
This loop is executed 1000 times without producing any output, it simply causes a time delay.
Notice that the body of the loop contains only a semicolon, known as a null statement. This can
be written as
for(j=1000; j>0; j=j-1);
Nesting of for loops
Nesting of loops, that is one for statement within another for statement is allowed in C. for
example
for(i=0;i<10;i++) outer loop
{
51
for (k=0;k<10;k++) inner loop
{
}
}
The nesting may continue up to any desired level.
Jumps in loops
Loops performs a set of operations repeatedly until the control variable fails to satisfy the test
condition. The number of times a loop is replaced is decided in advance and the test condition is
written to achieve this. Sometimes, when executing a loop it becomes desirable to skip a part of
the loop or to leave the loop as soon as a certain condition occurs. For example, consider the case
of searching for a particular name in a list containing say 100 names. A program loop written for
reading and testing the names 100 times must be terminated as soon as the desired name is
found. C permits a jump from one statement to another within a loop as well as jump out of a
loop.
An early exit from a loop can be accomplished by using break statement or goto statement. When
a break statement is encountered inside a loop, the loop is immediately exited and the program
continues with the statement immediately following the loop. When the loops are nested, the
break would only exit from the loop containing it. That is the break will exit only a single loop.
Since a goto statement can transfer the control to any place in a program, it is useful to provide
branching with in a loop. Another important use of goto is to exit from deeply nested loops when
an error occurs. A simple break statement would not work here.
1. while(….)
{
if ( condition)
break;
}
2. do
{
…..
…….
if( condition)
break;
…….
…….
while(….);
52
3. for(….)
{
……..
if (error)
break;
….
}
4. for (….)
{
…….
for (….)
{
….
if( condition)
break;
…….
}
5. while(….)
{
if (error)
goto stop;
….
if( condition)
goto abc;
….
….
abc:
……
}
Stop:
…..
….
6. for (….)
{
…….
for (….)
{
….
if (error)
goto error;
53
….
}
…..
}
error;
….
….
Skipping a part of a loop
During the loop operations, it may be necessary to skip a part of the body of the loop under
certain conditions. For example, in processing of applications for same job, we may like to
exclude the processing of data of application belonging to a certain category. On reading the
category code of an applicant, a test is made to see whether his application should be considered
or not. If it is to be considered, the part of the program loop that processes the application details
is skipped and the execution continues with the next loop operation.
Like the break statement, c supports another similar statement called the continue statement.
However unlike the break which causes the loop to be terminated, the continue, as the name
implies, causes the loop to be continued with the next iteration after skipping any statements in
between. The continue statement tells the complier, “skip the following statements and continue
with the next iteration” . the syntax of continue is continue,
continue;
54
3. for(initialization; condition; increment)
{
…….
if(….)
continue;
…..
….
}
Avoiding goto
It is a good practice to avoid using goto. There are many reasons for this. When goto is used,
many compliers generate a less efficient code. In addition, using many of them makes a program
logic complicated and renders the program unreadable.
We can jump out of a program by using the library function exit (). In case, due to same reason,
we may wish to break out of a program and return to the operating system, we can use exit ()
function. For example
if (condition)
exit(0);
The exit( ) function take an integer value as its argument. Normally Zero is used to indicate
normal termination and a non zero value to indicate termination due to same error or abnormal
condition. The use of exit( ) function requires the inclusion of the header file <stdlib.h>
55
Unit 3
ARRAYS
In a program, if we want to handle large amount of data, for example, we may
need to store marks of 60 students, then we can use derived data type known as array.
An array is a fixed size, sequenced collection of elements of same data type.
Arrays will avoid declaration of multiple variables to store large amount of data. So,
array makes the program smaller and efficient.
One dimensional arrays:
A list of items can be given one variable name by specifying a size and such a
variable is called single subscripted variable or a one dimensional array.
Declaration of one dimensional array:
Like any other variable, arrays must be declared before they are used so that
compiler can allocate memory for them. The general syntax of array declaration is,
type variable_name[size];
The type specifies the type of data that can be stored in an array such as int,
float, char etc. The size indicates the maximum number of data that can be stored in
an array. For example,
float height[50];
declares height to be an array can contain maximum of 50 real values.
Every value in an array can be called as element. Every element in an array is
referred by a number called index. Always index of array starts with O.
That is always the first element of the array have the index value 0 and last
element of the array have the index value size-1.
Similarly,
Int marks[10];
declares marks as an array to contain a maximum of 10 integer values.
If we try to store more number of elements than size of array would not
necessarily cause an error. Rather it might result in unpredictable program results. The
size should always be a integer value.
char name[10];
declares name as character array that can hold maximum of 9 characters. When the
compiler sees character array, it terminates it with a null character (10). So while
declaring character arrays. We must allow one extra element space for null character.
Initialization of one dimensional arrays:
After an array is declared, it must be initialized, otherwise it will contain
garbage values. An array can be initialized at either of the following stages.
a) at compile time
b) at run time
Compile time initialization:
We can initialize the elements of the array in the same way as ordinary
variables when they are declared. The general syntax of initialization of array is,
type array_name[size]={list of values};
The values in the list are sperated by commas. For example,
int arr[3]={0, 0, 0} arr
0 0 0
0 1 2
Will declare the variable arr as array of size 3 and will assign 0 to each memory
location. If the number of values in the list are less than the size, they only that many
values will be initialized. The remaining memory locations will be initialized to zero
automatically. For example,
int a[5]={3, 4} a
3 4 0 0 0
0 1 2 3 4
will initialize first two memory locations to 3 and 4, remaining
3 memory locations will be initialized to 0. If we initialize array at compile time, then
it is not mandatory to mention size of array. For example,
int x[ ]={2, 3, 9, 10}
will declare x as array with size 4. The compiler will find size of array by looking at
number of values. Character arrays may be initialized in a similar manner. For
example,
char s[4]= “4i”; s
4 I \0 \0
0 1 2 3
will declare s as array with size 4. First two memory locations
will be initialized to 4 and I, remaining memory locations will be initialized to null
character.
The character array can also be initialized as,
char s[4]={„4‟, „I‟}
Similarly,
char s1[ ]= “Hello”;
will declare s1 as array with size 6, where last memory location will be initialized to
null character.
If we initialize more values than the specified size, the compiler will produce an error.
For example,
int a[3]={2, 5, 9, 10}
will produce error.
Run time initialization:
An array can be explicitly initialized at run time. This approach is usually
applied for initializing large arrays. For example,
float sum [100];
for (i=0; i100; i++)
{
If(i50)
sum[i]=0.0;
else
sum[i]=1.0;
The first 50 elements of array sum will be initialized to zero and remaining 50
elements will be initialized to 1.0 at run time (execution time).
We can also use scanf function to initialize an array. For example,
int a [3];
10 20 30
10 11 12
40 50 60
20 21 22
70 80 90
Will be stored in memory as,
row 0 row 1 row 2
10 20 30 40 50 60 70 80 90
00 01 02 10 11 12 20 21 22
Like numeric arrays, character arrays may be initialized when they are
declared. C permits a character array to be initialized in either of the following two
forms.
Char city[9]= “New York”;
Char city[9]={„N‟, „e‟, „w‟, „ ‟, „Y‟, „o‟, „r‟, „k‟};
The reason that the size of city has to be 9 is that the sting New York contains
8 characters and one last memory location is for null character.
C also allows us to initialize a character array without specifying the number
of elements. In such cases, the size of the array will be determined automatically,
based on the number of elements initialized. For example,
Char s[ ]={„G‟, „O‟, „O‟, „D‟};
defines the array s with size 5.
We can also declare the size much larger than the number of characters. That
is,
Char s[10]= “Good”;
is allowed. In this case, the computer creates a character and of size 10, places the
value “Good”, in it, terminates it with the null character, and initializes all other
elements to NULL. That is,
S
G o o d \0 \0 \0 \0 \0 \0
0 2 2 3 4 5 6 7 8 9
garbage values
The remaining memory locations will be filled with garbage values.
If we want to read entire input New York, then we need two character arrays
of appropriate sizes. That is,
Char adr1[5], adr2[5];
Scanf(“%s%s”, adr1, adr2);
Will assign string New to adr1 and York to adr2.
We can also specify the field width in the scanf statement for reading a
specified number of characters from the input string. That is,
Scanf(“%ws”, array_name);
If the width w is equal to or greater than the number of characters in input,
then entire string will be read and stored to array variable.
If the width is less than the number of characters in the string, the excess
characters will not be read.
Consider the following statements,
Char name [10];
Scanf (“%s”, name)
If we give input as RAM, then it is stored as,
R A M \0
0 1 2 3 4 5 6 7 8 9
garbage values
If we give input as college, then it will read only 5 characters.
c o l l e \0
0 1 2 3 4 5 6 7 8 9
garbage values
Reading a line of text:
The scanf( ) function with %s or %ws can read only strings without white
spaces. That is, they cannot be used for reading a text containing more than one word.
However, C supports a format specification known as edit set conversion code %[..]
that can be used to read a line containing a variety of characters including
whitespaces. For example,
Char line [80];
Scanf (“%[ \n]”, line);
Printf(“%s”, line);
Will read a line of input from keyboard and display the same on the output.
Using getchar and gets functions:
Getchar( ) function can be used to read single character from keyboard. The
syntax to use getchar function is,
Char ch;
Ch=getchar ( );
Note that getchar( ) function has no parameters. The getchar and gets function are
defined in header file.
Stdio.h
We can use getchar function repeatedly to rad successive single character form input
and store it into a character array. Thus, the entire line of text can be read and stored
in an array. The reading is terminated when the new line character(\n) is entered.
Another more convenient method of reading a string of text containing
whitespaces is to use the library function gets. Gets does not stop reading when it
finds space. The syntax to use gets function is,
Char name[20];
Gets (name);
Printf(“%s”, name)‟
After reading string, gets will append null character at the end.
The above statements can also be written as,
Char name[20];
Printf(“%s”, gets(name));
Writing strings to screen:
Using printf function:
The printf() function can be used to print strings to the outpur screen. The
format specifier %s can be used to display an array of characters that is terminated by
the null character. For example,
printf(“%s”, name);
Can be used to display the entire contents of the array name. We can also use width
specifier with %s. for example,
%10.4s
Indicates first four characters are to be printed in a field width of 10. If we use minus
sign, then printing will start from left side.
printf(“%s”, “united states”); u n i t e d s t a t e s
printf(“%10.4s”, “united u n i t
states”);
printf(“%10.0s”, “united
states”);
printf(“%-10.4s”, “united u n i t
states”);
The another nice feature which allows variable field width or precision is,
Printf(“%*.*s”, w, d, array_name);
Prints the first d characters of array in the width w. For example,
Printf(“%*.*s”, 10, 4, “Hello world”);
Will print
H e l l
printf(“%10s”, “united u n i t e d s t a t e s
states”);
Stract function can also append string constant to a string variable. For example,
Strcat(s1, “Good”);
C permits nesting of strcat functions. For example
Stract(stract(string1, string2), string3); is allowed and concaveness all three strings
together. The resultant string is stored in string1.
Strrcmp( ) function:
The strcmp( ) function compares two strings and returns a value o if they are equal,
returns positive value if first string is greater than second one or returns a negative
value if string1 is less than string2. The syntax is,
Strcmp(string1, string2);
String1 and string2 are string variables or string constants. For example,
Strcmp(name1, nam2);
Strcmp(name1, “anu”);
Strcmp(“anu”, “asha”);
For example,
Strcmp(“Hi”, “Hi”)
Will return value 0, because both strings are equal.
Strcmp(“Ram”, “Ram”);
Will return -14. That is it will return numeric difference first non-matching characters
in the stings ASCII value of „a‟ – ASCII value of „0‟.
97 - 111
- 14
Strcmp(“has”, “as”);
Will return 7 that is,
ASCII value of „h‟ – ASCII value of „a‟
104 – 97
7
Strcpy( ) function:
The syntax will be,
Strcpy(string1, string2);
Will assigns the contents of string2 to sting1. String2 may be a character array
variable or a sting constant. For example,
Strcpy (city, “Delhi”);
Will assign the sting “Delhi” to the string variable city similarly,
Strcpy(city1, city2);
Will assign the contents of the sting variable city2 to the string variable city1. The
size of the array city1 should be large enough to receive the contents of city2.
Strlen( ) function:
This function counts and returns the number of characters in a string. The sytax is,
Int n=strlen(string);
N receives the value of length of string. The counting ends at first null character. For
example,
Char s[10]= “Hello”;
Int n = strlen(s);
Here, n will receive the value 5.
Strrev( ) function:
The strrev( ) function reverses the contents of string variable. The syntax is,
Strrev (string1);
For example,
Char s[6]= “Hello”;
Strrev(s);
After reversing, s contains “olleH”.
POINTERS
A pointer is a derived data type in C. pointers contain memory addresses as
their values. Since these memory addresses are the locations in the computer memory
where program instructions and data are stored, pointers can be used to access and
manipulate data stored in the memory.
Pointers are used frequently in C, as they offer a number of benefits to the
programmers. They are,
1. Pointers are more efficient in handling arrays and data tables.
2. Pointers can be used to return multiple values from a function via function
arguments.
3. Pointers reduce length and complexity of programs.
4. They increase the execution speed and thus reduce the program execution time.
Understanding Pointers:
The computer‟s memory is a sequential collection of storage cells. Each cell,
commonly known as a byte, has a number called address associated with it. Typically
the addresses are numbered consecutively, starting from zero. The last address
depends on the memory size. A computer system having 64k memory will have its
last address as 65,535.
. . . . . . . . .
0 1 2 3 4 5 6 7 8 65535
That is 64x1024=65536
Whenever we declare a variable, the system allocates somewhere in the
memory, an appropriate location to hold the value of the variable. Since, every byte
has a unique address number, this location will have its own address number consider
the following statement.
int quantity=179;
This statement instructs the system to find a location for the integer variable
quantity and puts the value 179 in that location. Let us assume that the system has
chosen the address location 5000 for quantity. That is quantity
179
5000
During execution of the program, the system always associates the name
quantity with the address 5000. We may have access to the value 179 by using either
the name quantity or the address 5000. Since memory addresses are simply numbers,
they can be assigned to some variables that can be stored in memory, like any other
variable. Such variables that hold memory addresses are called pointer variables. A
pointer variable, is therefore nothing but a variable that contains an address, which is
a location of another variable in memory.
Remember, since a pointer is a variable, its value is also stored in the memory
in another location. Suppose, we assign the address of quantity to a variable P.
The link between the variables P and quantity can be visualized as below.
Quantity
179 5000
Structure Initialization:
A structure variable can be initialized both at compile time and run time.
Compile Time Initialization:
Struct complex
{
int real;
int imag;
}c1={3,4};
Will assigns 3 to real and 4 to imag. There is a one to one correspondence between
members and their values.
In the same way structure can also be initialized as,
Struct complex
{
int real;
int imag;
};
Struct complex c1={2, 5};
Struct complex c2={1, 8};
We can also initialize only the first few members and leave the remaining blank. The
uninitialized members should be only at the right side. The uninitialized members will
be assigned with default values. That is zero for integer and float variables, 1 0 for
characters and strings. For example,
Struct complex
{
Int real;
Int complex;
}c1={2};
Will assign 2 to real and default value 0 to imag.
Run time initialization:
The structure variable can be initialized at run time assign scanf() function.
For example,
Scanf(“%d%d”,&c1.real, &c1.imag);
Copying and comparing structure variables:
Two variables of the same structure can be copied the same way as ordinary
variables. If c1 and c2 are variables of structure complex, then the following
statement is valid.
c1=c2;
However,
c1!=c2;
are not valid. C does not permit any logical operations on structure variables.
Word boundaries and slack bytes:
Computers stores structures using the concept of word boundary. The size of a
word boundary is machine dependent. In a computer with two bytes word boundary,
the members of a structure are stored left aligned on the word boundary. A character
data takes one byte and an integer takes two bytes. One byte between them is left
unoccupied. This unoccupied byte is known as slack byte.
1 2 3 4
Slack
Char int
Byte
When we declare structure variables, they may contain slack bytes and the
values stored in such slack bytes are undefined. Due to this, even if the members of
two variables are equal, their structures do not necessarily compare equal. Therefore
C does not permit comparison of structure variables directly.
Operations on individual members:
The individual members are identified using the member operator, the dot. A
member with the dot operator along with the structure variable can be treated like any
other variable and therefore can be manipulated using expressions and operators. For
example,
C3.real=c1.real+c2.real;
File management in C
We can use the functions such as scanf() and printf() to read and write data.
These are aconsole oriented I/o functions, which always use the terminal (Keyboard
and monitor) as the target place. This works fine as long as the data is small.
However, many real life problems involve large volumes of data and in such
situations console oriented I/o operations pose two major problems.
1. It becomes time consuming to handle large volumes of data through terminals.
2. The entire data is lost when either the program is terminated or the computer is
turned off.
It is therefore necessary to have a more flexible approach where data can be stored on
the disks and read whenever necessary, without destroying the data. This method
employs the concept of files to store data. A file is a place on the disk where a group
of related data is stored. Like most other languages, c supports a number of functions
that have the ability to perform basic file operations, which include
1. Naming a file
2. Opening a file
3. Reading data from a file
4. Writing data to a file
5. Closing a file
There are two distinct ways to perform file operations in C. the first one known as the
low level I/o and uses unix system calls. The second method is referred to as the high
level I/o operation and uses functions in c standard I/o library.
Defining and opening a file:
If we want to store data in a file in the secondary memory, we must specify certain
things about the file to the operating system.
They include,
1. File name
2. Data structure
3. Purpose
Filename is a string of characters that make up a valid file name for the operating
system. It may contain two parts, a primary name and an optional period with the
extension. For example,
Input.data
Sotre
Prog.c
Text.out
All files should be declared as FILE before they are used. FILE is a defined data type.
When we open a file, we must specify what we want to do with the file. For example,
we may write data to the file or read the already existing data.
The general syntax for dedclaring and opening a file is,
FILE *fp;
Fp=fopen(“filename”, “mode”);
The first statement declares the variable fp as a pointer of type FILE. The second
statement opens the file named filename and assigns an identifier to the FILE type
pointer fp. This pointer, which contains all the information about the file is
subsequently used as a communication link between the system and the program.
The second statement also specifies the purpose of opening this file. The mode will do
this job. Mode can be one of the following;
r- Open the file for reading only
w- Open the file for writing only
a- Open the file for appending (or adding) data to it.
Note that both the filename and mode are specified as strings. They should be
enclosed in double quotation marks.
When trying to open a file, one of the following things may happen;
1. When the mode is „writing‟, a file with the specified name is created if the file
does not exist. The contents are deleted, if the file already exist.
2. When the mode is „appending‟, the file is opened with the current contents safe. A
file with the specified name is created if the file does not exist.
3. If the mode is „reading‟ and if it exists, then the file is opened with the current
contents safe, otherwise an error occurs. Consider the following statements.
FILE *p1, *p2;
P1=fopen(“data”, “r”);
P2=fopen(“results”, “w”);
The file data is opened for reading and results is opened for writing. In case,
the results file already exists, its contents are deleted and the file is opened as a new
file. If data file does not exist, an error will occur.
Many recent compilers include additional modes of operation. They are,
rt- The existing file is opened to the beginning for both reading and
writing.
wt- same as w except both for reading and writing.
at- same as a except both for reading and writing.
Closing a file:
A file must be closed as soon as all operations on it have been completed. This
ensures that all links to the file are broken. It also prevents any accidental misuse of
the file. In cane, there is a limit to the number of files might help one the required
files. Another instance where we have to close a file is when we want to reopen the
same file in a different mode. The I/o library supports a function to do this for us. The
general syntax is,
fclose(file_pointer);
This would close the file associated with file_pointer. For ex,
FILE *p1, *p2;
P1=fopen(“input”, “w”);
P2=fopen(“output”, “r”);
……
……
fclose(p1);
fclose(p2);
The above code segment opens two files and closes them after all operations
one them are completed. Once a file is closed, its file pointer can be raised for another
file.
All files are closed automatically whenever a program terminates. However,
closing a file as soon as you are done with it is a good programming habit.
Input/output operations on files:
getc and putc functions:
The simplest file I/o functions are getc and putc. Assume that a file is opened
with mode w and file pointer fp1. Then, the statement,
putc(c, fp1);
Writes the character contained in the character variable c to the file associated with
pointer fp1. Similarly, getc is used to read a character from a file that has been opened
in read mode. For example,
C=getc(fp1);
Would read a character from the file whose file pointer is fp1. The file pointer moves
by one character position for every operation of getc or putc. The getc will return an
end of file marker EoF, when end of the file has been reached. Therefore, the reading
should be terminated when EoF is encountered.
getw and putw functions:
The getw and putw are integer oriented functions. They are similar to the getc
and putc functions and are used to read and write integer values. These functions
would be useful when we deal with only integer data. The general syntax of getw and
putw functions are,
putw(a, fp);
b=getw(fp);
putw will write data contained in a to a file pointed to by fp. getw will read integer
value from file pointed to by fp and store in b.
1
This division of problems into subproblems has many
advantages.Theyare
1. It provides top down approach. In this programming style, the high-
level logic of the overall problem is solved first while the details of
each lower level function are addressed later,
2. The length of program can be reduced.
3. It is easy to identify and debug errors.
4. A function may be used by many other programs. This means that
a C Programmer can use the functions which are written by others
to write his program.
Main Program
2
Main ( )
Function1( )
Function1( )
return
Flow of control in multi-function program
Some characteristics of modular programming are,
1. Each module/function should do a single task.
2. Communication between functions can be established using
functions calls and returning values.
3. No communication take place between functions if there is no
function call.
4. All functions will have single entry and exit point.
Elements of user defined functions:
In order to make use of a user defined function. We need to write
three things that are related to functions.
1. Function definition
2. Function call
3. Function declaration
The function definition is an independent program module that
is written to implement the requirements of a function. In order to use
this function, we need to invoke it at a required place in the program.
This is known as the function call. The function which calls another
function is called calling function. The function which is invoked by
other function is known as called function. The program should
3
declare any function that need to be call later. This is known as
function declaration or function prototype.
Definition of functions:
A function definition also known as function implementation,
should include the following elements.
1. Function name
2. Function type
3. List of parameters
4. Local variable declarations
5. Function statements
6. A return statement
All six elements are grouped into two parts. They are,
1. Function header [combination of function name, function type
and list of parameters].
2. Function body [combination of local variable declarations,
function statements and a return statement]
A general syntax & function definition is,
Function type function name [Parameter List]
{
Local variable declaration;
Statement 1;
Statement 2;
……… Statement n;
Return statement;
}
4
Function Header:
The function header consists of three parts, the function type
also known as return type, the function name and the formal
parameter list. Semicolon should not be used at the end of function
header.
The function type specifies the type of value that the function is
expected to return to calling function. If the return type is not explicitly
specified, C will assume it as integer type. If the function is not
returning anything, then we need to specify the return type as void.
The value returned is the output produced by the function.
The function name is any valid C identifier and therefore must
follow the same rules of formation as other variables in C. the names
should be appropriate to the task performed by the function. Library
function names should not be used as user defined function names.
The parameters list declares the variables that will receive the
data sent by the calling function. They serve as input data to the
function to carry out the specified task. Since they represent actual
input values, they are called as Formal Parameters. The parameters
are also known as Arguments.
The parameter list contains declaration of variables separated
by commas and surrounded by parenthesis. For example,
float quadratic (int a, int b, int c)
double power (double x, int n)
float mul (float x, float y)
int sum (int a, int b)
Note that the declaration of parameter variables cannot be combined,
that is,
int sum(int a, b)
5
is not vaild.
A function need not always receive data from calling function. This can
be indicated by empty parenthesis. That is,
int sum ( )
the function neither receives any data not returns any value. This can
be indicated as
void sum ( )
Function Body:
The function body contains the declarations and statements
necessary for performing the required task. The body enclosed in
braces, contains three parts in the order given below.
1. Local declarations that specify the variables needed by the function.
2. Function statements that perform the task of the function.
3. A return statement that returns the value evaluated by the function.
If a function does not return any value, then it is not required to write
return statement and return type should be specified as void.
Return values and their types:
A function may or may not send back any value to the calling
function. If it does, it is done through the return statement. While it is
possible to pass any number of values from calling function to called
function, but called function is able to return only one value at a time.
The general syntax of return statement is
return ;
or
return expression
The first return does not return any value, it meant to return control
of execution. An example of second return statement is,
return p;
6
returns the value of p.
A function may have more than one return statements. This situation
arises when the value returned is based on certain conditions. For
example,
is (x<0)
return 0;
else
return 1;
Function Calls:
A function can be called by simply using the function name
followed by a list of variable names. The variables names or values in
function call are called actual arguments (or) actual parameters.
When a compiler encounters a function call, the control of
execution will get transfer to called function. That function is then
executed line by line as defined and a value will be returned when it
encounters a return statement.
They are many different ways to call a function. They are,
mul (10, 5);
mul (n, 5);
mul (10, n);
mul (m, n);
mul (m+5, n);
However, a function cannot be used on the left side of assignment
statement. That is,
mul (a, b)=15
is invalid.
7
Function declaration:
Like variables, all functions in a C program must be declared,
before they are called A function declaration (also known as function
prototype) consists of four parts.
1. Function type (return type)
2. Function name
3. Parameter list
4. Terminating semicolon
The general syntax of function declaration is,
function_type function_name (parameter list);
This is very similar to function header line except the terminating
semicolon.
Rules to be followed while using functions:
1. The parameter list must be separated by commas.
2. The parameter names do not need to be the same in the
prototype declaration and the function definition.
3. The types must match the types of parameters in the function
definition in number and order with the parameters in function
call and function declaration.
4. Use of parameter names in function declaration is optional.
5. The return type is optional, if function returns int type data.
6. The return type must be void, when the function does not return
a value.
7. When the data types of variables in function declaration and
function definition does not match, they compiler will give an
error.
8
Category of functions:
A function, depending on whether arguments are present or not
and whether a value is returned or not, may belong to one of the
following categories.
1. Functions without arguments and without return value.
2. Functions with arguments and without return value.
3. Functions without arguments and with return value.
4. Functions with arguments and with return value.
5. Functions that return multiple values.
Functions without arguments and without return value:
When a function has no arguments, it does not receive any data
from the calling function. Similarly when it does not return a value, the
calling function does not receive any data from the called function.
Then, there is no data transfer between calling function and called
function. This is illustrated in the diagram below.
function1( ) function2( )
{ No data {
function2( ) Control
Output
No data
Control
}
Function2(a) No
Return value
} }
9
The actual and formal arguments should match in number, type
and order. The values of actual arguments are assigned to the formal
arguments on a one to one basis starting with the first argument.
We should ensure that the function call has matching arguments.
In case, the actual arguments are more than the formal arguments, the
extra actual arguments are discarded. On the other hand, if the actual
arguments are less than the formal arguments, the unmatched formal
arguments are initialized to some garbage values. Any mismatch in
data type may also result in passing of garbage values. No error
messages will be generated.
While the formal arguments must be valid variable names, the
actual arguments may be variable names, expressions or constants.
The variables used in actual arguments must be assigned values before
the function call is made.
When a function call is made, only a copy of the values of actual
arguments is passed into the called function. What occurs inside the
function will have no effect on the variables used in the actual
arguments list.
Variable number of arguments:
Some functions have a variable number of arguments and data
types which cannot be known at compile time. The printf and scanf
functions are typical examples. The ANSI standard proposes new
symbol called the ellipsis to handle such functions. The ellipsis
consists of three periods (…) and used as shown below.
Double area (float d, …)
Both the function declaration and definition should use ellipsis to
indicate that the arguments are arbitrary both in number and type.
10
Functions without arguments and with return value:
There could be a situation where we may need to design
functions that may not take any arguments but returns a value to the
calling function. The communication between calling function and
called function is given below.
Function2()
returns Return c;
a value
} }
Function2(e);
function Return f;
} result
}
11
Nesting of functions:
Nesting of functions is nothing but one function class another
function. C permits nesting of functions. Main ( ) function can call
function1, which can call function2, function2 can call function3 and
so on. There is no limit as to how deeply functions can be nested.
The nesting does not mean defining one function within another.
Recursion:
When a called function in turn calls another function a process
of chaining occurs. Recursion is a spend case of this process, where a
function calls itself.
Very simple example of recursion is,
Main ( )
{
printf (“recursion”);
main ( );
}
Here, main ( ) function is calling itself, this is called recursion. But the
above example runs for infinite number of times.
Recursive functions can be effectively used to solve problms where
solution is expressed in terms of successively applying the same
solution to subsets and the problem. When we write recursive
functions, we must have an if statement somewhere to force the
function to return without the recursive call being executed.
Otherwise, the function will never return.
Passing arrays to functions:
Like the values of simple variables, it is also possible to pass the
values of an array to a function. To pass a one dimensional array to a
12
called function, it is sufficient to mention the name of the array,
without any subscripts and the size of the array as arguments.
For example, the call
Largest (a, n)
Will pass the whole array a to the called function. The called function
expecting this call must be appropriately defined. The largest function
header must look like
Float largest (float a[ ], int size)
The function largest is defined to take two arguments, the array name
and the size of the array to specify the number of elements in the array.
The declaration of number of elements in the array. The declaration of
the formal argument array is made as follows.
Float a [ ]
The pair of brackets informs the compiler that the argument a is an
array of float values. It is not necessary to specify the size of the array
here.
In C, the name of the array represents the address of its first
element. By passing the array name, we are in fact, passing the address
of the array to the called function. The array in the called function now
refers to the same array stored in the memory. Therefore, any changes
in the array in the called function will be reflected in the original array.
Passing addresses of parameters to the functions is referred to
as pass by address (or pass by reference). We cannot pass a whole
array as value as we do in case of ordinary variables.
When dealing with array arguments, there will be one major
distinction. If a function changes the values of the elements of an array,
then these changes will be made to the original array that passed to
the function. When an entire array is passed as an argument, the
13
contents of the array are not copied into the formal parameter array,
instead information about the addresses of array elements are passed
on to the function. Therefore, any changes introduced to the array
elements are truly reflected in the original array in the calling function
however, this does not apply when an individual element is passed on
as argument.
Two dimensional arrays as parameters to functions:
Like one dimensional arrays, we can also pass two dimensional
arrays to functions. The approach is similar to one dimensional arrays.
The rules to pass two dimensional array as parameter to function are,
1. The function must be called by passing only array name without
subscripts.
2. In the function definition, we must indicate that the array has two
dimensions by including two brackets.
3. The size of second dimension must be specified.
4. The prototype declaration should be similar to function header.
*****
14