C - giftian

advertisement
Chapter-01
Background
The ‘C’ language consists of two visibly distinguished words that is: “C’ and Language. Let’s
Understand what is a language and what is it’s constituents:
Definition: Language can be defined as a medium of communication between two well acquainted entities.
Human-Human
interaction
In the above definition, well acquainted means, two entities must have a common logical interface such as
social, biological, or logical co-relations. The contradiction example: human and dog, person from japan and
person from orissa and don’t know each other’s language cannot communicate.
Hence, it is essential that two persons in communication must follow a common language format, else
cannot establish the communication.
Language Constituents
Set of symbols
words
Every
language
is
consisting of
several
symbols :
For ex: Set of symbols
that forms the English
language are: A to Z,
a to z, other special
symbols such as !, @, +, etc.,
Alphabets
are
grouped together to
form a word, whose
meaning is well
defined in the social
dictionary of the
language concerned
Grammar or
Syntax
For arranging the
words
into
a
meaningful
sentence,
every
language has it’s
own
rules
of
grammar, known
as Syntax
1
Hence, every language on earth shares the same architecture of language i.e, every language has their own set
of symbols, every language has a social dictionary that assigns a meaning to group of alphabets and every
language has it’s own rules of grammar (syntax) to frame meaningful sentences.
In other words, all languages differs in symbols within set of symbols, words in the dictionary and rules in the
grammar.
Example of languages that acts as an interface for human interactions are: English, Hindi, Japnese, German,
French, Telugu, Oriya and hundred of such languages.
Human – Computer interaction
Now, apply the above analogy for another set of entities, one of is an intelligent human and another is nonintelligent computer.
One test of communication: supply two numbers to computer and ask that to add, it will add both
and will tell you the result. Hence, we can assume that, computer understood the instructions, hence
gave us the correct
It is evident that some sort of language interface is essential for establishing a communication, hence
the same for human-computer interaction as well (henceforth we will refer it as computer language).
There are several languages that acts as interface between human-computer interactions are:
 ‘C’,,
 ‘C++’,
 Java,
 Visual Basic,
 Pascal,
 FOTRAN,
 Cobol,
 Basic
 VB.NET ….and several hundreds of such languages.
2
Language is the medium through which one expresses his/her thought to another person, hence
computer language as well serves the same purpose, only difference is that here one entity is human
and another is computer.
The relation between these two is master-slave or teacher-student.

The entity who teaches to computer by giving step by step instruction is known as a
Programmer,

The medium through which programmer teaches is known as Computer Language,

The step by step instructions arranged in an logical order for developing the intelligence of
the computer regarding solving a problem or performing a task is known as Program, and

The process of writing a program is known as Programming.
Now, we can safely conclude that ‘C’ is one of the several computer languages that is used to write a
program. It is one of the interfaces using which, programmer writes the instructions for computer to
perform a specific task.
System
“System can be defined as a group of components, which are inter-related and integrated with
each other, accepts the input, processes it and gives out the desired output”.
Following are the conditions need to be satisfied to become a system.
1. There must exist group of components,
2. The components must be inter-related and integrated with each other,
3. There must exist some component(s) to capture input from external world,
4. There must exist some components(s) to process the input captured by input component
of the system,
5. There must exist some component(s) to output the processed result,
6. The out must be desired output.
Input
Process
Input
(Inter-related and integrated components of a system)
Hence, any where the word “system” is annexed, it must comply with the above mentioned definition.
Examples of systems
 Nervous system,
 Digestive system,
 Education system,
 Computer system ……..
3
Conceptualizing and Visualizing Computer
Before becoming an teacher(or, programmer) of computer, it is essential to accumulate and conceptualize the
Architectural and designing background of computer.
As of layman’s idea, computer is a machine that is designed by human being with an intention to substitute
human brain. If we will introspect into the machine design attitude of human being, then we can find that,
human designs(or invents) machine with an intention to substitute the functionality of different parts of body
with an objective to save the self energy, to perform the tasks faster, to gain more accuracy and efficiency.
Body Part
Substituted Machine
Hand
Washing Machine, Vacuum Cleaner
Leg
Cycle, Motor Bike, Train, Aero plane, etc,
Eye
Tele Vision
Ear
Microphone, Phone, Mobile Phone
Brain
Computer
(Human Created machines to substitute various parts of body)
Every designer or inventor of above substituted machine must have gone through the functionality and
operational details of the body part for which substitution is designed.
Now, let’s attempt to substitute the most important part of our body i.e.,
Brain or Central
Nervous System(CNS).
Hence, as per the above analogy, to start designing the substitution of brain, we need to perform following
activities:
 Probing in depth into the functionality of brain and finding the exact atomic functionality that brain
performs,
 Designing the device units to substitute each of atomic function of brain,
 Integrating those substituted devices into an integrated device system that will substitute the whole of
CNS.
Let’s proceed with the first step,
Functions Of Brain
Various atomic functions that central Nervous System(CNS) performs are:
1. Control: This functionality is responsible for controlling the overall activity of the
human body,
2. Memory: This functionality is responsible for storing the data or instructions that are
going to be processed or storing the output after processing.
3. Arithmetic and Logical Calculation: It is the real processor of brain that is capable of
performing both arithmetic as well as Logical calculations.
4
4. Input: Data need to be captured from external world into the memory for processing. It
is done through various capturing organs such as: Ear, Eye, Skin and Nose.
5. Output: Processed data need to be output to the external world through various organs
such as Mouth .
For designing the substituted machine for the CNS, we need investigate the above functionality very keenly
and design the functionality.
Chapter-02
COMPUTER BASICS
A computer is an electronic device which can performs the arithmetic calculations as well as the logical
operations. It may store the data for future use by magnetic or optical manner and can process the data
according to the instruction given to it & produce the users requirement as output. N other words
A computer is an electronic device. It accepts some input, process it & produce the desired out put.
Basically a computer has four functions
- It accept the data as input .
- Storing the data & instructions in its memory & recalling it as when required.
- Processing the data as per instructions to convert it into useful information.
- Communicating the information as output.
Block diagram of computer
In the diagram, the arrows indicate the direction of data flow. Some data flows in one direction only.
In some cases it flows in both directions.
At the heart of the computer is the microprocessor. This contains several REGISTERS to store data
and an ARITHMETIC LOGIC UNIT (ALU) which manipulates data. It acts as the central
processing unit (CPU) of the computer, carrying out a sequence of instructions, called a program.
The program may be stored in memory, as software, or loading into the memory from disk.
CU
ALU
FPU
L1-Cache
Register Array
5
[FIG: Block diagram of a digital computer]
COMPUTER SYSTEM
The computer system includes.
- Hardware
- Software
- Firmware
- Data & information
- user
Hardware: All the physical components of a computer system called hardware. It includes:
- Input device
- Output device
- CPU
- Memory
Software: The instructions to manage system resources as well as requirements of user, is called as
software. It is the software, that make operational the system resources.
Firmware: The software in the form of hardware is called as firmware. Example of firmware is ROM .
Date: The raw and unevaluated fact or figures is called as Data.
Information: The processed data, which can be used for decision making is called as Information.
User: The entity who make use of
MEMORY
Memory can be defined as a storage location which is used to store intangible data such as
text, image, sound and smell etc.,
The intangible data initially captured by input device specific for specific data pattern then all data
transformed into respective bit format( where each bit represents an electrical pulse) and the bit format
then get stored inside the memory.
Purpose of storage
A digital computer represents information using the binary numeral system. Text, numbers, pictures,
audio, and nearly any other form of information can be converted into a string of bits, or binary digits,
each of which has a value of 1 or 0. The minimum unit of storage is the byte, equal to 8 bits. A piece of
information can be handled by any computer whose storage space is large enough to accommodate the
6
binary representation of the piece of information, or simply data. the most important part of every
computer is the central processing unit (CPU, or simply a processor), because it actually operates on
data, performs any calculations, and controls all the other components.
Processor without a memory would not be a computer, merely a simple digital signal processing device,
able to perform a fixed operation and immediately output the result. It would have to be re-built to change
its behaviour, like in case of a calculator. The ability to store and change both instructions and data, the
important von Neumann's idea, makes computers versatile. It basically introduces the concept of
computer programming, as opposed to re-building the hardware.
A computer can exist that uses the single type of storage for all the data. However, to provide acceptable
computer performance at a lower cost, computers usually use a whole storage hierarchy. The traditional
division of storage to primary, secondary, tertiary and off-line storage is based on the speed and cost per
bit. The lower a storage is in hierarchy, the bigger is its distance from the CPU.
Memory is a storage area which stores data and instruction in the form of High/Low signal only
for future uses and smooth operation of the computer. OR it can also be defined as storage place for
storing intangible data.
-
The present day memory can store the varieties of data like,
user’s data/instruction
graphs
pictures
sounds
smell, etc.
Architecture of memory may use any of the following device as it’s building block
1.
2.
3.
4.
Analog method (capacitor)
digital method (flip-flop)
electromagnetic method
optical method
TYPES OF MEMORY
Memory could be distinguished into four types as per their reach to the CPU for processing.
-
Primary storage / memory
Secondary storage
Off-line storage
Tertiary storage
Hierarchy of storage
7
PRIMARY MEMORY:
Primary memory can be defined as memory that is primarily available for the processor
and supply data and instruction required for data processing.
- Primary memory, is the only one that is directly accessible by the CPU. CPU continuously reads
instructions stored there and executes them. Any data actively operated on is also stored there in
uniform manner.
- The present day memory uses the semiconductor chips as their primary memory. So primary memory
otherwise called as semiconductor memory.
- The earliest form of memory was based on vaccume tubes, gradually it changes to magnetics cores to
transistors and finally to the electronics memory i.e. solid-state silicon chips technology.
- Basically the primary memory is made up of either flip-flop or capacitor.
- Again the primary memory devided into :
8
-RAM
-ROM
-Register
-Cache Memory
- RAM and ROM are considered as main memory, as their essential and its necessity is crucial to the
CPU execution.
As shown in the diagram, traditionally there are two more sub-layers of the primary storage, besides
main large-capacity RAM:


Processor registers are located inside every processor. Each of the registers holds only several
bits of data, for example 64 bits. The arithmetic and logic unit uses this data to carry out the current
instruction. Registers are technically the fastest of all forms of computer data storage, being switching
transistors integrated on the CPU's chip, and functioning as electronic "flip-flops".
Processor cache is an intermediate stage between ultra-fast registers and much slower main
memory. It's introduced solely to increase performance of the computer. Most actively used information
in the main memory is just duplicated in the cache memory, which is faster, but of much lesser capacity.
On the other hand it is much slower, but much larger than processor registers. Multi-level hierarchical
cache setup is also commonly used—primary cache being smallest, fastest and located inside the
processor; secondary cache being somewhat larger and slower.
Main memory is directly connected to the CPU via a memory bus, or front side bus, a high-speed digital
"superhighway". It is actually comprised of three buses
- an address bus
- a data bus and
- a control bus
The CPU firstly sends a number through an address bus, a number called memory address, that
indicates the desired location of data. Then it reads or writes the data itself using the data bus.
Additionally, a memory management unit (MMU) is a small device between CPU and RAM recalculating
the actual memory address, for example to provide an abstraction of virtual memory or other tasks.
RAM is zeroed after computer powers on. If a computer contained only RAM, the CPU would not have a
place to read any instructions from. Hence a non-volatile primary storage is used, containing small initial
program, both to perform hardware power-on self test, and to bootstrap, that is, to read the larger
program from non-volatile secondary storage to RAM and execute it. A non-volatile technology known as
read-only memory (ROM) is used for this purpose.
RAM :
- The memory, whose any random location can be accessed with exactly equal tme.
-RAM stands for Random Access Memory, that is used to temporarily store information while the
computer is ON.
-Random Access Memory means any of the locations on the memory can be randomly selected and
used to directly store (write) and retrive (read) data or information without affecting other cells.
-RAM is the region into which programs are loaded before the CPU processes the information.
-If the CPU needs to store the results of calculations it can store them in RAM. RAM can have instruction
READ from it by the CPU and also it can have other data WRITTEN to it by the CPU. So it is also called
Read/Write memory.
-RAM is also called as Volatile memory. i.e. it losses its contents when once switched off or power
failure.
-In RAM, a particular cell of information is accessed by referring to it by its row and columns. Since there
are no physically moving components and all access of data is achieved electronically, the process of
reading and writing to RAM is very fast compared to other forms of digital storage.
How does it operate ?
9
RAM is composed of millions of tiny elements that have the capabilities of storing a unit of digital
information – ‘bit(binary digit)’. Transistors and capacitors are two of the most popular electronic
components that have the capability of storing a charge. Capacitors are electronics components that are
constructed out of two conductors that are separated over a small space by a non-conducting materials.
When an electric voltage difference is applied between the two plates, a charge gets stored within this
component. This charge remains on it so long as there is an electric potential applied between the
plates. Otherwise it gets dischargeed over a period of time. To counter this problem, the charge on the
capacitors used in RAM is constantly ‘refreshed’ to as to keep the information within it. These capacitors
are extremely tiny and are fabricated on a chip of silicon that holds millions of them. They are
interconnected via very fine conducting paths that are also etched into the silicon and indivisual elements
are written to or read from these memory cells by applying the correct signals to the corresponding lines.
In this diagram, the process of reading and writing information to RAM is explained theoretically.
Fig.
There are various kinds of RAM
SRAM :
- SRAM is works on the principle of the transistors (flip-flop).
- It is much more faster than other memory. So they don’t need to refreshment. So it is
called static memory ( it don’t requirs refresh when the data flows)
- It is costly than others and consume more power.
- SRAM is used mainly in a special area of memory called a cache because of its high speed.
DRAM :
- DRAM stands for Dynamic Random Access Memory.
- DRAM is works on the principle of MOSFET and it is slower than SRAM.
- It is dynamic, because each memory cell quickly losses its charge. So it must be refreshed
hundreds of times per seconds to prevent data from being lost.
- Normally in computer system, the device which is called RAM CARD is coming under this
catagories.
SDRAM :
- SDRAM stands for Sequential / Synchronous Dynamic Random Access Memory.
- SDRAM coming under DRAM.
- Incase of SDRAM , the memory cell works one after another in a synchronous manner. i.e. when
one cell will full fill, the data will store in other cell like a shift register action.
- So it consume less power and durable.
- But the data speed is slower.
DDRAM :
- DDRAM stands for Double Dynamic Random Access Memory and it also coming under DRAM.
- In case of DDRAM, the data speed is much more faster than SDRAM. i.e. it store in randomize
form.
- It consume more current than SDRAM but the data speed is higher.
EDO RAM :
- EDO RAM stands for Extended Data Out Random Access Memory, was the successor of
DRAM.
- Its speed is high, due to higher operational frequencies.
- EDO RAM was used the pentium-I machine.
VRAM :
- VRAM stands for video Random Access Memory.
- This memory is otherwise called as AGP (Accelated Graphic Port).
- VRAM is used from the frame buffer, which is part of video memory used to hold the final frame
that is to be displayed on the monitor (VGA).
- It also used to store the extensive graphical information like textures(makes) of the 3D objects.
- VRAM is very similar to that used as a main memory of our system, except that it is optimised for
working with video and graphical information.
10
ROM:
-ROM stands for Read Only Memory.
-The contains of ROM is parmanently stored on memory chip installed by the manifacturer inside
the computer and we can’t change it.
-The ROM chip also called firmware.
-ROM is called as non-volatile memory because it is static and unchanging.
-ROM is generally used to store programs and instructions at the time of manufactur.
It contains the instruction about ;
- when we turn the computer ON, what will be do.
- How does it know to check out your systems hardware components to see that they
have been connected correctly ?
- It also contains the information about assembler, compiler, debugging package & other
permanent program.
There are several types of ROM
- PROM
- EPROM
- EEPROM
- EAPROM
PROM :
- PROM stands for Programmable Read Only Memory.
- Function of PROM same as ROM and PROM chips are custom made for the user by the
manufacturer. i.e. the user determine what ever data and instructions are recorded in them.
- Incase of PROM chip, once data is recorded on them, it can’t be changed.
EPROM:
- EPROM stands for Erasable PROM.
- In this type of ROM, the data can be erased again and again. i.e. this ROM can be used for a
number of times write and erase the data by the help of Ultraviloet ray.
- In computer system it is used for keeping the index of the peripherals. So otherwise called as
ROMBIOS.
EEPROM :
- EEPROM stands for Electrically Erasable PROM.
- Incase of EEPROM , the concept of data store is same as EPROM, but the erasing technology
are different.
- In EEPROM, by giving a higher voltage to the erasing pin, all data will erase.
EAPROM :
- EAPROM stands for Electrically Alterable PROM.
- EAPROM is an advance of EPROM.
- Incase of EPROM, where ultra violet & electrical voltage given, the data from all memory cell are
erased.
- But incase of EAPROM, data from only the required cell will erased. So the other datas are
safed.
- The data read and write is much slower than the EPROM and EEPROM.
CACHE MEMORY
- A small high speed memory which is used to increase the speed of processing by making current
program & data available to the CPU at a rapid rate called cache memory.
- Cache memory logically present in between the main memory & CPU .but it is physically present very
close to CPU.
i.e: cache are preset inside the CPU,which is called as on chip cache.
11
- The CPU cycle time in a computer is much faster then main memory cycle time. Every time information
read from main memory by CPU,then speed mismatch would make the CPU wait.so according to avoid
the wait ing time cache memory is used.
- The cache capacity is much smaller than the main memory and user’s program. Thus, every time new
data has to be stored in the cache and the used data has to be backed into the main memory.
- As per the CPU’s requirement, CPU fetched from the cache for to get data/instruction. If the required
data is in cache, is called cache hit. If the required data not in cache ,is called cache miss. Then it is
read from the main memory.
Cache hit
Main memory
Cache
CPU
Cache miss
[ fig : Cache memory]
REGISTERS
A Register is a special temporary storage location within the CPU which can accept, store and transfer
data & instruction very quickly and used for immediately.
Categories of registers
Registers are normally measured by the number of bits they can hold, for example, an "8-bit register" or
a "32-bit register". Registers are now usually implemented as a register file, but they have also been
implemented using individual flip-flops, high speed core memory, thin film memory, and other ways in
various machines.
A processor often contains several kinds of registers, that can be classified according to their content or
instructions that operate on them:
1. User-accessible Registers - The most common division of user-accessible registers is into data
registers and address registers.
2. Data registers are used to hold numeric values such as integer and floating-point values. In some
older and low end CPUs, a special data register, known as the accumulator, is used implicitly for many
operations.
3. address registers hold addresses and are used by instructions that indirectly access memory. In some
CPUs, a special address register is an index register, although often these hold numbers used to modify
addresses rather than holding addresses.
4. conditional registers hold truth values often used to determine whether some instruction should or
should not be executed.
12
5. General purpose registers (GPRs) can store both data and addresses, i.e., they are combined
Data/Address registers.
6. Floating point registers (FPRs) store floating point numbers in many architectures.
7. Constant registers hold read-only values such as zero, one, or pi.
8. Vector registers hold data for vector processing done by SIMD instructions (Single Instruction, Multiple
Data).
9. Special purpose registers hold program state; they usually include the program counter (aka
instruction pointer), stack pointer, and status register (aka processor status word).
o
o
Instruction registers store the instruction currently being executed.
Index registers are used for modifying operand addresses during the run of a program.
10. In some architectures, model-specific registers (also called machine-specific registers) store data
and settings related to the processor itself. Because their meanings are attached to the design of a
specific processor, they cannot be expected to remain standard between processor generations.
11. Control and status registers - It has three types. Program counter, instruction registers, Program
status word (PSW).
Registers related to fetching information from RAM, a collection of storage registers located on separate
chips from the CPU (unlike most of the above, these are generally not architectural registers):
o
o
o
o
Memory buffer register
Memory data register
Memory address register
Memory Type Range Registers
Hardware registers are similar, but occur outside CPUs.
Some examples
The table below shows the number of registers of several mainstream processors. Note that the stack
pointer (ESP) is counted as an integer register on x86-compatible processors, even though there are a
limited number of instructions that may be used to operate on its contents.
The number and types of registers in a CPU vary according to the CPU design. The register can store 1
byte to 2 bytes of data.
There are several types of registers:
-
Program counter
Input register
Output register
Instruction register
MAR
MBR
Accumulator
Program counter :
13
The program counter (also called the instruction pointer, or "instruction address register") is a register in
the central processing unit that contains the addresss of the next instruction to be executed.. Depending
on the details of the particular machine, it holds either the address of the instruction being executed, or
the address of the next instruction to be executed. The program counter is automatically incremented for
each instruction cycle so that instructions are normally retrieved sequentially alter the flow of control by
writing a new value to the PC from memory. Certain instructions, such as branches and subroutine calls
and returns(JUMP, CALL, RTS),, interrupt the sequence by placing a new value in the program counter.
In most processors, the instruction pointer is incremented immediately after fetching a program
instruction; this means that the target address of a branch instruction is obtained by adding the branch
instruction's operand to the address of the next instruction (byte or word, depending on the computer
type) after the branch instruction. The address of the next instruction to be executed is always found in
the instruction pointer.
Instruction register:
An instruction register is the part of a CPU's control unit that stores the instruction currently being
executed. In simple processors each instruction to be executed is loaded into the instruction register
which holds it while it is decoded, prepared and ultimately executed, which can take several steps.
More complicated processors use a pipeline of instruction registers where each stage of the pipeline
does part of the decoding, preparation or execution and then passes it to the next stage for its step.
Modern processors can even do some of the steps of out of order as decoding on several instructions is
done in parallel.
Decoding the opcode in the instruction register includes determining the instruction, determining where
its operands are in memory, retrieving the operands from memory, allocating processor resources to
execute the command (in superscalar processors), etc.it holds the intruction and tell what intruction to be
executed.its main work is to hold the instruction without it it does not perform any task.
Memory address register:
The Memory Address Register or MAR is the register of a computer's control unit that contains the
address of a register to fetch or store from or to the computer storage.
The Memory Address Register is half of a minimal interface between a microprogram and computer
storage. The other half is a memory data register.
Memory buffer register:
The Memory Buffer Register (MBR) is the register in the central processor that stores the data being
transferred to and from the immediate access store. It acts as a buffer allowing the central processor and
memory units to act independently without being affected by minor differences in operation. A data item
will be copied to the MBR ready for use at the next clock pulse when it can be either used by the central
processor or stored in main memory.
Accumulator:
Accumulator is a special storage register which is associated with the ALU, in a CPU, a processor
register for storing intermediate results
SECONDARY MEMORY
14
Secondary storage, differs from primary storage in that it is not directly accessible by the CPU. The computer
usually uses its input/output channels to access secondary storage and transfers desired data using
intermediate area in primary storage. Secondary storage does not lose the data when the device is powered
down—it is non-volatile. Per unit, it is typically also an order of magnitude less expensive than primary
storage. Consequently, modern computer systems typically have an order of magnitude more secondary
storage than primary storage and data is kept for a longer time there.
i.e. we knoe that the memory which is vital for computer system is known as primary memory.
According to the disadvantages of primary memory, secondary memory is developed. There are several
reasons for the use of secondary storage devices.
-
In RAM, data can be easily read/write still then it is volatile in nature. So all the data is lost after
switch off the PC which are not recoverable.
In ROM, where datas are permanently store and can also access them. But if some data written
wrongly, we can’t easily change them.
To process large amount of data the primary memory is not sufficient.
Secondary storage devices provide a flexible storage capability for data and program.
Secondaty memory are not part of motherboard. And the system can run without the secondary memory.
Secondary storage have to be accessed through a data channel or a bus. The CPU can’t fetch data or
instruction directly from them. In between the CPU and secondary memory, primary memory (also known
as RAM)is the medium.
There are two types of secondary memory.
 magnetics memory
 optical memory
Again magnetics memory is of two types


magnetic tape
magnetic disk
magnetics disk is of two types
-
floppy disk
hard disk
15
Chapter-03
Language Basics
GENERATION OF LANGUAGE
Machine level Language: The language format which consists of binary digits, that means 0 and 1 is called
machine level language. Machine understand only machine level language.
Assembly Level Language: The language format which consists of mnemonics is called as assembly level
language. The name assembly is given, as it assembles mnemonics with it’s corresponding machine code.
Assembly level language is quite easier to represent logic in comparison with machine level language, as
programmer can write the instructions in English format called as mnemonics. Example of mnemonics are:
ADD, SUB, STA, LDA etc.,
Though, programmer use mnemonics for easier implementation of logic, but, program written in assembly
level language must be translated into machine level language format, as machine architecture can understand
only binary format.
The language translator that translates assembly language format into their corresponding machine level
format is known as Assembler.
But, still the disadvantage of the assembly level language is that, it expects expert level knowledge on system
architecture, hence could not be popular among the novice programmer.
Example of such languages are; MASM, TASM, NASM etc.,
High Level Programming language: The language format that contains more of English language
and works at higher level view of the system architecture, is known as high level language. This language
16
format uses the syntax mostly of English language, and also have programmer friendly features such as:
conditional constructs, looping constructs, functions etc.,
Though it is easier for a programmer to write programs but, as it lacks view to the lower level system
architecture, hence, programmer can not write system level programs using high level language.
The language translators that translates programs written in high level language, into it’s
corresponding machine level format, is known as compiler or interpreter.
Example of such languages are: Pascal, Visual Basic, Basic, PERL etc.,
Middle Level Language: These language formats are very powerful, in the sense
programmer enjoys advantages of both low level language formats and high level formats. In other
words, programmer cam low level applications with programmer friendly features of high level
language.
Example of such language is: ‘C’ language.
Hence ‘C’ language is the most powerful and preferred language and mostly used to develop system software
such as: operating system, driver programs etc., with much ease by utilizing programmer friendly features
such as: functions, looping and conditional constructs.
Language Translators
Language translators are system level programs, which translates high level or assembly level
language to machine level language. Language translators can be categorized into following types:
1. Assembler: It is the language translator that translates programs written in assembly level
language format to it’s corresponding machine level language format.
2. Interpreter: It the language translator that translates a program written in high level language
line by line to it’s corresponding machine level language format.
3. Compiler: It is the language translator that translates the whole program written in a high level
language into it’s corresponding machine level language format.
Compilation Process Under gcc compiler
Following programs are associated in compiling a program.
Editor: It is the program that enables the program to write program using a specific computer
language and edit it when ever necessary. Under Linux we mostly use vim Editor, by writing following
command in command line:
$ vim filename.c
During the whole GCC compilation process many sequence of commands executed internally one after the
other to complete the compilation of the source file. In general GCC consists of the following stages:
*Preprocessing
*Compilation
*Assembly
*Linking
17
Individual compiling steps for hello.c, are as given below.
#include <stdio.h>
int main (void)
{
printf ("Hello, world!\n");
return 0;
}
Note that it is not necessary to use the individual commands described in this section to compile a program. All the
commands are executed automatically and transparently by GCC internally, and can be seen using the -v option.
Although the Hello World program is very simple it uses external header files and libraries, and so exercises all the
major steps of the compilation process.
The Preprocessor
Basically a C program consists of numerous source files like the included header files. For e.g.
#include <stdio.h>
#include "source.h"
where source.h is the user-defined header file. It also includes some user-defined macros.
So the first stage of the compilation process is to expand those include header files and defined macros. Hence a
Preprocessor is used to merge the included header files and defined macros with the source file to produce a transitory
source file, which the standard calls a Translation unit. Translation units are also known as compilation units. GCC
contains a preprocessor for C namely 'cpp' which is used to produce Translation unit. To perform the preprocessing
operation use the following command:
$ cpp hello.c > hello.i
The result is a file ‘hello.i’ which contains the source code with all macros expanded. By convention, preprocessed files
are given the file extension ‘.i’ for C programs and ‘.ii’ for C++ programs. In practice, the preprocessed file is not saved
to disk unless the -save-temps option is used in gcc so we are just redirection operator to save a copy of preprocessed
file.
The Compiler
The next stage of the process is the actual compilation of preprocessed source code to assembly language, for a specific
18
processor. The command-line option -S instructs gcc to convert the preprocessed C source code to assembly language
without creating an object file:
$ gcc -Wall -S hello.i
The resulting assembly language is stored in the file ‘hello.s’. Here is what the Hello World assembly language for an
Intel x86 (i686) processor looks like:
$ cat hello.s
.file "1.c"
.section .rodata
.LC0:
.string "Hello\n"
.text
.globl main
.type main,@function
main:
pushl %ebp
movl %esp, %ebp
subl $8, %esp
andl $-16, %esp
movl $0, %eax
subl %eax, %esp
subl $12, %esp
pushl $.LC0
call printf
addl $16, %esp
movl $0, %eax
leave
ret
.Lfe1:
.size main,.Lfe1-main
.section .note.GNU-stack,"",@progbits
.ident "GCC: (GNU) 3.2.3 20030502 (Red Hat Linux 3.2.3-53)"
Note: that the assembly language contains a call to the external function printf.
The Assembler
The purpose of the assembler is to convert assembly language into machine code and generate an object file. When there
are calls to external functions in the assembly source file, the assembler leaves the addresses of the external functions
undefined, to be filled in later by the linker. The assembler can be invoked with the following command line:
$ as hello.s -o hello.o
As with GCC, the output file is specified with the -o option. The resulting file ‘hello.o’ contains the machine instructions
for the Hello World program, with an undefined reference to printf.
The Linker
The final stage of compilation is the linking of object files to create an executable. In practice, an executable requires
many external functions from system and C run-time libraries. Consequently, the actual link commands used internally
by GCC are complicated. For example, the full command for linking the Hello World program is:
19
$ ld -dynamic-linker /lib/ld-linux.so.2 /usr/lib/crt1.o
/usr/lib/crti.o /usr/lib/gcc-lib/i686/3.3.1/crtbegin.o
-L/usr/lib/gcc-lib/i686/3.3.1 hello.o -lgcc -lgcc_eh
-lc -lgcc -lgcc_eh /usr/lib/gcc-lib/i686/3.3.1/crtend.o
/usr/lib/crtn.o
Fortunately there is never any need to type the command above directly--the entire linking process is handled
transparently by gcc when invoked as follows:
$ gcc hello.o
This links the object file ‘hello.o’ to the C standard library, and produces an executable file ‘a.out’:
$ ./a.out
Hello, world!
An object file for a C++ program can be linked to the C++ standard library in the same way with a single g++ command.
Compiling a simple C program using GCC
In this post we learn How to compile a C program using GCC. The classic example program for the C language is Hello
World. Here is the source code for our version of the program:
#include <stdio.h>
int main (void)
{
printf ("Hello, world!\n");
return 0;
}
We will assume that the source code is stored in a file called ‘hello.c’. To compile the file ‘hello.c’ with gcc, use the
following command:
$ gcc -Wall hello.c -o hello
This compiles the source code in ‘hello.c’ to machine code and stores it in an executable file ‘hello’. The output file for
the machine code is specified using the -o option. This option is usually given as the last argument on the command line.
If it is omitted, the output is written to a default file called ‘a.out’.Note that if a file with the same name as the executable
file already exists in the current directory it will be overwritten.
The option -Wall turns on all the most commonly-used compiler warnings---it is recommended that you always use this
option! There are many other warning options, but -Wall is the most important. GCC will not produce any warnings
unless they are enabled. Compiler warnings are an essential aid in detecting problems when programming in C and C++.
In this case, the compiler does not produce any warnings with the -Wall option, since the program is completely valid.
Source code which does not produce any warnings is said to compile cleanly.
To run the program, type the path name of the executable like this:
$ ./hello
Hello, world!
This loads the executable file into memory and causes the CPU to begin executing the instructions contained within it.
The path ./ refers to the current directory, so ./hello loads and runs the executable file ‘hello’ located in the current
directory.
20
Chapter-04
Operating system types
Definition-1
Operating system can be defined as a type of control system software, that manages overall resources of the computer
system.
Definition-2
Operating system is the only software that starts with the start of the computer and stops with stop of the computer. In
other words it stays resident throughout the tenure of the system.
An operating system, is a software program that enables the computer hardware to communicate and operate with the
computer software. Without a computer operating system, a computer would be useless.
Defintion-3
Operating system acts as an environment for other programs to run.
Hence, for executing a program written in ‘C language as well need the an environment called as operating system. Once
the program is compiled, assembled and linked and executable program is created, the executable program is submitted
to operating system and operating system loads and executes the program.
As computers have progressed and developed so have the types of operating systems. Below is a basic list of the
different types of operating systems and a few examples of operating systems that fall into each of the categories. Many
computer operating systems will fall into more than one of the below categories.
CUI – Short for character user interface. Incase of CUI based Operating system, commands are given in the form
characters, and user need to know the exact syntax of the command for using that.
Below are some example of CUI based Operating system.
MSDOS
Unix
Minix
GUI - Short for Graphical User Interface, a GUI Operating System contains graphics and icons and is commonly
navigated by using a computer mouse.. Below are some examples of GUI Operating Systems.
Linux
Windows 98
Windows CE
Multi-user - A multi-user operating system allows for multiple users to use the same computer at the same time and/or
different times. Below are some examples of multi-user operating systems.
Linux
Unix
Windows 2000
Multiprocessing - An operating system capable of supporting and utilizing more than one computer processor. Below
are some examples of multiprocessing operating systems.
Linux
Unix
Windows 2000
Multitasking - An operating system that is capable of allowing multiple software processes to run at the same time.
Below are some examples of multitasking operating systems.
Unix
Windows 2000
Multithreading - Operating systems that allow different parts of a software program to run concurrently. Operating
systems that would fall into this category are: Linux, Unix, Windows-2000.
21
About Linux
Linux is a GUI based multi user, multi processing, multitasking and multi threading operating system and is a choice of
today’s engineering environment due to following features:
1.
2.
3.
4.
5.
Linux is a robust operating in the sense, chances of viral attack, spy ware intrusion is minimal comparing to it’s
counterpart Microsoft windows.
Linux Is inherently network friendly, and protects the privacy of users as well as provides much flexibility in
operation to the user.
Linux is open, in the sense, user can access to the complete source code of the Linux base and can customize
the features of own, but in case of any other operating system, source code is not made available to the user,
hence, whatever feature available, user must confined to that itself.
Linux is most reliable
Linux is packed with most of the essential applications along with the distribution itself and do not require to
purchase extra application software to add on.
Internal Architecture of Linux operating system
Kernel
Linux operating system consists of following layers in it’s internal architecture:
1.
2.
Hardware: It is the lowest layer in the computer system and includes all tangible components inside the
computer.
Kernel: In computer science, the kernel is the central component of most computer operating systems (OS). Its
responsibilities include managing the system's resources (the communication between hardware and software
components).As a basic component of an operating system, a kernel provides the lowest-level abstraction layer
for the resources (especially memory, processors and I/O devices) that application software must control to
perform its function. It typically makes these facilities available to application processes
Application
Kernel
CPU
Memory
Devices
22
3. Shell: The Linux/Unix shell refers to a special program that allows user to interact with it by entering certain
commands from the keyboard; the shell will execute the commands and display its output on the monitor. The
environment of interaction is text-based (unlike the GUI-based interaction we have been using in the previous chapters)
and since it is command-oriented this type of interface is termed Command Line interface or CLI. Before the advent of
GUI-based computing environments, the CLI was the only way that one can interact and access a computer system.
Important Shell Commands of Linux
1. mkdir - make directories
Usage:
mkdir [OPTION] DIRECTORY
Options
Create the DIRECTORY(ies), if they do not already exist.
Mandatory arguments to long options are mandatory for short options too.
-m, mode=MODE set permission mode (as in chmod), not rwxrwxrwx - umask
-p, parents no error if existing, make parent directories as needed
-v, verbose print a message for each created directory
-help display this help and exit
-version output version information and exit
2. cd - change directories
Use cd to change directories. Type cd followed by the name of a directory to access that directory.Keep in mind that you
are always in a directory and can navigate to directories hierarchically above or below.
3. mv- change the name of a directory
Type mv followed by the current name of a directory and the new name of the directory.
Ex: mv testdir newnamedir
4. pwd - print working directory
will show you the full path to the directory you are currently in. This is very handy to use, especially when performing
some of the other commands on this page
5. rmdir - Remove an existing directory
rm -r
Removes directories and files within the directories recursively.
6. chown - change file owner and group
Usage
23
chown [OPTION] OWNER[:[GROUP]] FILE
chown [OPTION] :GROUP FILE
chown [OPTION] --reference=RFILE FILE
Options
Change the owner and/or group of each FILE to OWNER and/or GROUP. With --reference, change the owner and group
of each FILE to those of RFILE.
-c, changes like verbose but report only when a change is made
-dereference affect the referent of each symbolic link, rather than the symbolic link itself
-h, no-dereference affect each symbolic link instead of any referenced file (useful only on systems that can
the ownership of a symlink)
change
-from=CURRENT_OWNER:CURRENT_GROUP
change the owner and/or group of each file only if its current owner and/or group match those specified here. Either
may be omitted, in which case a match is not required for the omitted attribute.
-no-preserve-root do not treat `/' specially (the default)
-preserve-root fail to operate recursively on `/'
-f, -silent, -quiet suppress most error messages
-reference=RFILE use RFILE's owner and group rather than the specifying OWNER:GROUP values
-R, -recursive operate on files and directories recursively
-v, -verbose output a diagnostic for every file processed
The following options modify how a hierarchy is traversed when the -R option is also specified. If more than one is
specified, only the final one takes effect.
-H
if a command line argument is a symbolic link to a directory, traverse it
-L
traverse every symbolic link to a directory encountered
-P
do not traverse any symbolic links (default)
7. chmod - change file access permissions
Usage
chmod [-r] permissions filenames
r Change the permission on files that are in the subdirectories of the directory that you are currently in.
permission
Specifies the rights that are being granted. Below is the different rights that you can grant in an alpha numeric
format.filenames File or directory that you are associating the rights with Permissions
u - User who owns the file.
g - Group that owns the file.
o - Other.
24
a - All.
r - Read the file.
w - Write or edit the file.
x - Execute or run the file as a program.
Numeric Permissions:
CHMOD can also to attributed by using Numeric Permissions:
400 read by owner
040 read by group
004 read by anybody (other)
200 write by owner
020 write by group
002 write by anybody
100 execute by owner
010 execute by group
001 execute by anybody
8. ls - Short listing of directory contents
-a
list hidden files
-d
list the name of the current directory
-F
show directories with a trailing '/'
executable files with a trailing '*'
-g
show group ownership of file in long listing
-i
print the inode number of each file
-l
long listing giving details about files and directories
-R
-t
list all subdirectories encountered
sort by time modified instead of name
9. cp - Copy files
cp myfile yourfile
Copy the files "myfile" to the file "yourfile" in the current working directory. This command will create the file
"yourfile" if it doesn't exist. It will normally overwrite it without warning if it exists.
cp -i myfile yourfile
With the "-i" option, if the file "yourfile" exists, you will be prompted before it is overwritten.
25
cp -i /data/myfile
Copy the file "/data/myfile" to the current working directory and name it "myfile". Prompt before overwriting the file.
cp -dpr srcdir destdir
Copy all files from the directory "srcdir" to the directory "destdir" preserving links (-poption), file attributes (-p option),
and copy recursively (-r option). With these options, a directory and all it contents can be copied to another dir
10. ln - Creates a symbolic link to a file.
ln -s test symlink
Creates a symbolic link named symlink that points to the file test Typing "ls -i test symlink" will show the two files are
different with different inodes. Typing "ls -l test symlink" will show that symlink points to the file test.
11. locate - A fast database driven file locator.
slocate -u
This command builds the slocate database. It will take several minutes to complete this command.This command must
be used before searching for files, however cron runs this command periodically on most systems.locate whereis Lists
all files whose names contain the string "whereis". directory.
12. more - Allows file contents or piped output to be sent to the screen one page at a time
13. less - Opposite of the more command
14. cat - Sends file contents to standard output. This is a way to list the contents of short files to the screen. It works
well with piping.
15. whereis - Report all known instances of a command
16. wc - Print byte, word, and line counts
17. bg
bg jobs Places the current job (or, by using the alternative form, the specified jobs) in the background, suspending its
execution so that a new user prompt appears immediately. Use the jobs command to discover the identities of
background jobs.
18. cal month year - Prints a calendar for the specified month of the specified year.
19. cat files - Prints the contents of the specified files.
20. clear - Clears the terminal screen.
21. cmp file1 file2 - Compares two files, reporting all discrepancies. Similar to the diff command, though the output
format differs.
22. diff file1 file2 - Compares two files, reporting all discrepancies. Similar to the cmp command, though the output
format differs.
23. dmesg - Prints the messages resulting from the most recent system boot.
24. fg
26
fg jobs - Brings the current job (or the specified jobs) to the foreground.
25. file files - Determines and prints a description of the type of each specified file.
26. find path -name pattern -print
Searches the specified path for files with names matching the specified pattern (usually enclosed in single quotes) and
prints their names. The find command has many other arguments and functions; see the online documentation.
27. finger users - Prints descriptions of the specified users.
free - Displays the amount of used and free system memory.
28. ftp hostname
Opens an FTP connection to the specified host, allowing files to be transferred. The FTP program provides
subcommands for accomplishing file transfers; see the online documentation.
29. head files - Prints the first several lines of each specified file.
30. ispell files - Checks the spelling of the contents of the specified files.
31. kill process_ids
kill - signal process_ids
kill -l
Kills the specified processes, sends the specified processes the specified signal (given as a number or name), or prints a
list of available signals.
32. killall program
killall - signal program
Kills all processes that are instances of the specified program or sends the specified signal to all processes that are
instances of the specified program.
33. mail - Launches a simple mail client that permits sending and receiving email messages.
man title
man section title - Prints the specified man page.
34. ping host - Sends an echo request via TCP/IP to the specified host. A response confirms that the host is
operational.
35. reboot - Reboots the system (requires root privileges).
36. shutdown minutes
shutdown -r minutes
Shuts down the system after the specified number of minutes elapses (requires root privileges). The -r option causes the
system to be rebooted once it has shut down.
37. sleep time - Causes the command interpreter to pause for the specified number of seconds.
27
38. sort files - Sorts the specified files. The command has many useful arguments; see the online documentation.
39. split file - Splits a file into several smaller files. The command has many arguments; see the online documentation
40. sync - Completes all pending input/output operations (requires root privileges).
41. telnet host - Opens a login session on the specified host.
42. top - Prints a display of system processes that's continually updated until the user presses the q key.
43. traceroute host - Uses echo requests to determine and print a network path to the host.
44. uptime - Prints the system uptime.
45. w - Prints the current system users.
46. wall - Prints a message to each user except those who've disabled message reception. Type Ctrl-D to end the
message.
28
Chapter-05
‘C’ language
C is a general-purpose, block structured, procedural, imperative computer programming language
developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating
system. It has since spread to many other platforms. Although C was designed as a system
implementation language, it is also widely used for applications. C has also greatly influenced many
other popular languages, especially C++, which was originally designed as an extension to C.
Philosophy
Its design goals were for it to be compiled using a relatively straightforward compiler, provide low-level
access to memory, provide language constructs that map efficiently to machine instructions, and require
minimal run-time support. C was therefore useful for many applications that had formerly been coded in
assembly language.
Despite its low-level capabilities, the language was designed to encourage machine-independent
programming. A standards-compliant and portably written C program can be compiled for a very wide
variety of computer platforms and operating systems with minimal change to its source code. The
language has become available on a very wide range of platforms, from embedded microcontrollers to
supercomputers.
‘C
‘ language is called middle level language. Justify why it is called so.
High level task
Low level task
High level syntax
Low level syntax
High level task : the task, which satisfies users need is called as high level task. So the high level
tasks are,




Game
Window media player
Ms-word
Accounts package
High level syntax : the syntax means the rules of grammar.
 the syntax, which is more English like.
 It is easier to represent the logic.
i.e. compiler, VC++, Java, .net etc.
low level task : the task, which satisfies systems need, is called as low level task. The
low level tasks are,
 communication between memory and processor.
 Communication between I/O devices and processor
 Managing the resourses
i.e. by the help of HLL user manages the hardware and software.
Low level syntax : the syntax, which is directly refers to the system components called low level
syntax.
‘C’ as a middle language combines advantages of both high and low level languages. It
provides advantages of high level languages to a low level programmer. Hence, It is
considered as the most powerful language in it’s category.
29
Use of languages :
To write a set of instruction for computer, such that computer can process and perform the desired
task to yield a desired result.
Definition of program :
A set of instruction arranged in a logical order to solve a specific problem is called program.
Instruction is the set of words or set of commands which meaning already given to our computer
system.



Program as a system :
Most program or set of instruction can be essentially devided into three inter-related and
integrated components :
input instructions
process instructions
output instructions
Input
instruction
Process
instruction
output
instruction
[Fig. : program as a system ]
Input instructions :
-
-
these are the instructions to active an specific physical input device such as keyboard, mouse,
etc. to capture data from external world.
Examples: scanf( ), gets( ), getchar( ), getch( ) etc.
In ‘C’ language input instructions are in the form of library defined functions.
Process instructions :
-
the instruction that processes the data captured by the input devices.
Internally, process instructions mostly activate internal components ( i.e. ALU, CU, FPU etc.) to
process data.
Examples : arithmetic operators, logical operators, constructs etc.
Output instructions :
-
these are the instructions, which activates the output hardware devices such as monitor, printer
etc. to give out the output.
Examples : printf( ), puts( ), putchar( ) etc.
In ‘C’ language output instructions are in the form of library defined functions.
DATA TYPE
Data type can be defined as a nomenclature of a unique data structure that stores an
unique type of data. Data type speaks about the size and pattern of data structure that is required
to store a specific type of data.
30
Types of Data Type
C supports three types of data types.
1. Primitive data type
2. Derived data type
3. User defined data type
1. Primitive data type:
- Primitive data types are atomic in nature. i.e. not further decomposable. It is otherwise called as hardwired datatype.
-primitive data types are data types provided by a programming language as basic building blocks.
Primitive types are also known as built-in types or basic types.
Depending on the language and its implementation, primitive types may or may not have a one-to-one
correspondence with objects in the computer's memory. However, one usually expects operations on
primitive types to be the fastest language constructs there are. Integer addition, for example, can be
performed as a single machine instruction, and some processors offer specific instructions to process
sequences of characters with a single instruction. In particular, the C standard mentions that "a 'plain' int
object has the natural size suggested by the architecture of the execution environment". This means that
int is likely to be 32 bits long on a 32-bit architecture.
Most languages do not allow the behaviour or capabilities of primitive types to be modified by programs.
Exceptions include Smalltalk, which permits primitive datatypes to be extended within a program, adding
to the operations that can be performed on them or even redefining the built-in operations.
Examples:
Int, char, float, double, void etc.
Integer:
- integer is represented in C language by using the keyword int
- integers are whole numbers with a range of values supported by a particular data types.
In order to provide some control over the range of numbers and storage space, C has three
classes of integer storage.
1. short int
2. int
3. long int
-
The sign qualifier are signed and unsigned. So the data types are,
1. signed short int
2. unsigned short int
31
3. signed int
4. unsigned int
5. signed long int
6. unsigned long int
signed
unsigned
int
unsigned int
short int
unsigned short int
long int
unsigned long int
[fig. : Representation format in ‘C’ language]
int :
-> integer is represented in ‘C’ language, by using the keyword int
-> int is by default signed.
-> it takes 2 bytes in turbo C and 4 bytes in ANSI ,GNU C, with left most bit as sign bit.
Here we take the example of 2 bytes.
1 bit
15 bits for
for sign bit
data bit
- the range of integer type of data is -32768 to
i.e. -2 15
+32767
0
+2 15 - 1
- If n-bit are there, then data stored in (n-1) bits & left most bit is resreved to store sign.
i.e. 0 for +ve
and
1 for –ve
- in case of integer, the –ve numbers are represented by using 2’s complement method.
Examples:
lets say n = 4
Sign bit
then, data bit = 3 i.e. n-1
left bit is sign bit
data bit
32
- if n-bits are true, then data stored in (n-1) bits and left most bit is reserved to store signs. i.e.0 for +ve
and 1 for –ve.
Sign bit
data bit
effect
0
all 0’s
0
0
0
0

+0
0
all 1’s
0
1
1
1

+7
1
all 1’s
1
1
1
1

-7
1
all 0’s
1
0
0
0

-8
As there is no 2’s complement of ‘0’ and 2’s complement of ( 1 0 0 0 )2 is ( 1 0 0 0 )2 , hence the range of
signed integer is,
- 2 n-1
to
+ 2 n-1
There are three methods to represent –ve numbers in memory.
1. sign magnitude method
2. 1’s complement method
3. 2’s complement method
Floating-point numbers :
A floating-point number represents a real number that may have a fractional part. These numbers are
stored internally in scientific notation, typically in binary but sometimes in decimal. Because floating-point
number have only a limited number of digits, most values can be represented only approximately.
Many languages have both a single precision (often called "float") and a double precision type.
Literals for floating point numbers include a decimal point, and typically use "e" to denote scientific
notation. Examples of floating-point literals are:




20.0005
99.9
-5000.12
6.02e23
Some languages have a complex number type comprising two floating-point numbers: a real part and an
imaginary part.
Characters and strings:
A character type (typically called "char") may contain a single letter, digit, punctuation mark, or control
character. Some languages have two character types, a single-byte type for ASCII characters and a
multi-byte type for Unicode characters.
Characters may be combined into strings. The string data can include numbers and other numerical
symbols but will be treated as text.
33
Literals for characters and strings are usually surrounded by quotation marks: often, single quotes (') are
used for characters and double quotes (") are used for strings.
Examples of character literals in C syntax are:




'A'
'4'
'$'
'\t'
Examples of string literals in C syntax are:



"A"
"Hello World"
"I am 30 years old"
CONTROL FLOW
The sequence in which each line of instruction gets executed is known as control flow i.e. the
statement is controlling the flow of execution of the program.
There are three forms of control flow.
 Sequential
 Conditional or branching.
 Iterative / Looping.
Sequential : Executing the statement one by one i.e. in sequence order.
Ex:
#include<stdio.h>
#include<conio.h>
int main( )
{
int a,b,sum;
printf(“enter two number : “);
scanf(“%d %d”,&a,&b);
sum=a+b;
printf(“After addition result is %d”,sum);
return 0;
}
Conditional or Branching : Depending upon a condition the system decide where the control goes
between alternative sequences.
-
if
34
-
switch
if -> Simple if
-> if ….else
-> if else if else
1) Simple if :
Syntax :
if (condition)
{
statement,
}
flowchart :
Condition
T
Statements
End
2) if …………..else.
F
Syntax :
If (condition)
T
{
statements ;
}
else
{
Statements;
}
35
Flowchart:
F
Condition
T
Statements
Statements
End
Ex : WAP to check a input whether it is odd or even
Algorithm :
Step –1 : Start
Step –2 : Take a number as input
Step –3 : Check the number is odd or even using modulus operator.
Step -4 : If condition true, then print “Odd” else print “even”
Step –5 : Stop
flowchart:
F
n%2!=0
T
odd
even
End
36
Program :
#include<stdio.h>
#include<conio.h>
int main ( )
{
int n;
clrscr ( );
printf (“enter a number: ”);
scanf (“%d”, &a);
if (n % 2 ! = 0)
{
printf (“Number is odd”);
}
else
{
printf (“ Number is even”);
}
Return 0;
}
3) if…………else if …………else :
This is used for multiway decision i.e. more than two alternative
Syntax :
if (condition)
Statements;
else
{
if (condition)
Statements;
else
statements;
}
37
Flowchart:
T
Condition
F
Statements
T
statements
Condition
sssssssStatements
F
Statements
Statements
End
Ex : Write a gradation program, where 3 subject marks are given.
#include<stdio.h>
#include<conio.h>
int main ( )
{
int m1, m2, m3 tot;
float avg;
char grade;
clrscr ( );
printf (“ enter 3 marks”);
scanf (“%d %d”, &m1, &m2, &m3);
tot =m1 + m2 + m3
avg = (float) tot/ 3;
if (avg < 50)
grade = ‘F’;
else if (avg < 55 avg > = 50)
grade = ‘D’
else if (avg > = 55 avg < 65)
grade = ‘C’ ;
else if (avg > = 65 avg < 75)
grade = ‘B’
else if (avg > = 75 avg < 85)
38
grade = ‘A’
else
grade = ‘S’
printf (“grade is % c”, grade);
return 0;
}
Switch….case
-
It is case control statement.
Switch case used to choose a statement among several alternatives.
Switch variable must be integer or character type, not any fractional number.
Syntax :
switch (variable)
{
case value 1 :
statements;
break;
case value 2 :
statements;
break;
.
.
.
default :
statement;
break;
}
Flow chart :
condition
Case value 1
Statements
Case value 2
Statements
(no match) default
Statements
Ex :
int main ( )
39
end
{
int i = 2
switch (i)
{
case 1 :
printf (“ I am in case 1”);
break;
case 2 :
Printf (“I am in case 2”);
break;
case 3 :
Printf (“ I am in case 3”);
break;
Default :
Printf (“I am in default case”);
}
return 0;
}
Output :
I am in case 2
Looping :
Repetative execution of a statement or statement block, till the condition is false is called looping.
Components of Loop :
Basic components of loop constructs are ,
- Initialization
- Condition
- Change of value
Various constructs used to archieve itterativeness in ‘C’ program are :
(1) While
(2) For
(3) Do…. While
While :
Syntax :
initialization ;
while (condition)
{
Statements;
Change of value ;
}
40
Ex. :
1) a = 3
while (a)
{
printf (“Hello”);
}
output : infinite loop
2) a = 5
while (a>3)
{
printf (“Hello”);
a - -;
}
output : 2 times print Hello
3) Float a = 6.22;
While (a)
{
printf (“Hello”);
a--;
}
output : Infinite loop
4) i = 0
while (i < 3)
printf (“%d”, i ++);
output : 0 1 2
5) a = 5;
while (++a < 10) printf (“%d”, a);
output : 6 7 8 9
For
Syntax :
for (initialization ; condition ; change of value)
{
Statements;
}
41
Example :
1) For (a = 1, b =5 ; a < 5, b > 0; a++, b - - );
printf (“% d % d”, a, b);
output = 5 1
2) i = 0
for ( ; ; )
{
if (i < 10)
i++;
else
break ;
printf (“%d”, i);
}
Output : 1 2 3 4 5 6 7 8 9 10
2) for ( i =1; i < 10; i ++)
{
printf (“%d”, a) ;
}
output : 1 2 3 4 5 6 7 8 9
3) for ( ; a < 10; )
{
printf (“%d”, a);
a + +;
}
output : 1 2 3 4 5 6 7 8 9
4) for ( n = 3245; n > 0; printf (“% d”, n = n / 10));
42
output = 324
32
3
do while
syntax :
do
{
Statements;
}while (condition);
Ex :
int a =5;
do
{
printf (“%d”, a);
} while (a>10);
output : 5
43
Chapter-06
PROBLEM SOVING TECHNIQUE USING ‘C’
1. Analyse the problem, then classify the problem into systems format i.e. input, process
and output.
2. Take input to validate the problem.
3. Use lock and key method to solve the process part of the model.
4. Translate the solved problem model into computer language model / program.
5. Test the program into the light of accuracy and efficiency.
6. If found some difficulties, then estimate the problem and start from step-1 again.
Examples : 1 Prime Number
Step –1 : Prime no. is a number, which is divisible by 1 and by itself and no by any.
Step –2:
5%1=0
6%1=0
5%2=1
6%2=0
5%3=2
6%3=0
5%4=1
6%4=2
5%5=0
6%5=1
6%6=0
Any prime number have only two zero because Prime Number is divisible by 1 and
by itself only. So here 5 is the prime no. and 6 is not prime.
Step –3 :
num I
rem
5 % 1 =0
I.
5 % 2 =1
5 % 3 =2
5 % 4 =1
5 % 5 =0
Program Analysis I.
Program Analysis II.
44
for (i = 1; i < = num, i ++)
int flag = 0;
{
For (i = 0; i < num; i ++)
rem = rem % i ;
{
if (rem = = 0 )
if ( num % c = = 0 )
flag = 1 ;
count++;
break ;
}
if (count = = 2)
printf (“Prime”);
}
if (flag = = 1)
print “not Prime”
else
printf (“not prime”);
else
print “prime”
In program Analysis II,Here we can use a flag. Flag is used to show the status.
A disable flag has to two status.
-
0
-
1
Demerit : there unnecessarily we have to take a flag variable.
Program Analysis III.
In program analysis II, two conditions are use to break the loop. Those are ,
 i < num
 num % i = = 0
So, instead of 2 condtions we can accommodate only are condition.
for ( i = 2 ; num % i ! = 0 ; i ++);
num = =i ? printf (“prime”) : printf (“not prime”);
Step – 4: Translate the solved problem into comp. Language.
45
Step- 5: Test it
Examples and Analysis – 1
Example 1- Fibonacci Series :
0
1
1
2
3
5
8
13
21
34
55….
Analysis :
To generate fibonacci series
 We have to take two integer is a = 0 & b = 1
 Addition of a & b stored inside c.
 Print the value of c
 Then assign the value of b to a and value of c to b
a
+
b
=
c
0
1
1
1
1
2
1
2
3
2
3
5
3
5
8
so it will print :
1
2
3
5
8
13 …….
But this is not a complete series. To find that series, we have to take that two number,
a = -1 b =1
Now, we can get 0
1
1
2
3
5
8
13
21……
46
# include < stdio.h>
# include < conio.n>
Void main ( )
{
int i , num;
clrscr ( );
printf (“enter a no”);
scanf (“% d”, & num);
for ( i = 2; num % I 1= 0; i ++);
(num = = I) ? printf (“prime”) : printf (“not prime”);
gutch ( );
}
Algorithm :
Step 1 :
Start
Step 2 :
Take all variables and take input for nth turm.
Step 3 :
Assign a = -1 and b =1 & i = 1
Step 4 :
Calculate c = a + b
Step 5 :
Assign value of b to a and value of c to b
Step 6 :
value of i incremented by 1
Step 7 :
Repeat step 4 and step 6 until i < = n
Step 8 :
Stop
Programme :
#include<stdio.h>
#include<conio.h>
int main ( )
{
int a = -1, b = 1, n, i;
clrscr( );
printf (“entur nth term”);
scanf (“%d”, &n);
for ( i = 0; i < n ; i ++)
{
c=a+b;
a=b;
47
b=c,
printf (“ % d”, c) ;
}
return 0;
}
Example 2- Summation Series :
Analysis :
Add from 1 to n
i.e. 1 + 2 + 3 + 4 + 5 + ………………n
 We have to take two integer is a = 1 & b = 2
 Addition of a & b stored inside c.
 Finally it will print the value of c.
a + b = c
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
10 + 5 = 15
15 + 6 = 21
21 + 7 = 28
:
n
so we can write,
a = 1, b = 2
c=a+b
a =c
print c
i.e. initially we can take a = 1 & b = 2 and calculate c = a + b; and print value of c.
Result of c assign to a
Frequency of b change by 1 i.e. here value of b is progressive by frequency base is b ++.
48
a=1
for ( b = 2 ; b < = n , b ++)
{
printf (“ % d”, a);
c=a+b;
here to avoid the redunancy we can use a = a + b
a=c;
}
Algorithm :
Step 1 :
Start
Step 2 :
Take all variables and take input for nth turm.
Step 3 :
Assign a = 1 and b =2
Step 4 :
Print the value of a.
Step 5 :
Calculate c = a + b
Step 6 :
Addition of a and b assign to a
Step 7 :
value of b incremented by 1
Step 8 :
Repeat step 4 and step 6 until b < = n
Step 9 :
Stop
Program :
#include<stdio.h>
int main ( )
{
int a, b , n ;
clrscr ( );
printf ( ‘enter the nth term”);
scanf (“ %d” , &n );
for (a = 1, b =2 ; b < = n; b ++)
{
printff (“ % d + “, a) ;
a=a+b;
}
return 0 ;
}
Example 3-
Multiple Series
49
Analysis 1:
5*4*3*2*1
->Here, initially we can take a = n & b = n – 1.
And here n=5
-> After multiply a and b the result of multiplication again assign to a
-> Frequency of b is decrement by 1.
-> These instructions are reputably execute until b > 1 .
a * b = a
5 * 4 = 20
20 * 3 = 60
60 * 2 = 120
120 * 1 = 120
a=n b=n–1
for ( b = n – 1; b > 1 ; b - - )
{
a = a * b;
}
Program :
# include < stdio.h>
int main ( )
{
int a, b, n ;
clrscr ( ) ;
printf (“enter nth term”);
scanf ( “ % d”, & n) ;
for ( a = n, b = n – 1; b > 1 ; b - - )
{
a=a*b;
}
printf (“ summation of multiplicative series is % d” , a) ;
return 0;
}
50
Analysis –2
Analysis – 3
1 *2*3*4*5
5*1*2*3*4
1*2=2
5*1=5
2*3=6
5 * 2 = 10
6 * 4 = 20
10 * 3 = 30
20 * 5 = 120
30 * 4 = 120
EXPRIMENT- 1
Q. 1.Write a program to generate all the prime numbers between 1 to n, where n is a value supplied
by the user.
Q. 2. WAP to calculate the following sum :
Sum = 1 – x2/ 2 ! + x4 / 4 ! + x6 / 6 ! + 8 / 8 ! – x10 / 10 !
Q. 3. Write a c programme to find the roots of a quadratic equation.
Example and Analysis - 2
Example-1: WAP TO REVERSE A NUMBER
1258  8521
ANALYSIS :
To find the reverse number, a number should be taken as input
Let n = 1258.
 Here the last digit becomes first i.e. we have to pick the last digit and store in another variable as
first and so on.
 To pick the last digit, modules operator should be used.
 This process should be done until n > 0.
8 = 1258 % 10
5 = 125 % 10
2 = 12 % 10
1 = 1 % 10
rev = rev * 10 + 8
rev = rev * 10 + 5
rev = rev * 10+2
rev = rev * 10 + 1
125 = 1258 / 10
12 = 125 / 10
1 = 12/10
0 = 1/ 10
51
Algorithm :
Step –1 : start
Step –2 : Take all variable like n, r, rev
Step – 3 : take input for n & assign rev = 0
Step – 4 : Calculate Reminder,
i.e. r = n % 10
Step – 5 : Store this r inside rev
i.e. rev = rev * 10 + r
Step – 6 : Now change the value of n
i.e. n = n / 10;
Step – 7 : Repeat step 4 to step 6 until n > 0
Step – 8 : Stop
Program:
#include<stdio.h)
int main ( )
{
int n, rev = 0, r,
clrscr ( ) ;
printf (“ enter and number”);
scanf (“%d”, & n);
while ( n > 0)
{
r = n % 10;
rev = rev * 10 + r ;
n / 10;
}
printf (“Reverse no. is % d”, rev);
getch ( );
}
EXPERIMENT-2
1. WAP to count the number of digit in a number.
2. WAP to find the number is pallendrium or not.
3. WAP to split a number into two parts from a given position and reverse each part, then join.
4. WAP to remove the second occurrence of a given digit.
5. WAP to insert a multi digit number from a given position of a number.
6. WAP to find prime digit of a number.
7. WAP to find the prime number present within a number.
8. WAP do delete prime numbers within a number.
52
Chapter-07
FUNCTION
Function is a set of instruction, which is design to accomplish a particular task.
Components of a function.
Ex. :
-
Function prototype
-
Function call
-
Function definition.
#include<stdio.h>
int add (int , int ) ;
// function prototype
int main ( )
{
int a, b, c ;
clrscr ( );
printff (“enter value for a & b”);
scanf (“ % d % “d”, & a, & b);
c = add (a , b)
// function call
actual argument
printff (“Addition Result is % d”, c);
return 0 ;
}
int add (int a, int b)
// function definition
{
int res;
formal argument
res = a + b ;
return (res);
}
Function prototype :
Prototype is a function declaration statement which performs the following activity. It
reflects our plan to frame the function.
-
It presets the no. of arguments and their type.
-
It presets the return type.
-
It declares the function name.
53
Argument :
-
Argument(s) is/ are the parameter(s) that are passed from calling function to called
function.
-
Arguments are two types.
* Actual argument
* Formal argument
Actual Argument
Formal Argument
- Arguments that are passed in - Arguments that are present in header
calling function is called actual of called function is known as formal
argument
argument.
- Actual argument could be - formal argument must be unit variable
constant, expression or any unit only.
variable.
- Actual arguments are assigned to - formal arguments are assigned by the
formal argument one-to-one or actual arguments one to one basis.
onto basis.
Returns :
-
the parameter that is passed from called function to calling function is called as return.
-
Function can return only one value (the value could be referential or non-referential).
-
Function can accept many arguments but returns only one value.
Types of function :
Function is of two types.
-
Library function.
-
User defined function.
Library function
Prototype
User defined function
Written inside header file by Written by the user
vender
Function call
By user
By user
Function definition
Inside library file
By user.
54
Header file :
-
Header file is a file with an extension . h
-
It is a collection of prototypes of related functions.
-
The default path, where header file are located is \ tc \ include \
-
While need to use any library function we must include the header file in which
respective function prototype is declared.
-
We use the preprocessor directive is #include for including the header file to user source
file.
Library file :
-
Library file is the file, which collects, the definition part of the function .
-
The extension of library file . lib
Ex :
math . lib
graphics. lib
-
The default path of library fie is \ tc\ lib \
-
These files are linked to the source program by the help of a program called linker.
-
Files are in the form of pre-complied object file.
Types of user defined function :
User defined functions are 4 types .
 Return type having argument
 Return type having no argument.
 No return type having argument
 No return type having no argument.
Ex : Return type having argument :
#include<stdio.h>
int add (int , int ) ;
int main ( )
{
int a, b, c;
clrscr ( ) ;
printf (“ enter value for a and b”);
scanf (“% d % d”, &a, &b);
55
c = add (a , b);
printf (“Result is % d”, c);
return 0 ;
}
int add (int a, int b )
{
int res ;
res = a + b ;
return (res) ;
}
Ex: Return type having no argument :
#include<stdio.h>
int add (void) ;
int main( )
{
int c ;
c = add ( ) ;
printf (“ Result is % d”, c );
return 0 ;
}
int add (void)
{
int a, b, c ;
clrscr ( ) ;
printf (“ enter value for a and b”);
scanf (“ % d % d” , &a , &b ) ;
c = a + b;
return (c) ;
}
56
Ex: No return type having argument :
#include<stdio.h>
#include<conio.h>
void add ( int , int ) ;
int main ( )
{
int a, b ;
clscr ( );
printf (“enter value for a and b”);
scanf (“ % d % d”, &a, &b);
add (a , b);
return 0;
}
void add ( int a , int b)
{
int c ;
c=a+b;
printf (“ Result is % d” , c) ;
return;
}
Ex: No return type having no argument :
#include<stdio.h>
#include<conio.h>
void add (void);
int main ( )
{
clrscr ( );
add ( ) ;
return 0 ;
}
void add (void)
{
57
int a, b, c ;
printf (“enter value for a and b”)
scanf (“% d % d”, &a , &b);
c=a+b;
printf (“ Result is % d” , c) ;
return;
}
main ( )
User Define Function ( )
Return type having arguments.
IO
P
Return type having no arguments.
0
IP
No return type having arguments.
I
PO
No return type having no arguments.
-
IPO
RECURSION:
f( )
f1( )
f2( )
{
{
{
}
int a;
int a;
f1( );
f2( );
return;
return;
}
int a;
return;
}
[fig:: call executed in cascade manner]
total space = total space taken by code + total space taken by data
Recursion is a process of cyclic call by a function to itself.
In the process of recursion, the code part is not going to be replicated in each call, where as data part
is going to be replicated at each call..
58
ANALYSIS:
Sum of two numbers
a
b
5
4
6
3
7
2
8
1
9
0
Iteratively
a = 5, b=6;
while(b!=0)
{
a++;
b--;
}
printf(“%d”,a);
Recursively
initilisation
condition
Change of value
add( a, b);
int add(int a, int b)
{
if(b= =0)
return(a);
else
add( a+1, b-1);
}
program:
FACTORIAL OF A NUMBER USING RECURSIVE FUNCTION
#include<stdio.h>
int main( )
{
int n;
long int fact;
printf("enter the no.: ");
scanf("%d",&n);
fact=factorial(n);
printf("the factorial number is %d",fact);
getch( );
}
long int factorial(a)
{
if(x= =0)
return(1);
else
return(x * factorial(x-1));
59
}
EXPERIMENT- 3
Write C programs that use both recursive and non-recursive functions.
Q. 1. To generate the Fibonacci seriesusing recursive function.
Q. 2. To find the GCD (greatest common divisor) of two given integers.
Q. 3. To solve Towers of Hanoi problem.
Q. 4. To find the multiplication of two number.
60
Chapter-08
POINTER
Pointer
Destinition
location
Source
location
If we analyse above picture we can find that, this object is pointing towards a location from a
specific location . In brief, pointer is pointing from a source location towards target location.
When we declare
int a = 5;
This declaration tells to the compiler,
 to allocate location for integer variable named as a.
 put the value 5 in that location.
 compiler choose the address 255 for a.
name of variable
a
Valueofvariable
5
255
Address
of
variable.
(Fig : Description of allocation)
What is a pointer ?
Pointer can be defined as a special type of variable, that stores the address of another
variable of it’s type.
In other words, the location which points to another location by storing its reference is known
pointer.
61
Referential data Vs. Non-Referential data
Referential Data : The type of data which is used to reference an object or location is called as
reference data.
For ex : Address of house, address of allocation etc.
Non-reference Data : The type of data which denotes the value of an entity is called as nonreferential data.
For Ex : Weight of a person, name of a person, price of an object etc.
NOTE: Pointer location stores only referential data and non-pointer or primitive locations used to
store only non-referential data.
Assignment of content of one location to another location :
int a, b = 10
a = b;
Here, by using assignment operators, content of b is assigned to of a .
Assignment of address or reference of one location to another location :
This operation involves three another sub operations.
(i)
Extraction of reference or Address.
(ii)
Declaration a location as a pointer location.
(iii)
Assignment of reference or address to the pointer location.
(i)
Extraction of reference or address :
Extraction of reference or address of a location can be done by using an unary operator ‘&’
int a = 10;
a
Name the location
10
Content of Location
50
Address of the location
a  10
& a  50
(ii)
Declaration of a location as a pointer location :
As primitive location can store only non-referential data, hence, location that can store address or
reference of another location must be differentiated from previous type of location.
Hence , the symbol * is used to mark a location as pointer while declaration.
int a ;
// primitive declaration
62
int * pvt ;
// pointer declaration
Note :
In the line of declaration, the symbol * should be treated as a mere symbol to distinguish
from a primitive location, and should not be treated as an operator.
(iii)
Assignment of Reference or address a location to a pointer location:
int a = 10;
int * pt = &a
This operator extracts the address of a and
assigns the address of a to pointer pt.
NOTE: The generic Data type of pointer is unsigned int.
int a , *it ;
// here a occupies 2 byte inside memory so, it pointer points to a location which
binds 2 bytes.
float f , *ft ; // here ft pointer points to a location which binds 4 bytes.
Labels of pointer :
a
pt
pt1
5
100
200
100
200
300
L0
L1
L2
pt2
300
400
L3
Level 0 (L0) – Normal Variable ( a )
Level 1 (L1) – First level pointer ( *pt )
Level 2 (L2) – Second level pointer ( **pt1)
Level 3 (L3) – Third level pointer ( ***pt2)
Call by value Vs. Call by Reference :
Call by value : When we are passing value to a function, called call by value.
Void swap ( int a, int b );
int main ( )
{
int a = 10, b = 20;
swap (a, b) ;
pintf (“%d %d”, a ,b) ;
63
return 0;
}
void swap (int a , int b)
{
int t ;
t = a;
a=b;
b = t;
return ;
}
Output :
a = 10
b = 20
Call by Address : when passing address or reference through a function, called Call by reference.
Void swap ( int *a , int *b) ;
int main ( )
{
int a = 10, b = 20;
swap ( &a , &b) ;
printf (“%d %d”, a , b)
return 0 ;
}
void swap ( int *a , int *b)
{
int t ;
t = *a ;
*a = *b;
*b = t ;
return;
}
Output :
a = 20
b = 10
64
int a, b, c, d;
a
b
c
d
10
50
60
70
100
325
220
155
In the above diagram, no logical co-relation exists between the variables.
But,
10
12
14
16
18
here, some logical co-relations present i.e. if we get address of first location, then we
can retrieve all related address data. We can get these location by using,
int ar [5];
In the above declaration, ar is a constant base pointer, unlike xt, which is a variable pointer.
Hence, any attempt to apply arithmetic operation on the base pointer, will produce the error
”L Value Required”.
If we need large number of data to store, then we need large number of variables, to store in case of
normal declaration.
Foe ex:
int a,b,c,d,e,……….
Scanf(“%d %d %d %d…….”,&a,&b,&c,&d,…….);
Which is quite impractical.
Again, we will go by the next method
int i,a;
for(i=0;i<1000;i++)
scanf(“%d”, &a)
then only last input data will exist in a. That means we can not store distinct data in the above
procedure also. But, through increment of pointer, we can input and output the distinct datas.
65
Input using Pointer :
for (i = 0;(xt + i) <(xt + 4) ; i + + )
{
scanf (“ % d” , xt + i ) ;
}
Or
for(i = 0; i < 4 ;i++)
{
scanf(“%d”, &a[i]);
}
Output using address / pointer :
for (i = 0; (xt + i) < (xt + 4) ; i + + )
{
printf (“ % d” , * (xt + i )) ;
}
Or
for (i = 0; i < 4 ; i + + )
{
printf (“ % d” , a[i] ) ;
}
what is an array ?
An array is a sequenced collection of elements of the same data type.
Types of array :
1. One-dimensional array.
2. Two-dimensional array.
3. Multi-dimensional array.
One-dimensional array:
Declaration:
Index / subscript
int a[8];
array name
66
0
1
2
3
4
5
6
7
10
12
14
16
18
20
22
24
Base address of array
Array name itself is a base pointer and points consistantly to the first location and can not be subject
to change.
To get the effective address,
EA = Base address + position * sizeof(datatype)
A single student have ,
Number of semistar = 7
Paper per semistar = 6
Total number of paper = 7 * 6 = 42 papers
We need to store the 42 papers mark. So here we required one-dimensional array.
int stud[42];
Insertion in any array :
0
10
1
2
3
4
5
6
20
30
40
50
60
70
7
8
9
Insertion operation are possible
 After the position
 Before the position.
Deletion operation are possible
 delete the position
67
Analysis
Ex : 45 insert after position 3
i.e. element are shifted from POS 3 to the last element.
0
10
1
2
3
4
5
6
20
30
40
50
60
70
7
8
9
i.e. element shifted from n to position.
a [i] = a [ i-1];
0
10
1
2
3
20
30
40
4
5
6
7
50
60
70
8
9
for ( i = n ; i > PO ; i - - )
{
a (i) = a [ i-1];
}
a [i] = el ;
How to enter data in 2D
0
1
2
3
0
00
01
02
03
1
10
11
12
13
2
20
21
22
23
3
30
31
32
33
For (i = 0; i <n; i + +)
{
for (j=0; i < n ; j + +)
scanf (“%d”, & a [i] [i] ); }
68
How to write data from 2D
for (i = 0; i < n ; i + +)
{
for ( j=0; j < n ; j + +)
printf (“%d”, a (i) (i)];
}
EXPERIMENT- 4
1. Write a program to find both largest and smallest number in a list of integers.
2. Write a program to add all the prime number in an array.
3. Write a program to search an element from an unsorted array.
4. Write a program to find the occurances of an element in an array.
5. Write a program that uses functions to perform the following:
a) Addition of two matrix
b) Multiplication of two matrix
c) Norm of matrix
d) Diagonal of matrix
e) Row sum and column sum of matrix
f) Transpose of matrix
g) Symmetrical matrix
69
What is a string ?
Array of characters, terminated with a terminal character i.e.‘/0’ (NULL)
character is known as string.
How string is different than array of characters ?
- Array of character may or may have ‘/0’ character. But, string is a array of characters must
terminate with NULL character.
- All strings must be array of character, but all array of characters may not be string.
Input/ Output Procedure for string :
Input/ Output procedure for a string is different then input/ output for other type of data in the aspect.
 In case of other type of data, only one value can be input or output for input/ output function.
Whereas in case of string, chain of data can be input or output with single input/ output function .
Ex : Normal data
Array data
scanf (“ %d”, & a) ;
scanf (“%s”, st) ;
 List of input/ output functions specially works for string.
-
formatted I / O
Ex : % s with printf ( ) and scanf ( )
-
Unformatted I/O
Ex ; gets ( ) for input
puts ( ) for output
How gets ( ) different from scanf ( )
% s specifier with scanf ( ) terminate with space or return key. Where as gets ( ) termintes only with
return key.
Hence, with scanf (“%s”) strings without space can be entered, where as with gets string with
space can be entered.
Ex :
char st [ 20];
Printff (“enter your name”);
gets (st);
70
Analysis of word search program
Procedure :
Step –1 : Take a main string
Step –2 : Take a sub string.
Step –3: Search that sub string within main string.
-
Take first world from main string as a string, the compare with sub string using
strimp ( ) / using UDF.
-
This procedure continue till the end of the string.
Step –4 : If found print message “String found” else print message “String not found”.
Step –5 : end
Main string Str
0
1
2
3
A
J
A
Y
4
5
6
7
8
9
K
U
M
A
R
10
11
12
13
14
15
D
A
S
H
‘/0’
Sub string st
0
1
2
3
4
5
K
U
M
A
R
‘/0’
for (pt=st, i = 0;’ str [i] ! = ‘/0’; i ++)
{
if (str [i] = = ‘/0’ || str [i+1] = = ‘/0’ )
{
if (str [i +1] ! = ‘/0’)
st [i] = ‘ /0’;
}
if (strcmp (substr, pt) = = 0)
{
f=1;
st [i] = ‘ ‘ ;
break;
71
}
pt = st + i + 1;
}
EXPERIMENT-5
1. WAP to find the length of a string.
2. String copy.
3. String concatenation.
4. string reverse.
5. string pallinedrium.
6. Mirror Image of a string.
7. Each word reverse.
8. World search.
9. Finding occurrence of a word.
10. Word count.
11. Name abbreviation.
12. Pattern matching.
13. Scrolling morque.
14. Word insert / delete.
15. Finding occurrence of a world in a sentence.
EXPERIMENT - 6
1.Write a program to construct a pyramid of numbers.
2. Write a program to count the lines,words and characters in a given text.
72
Chapter -09
STRUCTURE
Suppose you want to store information about a student. In such case the arrays are not useful
because personnel information data is never homogeneous.
Ex: name, roll_no, marks,class
Here the name and class are character strings, where as rool_no,marks are numerical
quantities.
‘C’ provides a facility called as structure. Array provide the facility of grouping homogenous
data items into a single object.
Structure is nothing but simple if is a frame.
There are two types of structure.
-
System defined.
-
User defined.
System defined structure : The size and pattern of data is defined by the system.
Ex : int, char, float, double etc.
User Defined Structure : The size and pattern of data is defined by the user.
Structure is the User defined data structure / multimember structure.
Syntax :
Struct <structure name>
{
data members;
};
1) Struct stud definition :
Ex : Struct stud data type
{
char name [20];
char roll [10];
definition of data structure/ struct stud
int mark1, mark2;
float per; }
73
2) Struct stud storage pattern:
name
roll
mark, marks pur
EXPERIMENT-7
1.Write a program that uses functions and structure to perform the following operation:
a) Addition, Substraction, Multiplication of two complex number.
b) Operation with Date and Time
c) Write a program to store the Examination related information and create provision
to search the desired record by entering Roll. No.
d) Write a program to sort records on the basis of name.
74
Chapter-10
FILE HANDLING
Till today we are working with volatile memory i.s. RAM After executing the
program, your variable reserve some location. And after re-executing the program, that
memory is free and again it referess and reserve new location.
Due to volatile problem, the information can store permanently in a disk for back up.
For back up user can use. Hard disk, flash memory.
File I/O (How input/output function works in File )
Memory is one dimensional and buffer is the part of memory. So, buffer is nothing, simply it
is an array.
There are some standard buffer provided by c language. These are,
-
Stdin
-
Stdout
-
Stdprn
-
Stderr
-
Std aux
Write operation :
Keyboard  Memory (RAM)  Disk
75
-
Read Operation :
Disk  Memory (RAM)  VDU
Some functions associated with file handling :
1. fopen ( ) : It opens a file.
Syntax :
File pointer = fopen (“file name”, “mode”);
-
It opens the file as per mode type.
Mode : 1.
read (r)
4. Read and write (r+)
2.
write (w)
5. write and read (w+)
3.
append (a)
6. (a+) append
Ex :
FILE * fp;
fp = fopen (“ myfile. Txt” , “w“);
this statement will open a file named as myfile.txt in write mode. If compiler open that
file successfully then, fopen ( ) returns address of myfile.txt to fp, else return NULL to
fp. Information regarding the file i.e. fd, *buffer, *curp etc. are stored inside file
structure.
2. File Read :
int a ;
scanf (“ %d”, &a);
fscanf or (stdin , “%d”, &a);
scanf ( ) working for common buffer. So it couldn’t required the file pointer.
FILE * fp;
fp = fopen (“my file”, “r +”);
76
Analysis
WAP which copies one file to another
1. Process of writing into a file
Keyboard 
(i)
Memory 
File
Scanf ( )
fprintf ( )
Gets ( )
fputc ( )
Getchar ( )
fputchar ( )
File must be open first
FILE * fp;
fp =fopen (“myfile” , “W”);
(ii)
Read from Keyboard while encounter EOF
While () ch = getchar ( ) ) ! = EOF)
{
fputc (ch, fp);
}
2. Reading a file
File

Scanf ( )
Memory 
VDU
fprintf ( )
fgetc ( )
(i)
File must be open first in read mode file & * fp;
fp = fopun (“myfile”, “r”);
(ii)
Read from file and write in VDU
While (( ch = fgetc (fp)) ! = EOF)
{
putchar (ch);
}
(iii)
Close that file
Fclose (fp);
3. Process of copy file
77
(i)
Open myfile in read mode and your file in write mode.
fp1 = fopen (“myfile”, “r”);
fp2 = fopen (“yourfile”, “w”);
(ii)
Read characters from my file and write into your file.
While ( ( ch = getc (fp) ! = EOF)
{
fputc ( ch, fp1) ;
}
Algorithm :
Step –1 : Start
Step –2 : Open a file myfile in ‘W’ mode.
Step-3: Write into myfile
Step – 4 : Close myfile
Step- 5 : Open file myfile in ‘r’ mode
Step –6 : Open file f2 in ‘W’ mode
Step-7 : Copy f1 to f2
Step-8 : Close f1 and f2
Step –9 : Open file f2 in ‘r’ mode
Step – 10 : Read file f2
Step – 11 : Close f2
Step – 12 : end
Program:
#include<stdio.h>
#include<conio.h>
int main ( )
{
FILE * fp, *fp1;
fp = fopun (“myfile”, “w”);
while ((ch = getchar ( ) ) ! = EOF)
{
fputc (ch, fp);
78
}
fclose (fp);
fp = fopun (“myfile”, “r”);
fp1 = fopun (“yourfile”, “w”);
while ( ( ch = getc (fp)) ! = E OF)
fptc (ch, fp1);
fclose (fp);
fclose (fp1);
fp = fopun (“yourfile”, “r”);
while ( ( ch = getc(fp)) ! = EOF)
putchar (ch);
fclose (fp);
return 0;
}
EXPERIMENT- 8
1) WAP to revere the first n characters in a file.
2) Remove all ; from your program file
3) Write a program to concanat two files
79
APPENDIX-1
C Keywords
asm
auto
bool
break
case
char
const
const_cast
continue
default
delete
do
double
else
enum
extern
false
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
true
typedef
union
unsigned
void
volatile
while
insert an assembly instruction
declare a local variable
declare a Boolean variable
break out of a loop
a block of code in a switch statement
declare a character variable
declare immutable data or functions that do not change data
cast from const variables
bypass iterations of a loop
default handler in a case statement
make memory available
looping construct
declare a double precision floating-point variable
alternate case for an if statement
create enumeration types
tell the compiler about variables defined elsewhere
the Boolean value of false
declare a floating-point variable
looping construct
jump to a different part of the program
execute code based off of the result of a test
declare a integer variable
declare a long integer variable
request that a variable be optimized for speed
return from a function
declare a short integer variable
modify variable type declarations
return the size of a variable or type
create permanent storage for a variable
define a new structure
execute code based off of different possible values for a variable .
the boolean value of true
create a new type name from an existing type
a structure that assigns multiple variables to the same memory location
declare an unsigned integer variable
declare functions or data with no associated data type
warn the compiler about variables that can be modified unexpectedly
looping construct
80
Appendix-2: Operator Precedence
Operator precedence describes the order in which C reads expressions. Operators higher in the chart
have a higher precedence, meaning that the C compiler evaluates them first. Operators on the same
line in the chart have the same precedence, and the "Associativity" column on the right gives their
evaluation order.
Operator Precedence Chart
Operator Type
Operator
Associativity
Primary Expression
Operators
() [] . ->
left-to-right
Unary Operators
* & + - ! ~ ++expr --expr (typecast)
sizeof()
right-to-left
Binary Operators
* / %
left-to-right
+ >> <<
< > <= >=
== !=
&
^
|
&&
||
Ternary Operator
?:
right-to-left
Assignment Operators
= += -= *= /= %= >>= <<= &= ^= |=
right-to-left
Comma
,
left-to-right
81
82
Download