C Programming Lecture Notes 1
C Programming Lecture Notes 1
SYLLABUS
Programming in C BS-106
Unit – I
Computer Fundamentals: Introduction of Computers, Classification of Computers, Anatomy of a
Computer, Memory Hierarchy, Introduction to OS, Operational Overview of a CPU.
Program fundamentals: Generation and Classification of Programming Languages, Compiling,
Interpreting, Loading, Linking of a Program, Developing Program, Software Development.
Algorithms: Definitions, Different Ways of Stating Algorithms (Step-form, Pseudo-code, Flowchart),
Strategy for Designing Algorithms, Structured Programming Concept.
Basics of C: Overview of C, Developing Programs in C, Parts of Simple C Program, Structure of a C
Program, Comments, Program Statements, C Tokens, Keywords, Identifiers, Data Types, Variables,
Constants, Operators and Expressions, Expression Evaluation–precedence and associativity, Type
Conversions.
Unit – II
Input-Output: Non-formatted and Formatted Input and Output Functions, Escape Sequences, Control
Statements: Selection Statements – if, if-else, nested if, nested if-else, comma operator, conditional
operator, switch; Iterative Statements–while, for, do-while; Special Control Statement–goto, break,
continue, return, exit.
Arrays and Strings: One-dimensional Arrays, Character arrays, Functions from ctype.h, string.h,
Multidimensional Arrays.
Unit – III
Functions: Concept of Function, Using Functions, Call-by-Value Vs Call-by-reference, Passing Arrays to
Functions, Score of Variables, Storage Classes, Inline Functions, and Recursion.
Pointers in C: Introduction, Address of Operator (&), Arrays and Pointers, Pointers and
Strings, Pointers to Pointers, Array of Pointers, Pointer to Array, Dynamic Memory Allocation.
Unit – IV
User-defined Data Types: Declaring a Structure (Union) and its members, Initialization Structure
(Union), Accessing members of a Structure (Union), Array of Structures (Union), Structures Vs Unions,
Enumeration Types.
Files in C: Introduction, Using Files in C, Working with Text Files, Working with Binary Files, Files of
Records, Random Access to Files of Records, Other File Management Functions.
Silent Features
1. Complete Syllabus Covered According to the latest CBCS
Syllabus.
This book is devoted to practical C programming. C is currently the premier language for
software developers. That’s because it’s widely distributed and standard. Newer languages
are available, such as C++, but these are still evolving. C is still the language of choice for
robust, portable programming. This book emphasizes the skills you will need to do real-
world programming. It teaches you not only the mechanics of the C language.
To create a good program you must do more than just type in code. It is an art in which
writing and programming skills blend themselves together to form a masterpiece. A well-
written program not only functions correctly, but is simple and easy to understand.
Comments allow the programmer to include descriptive text inside the program.
Author….
M&S PUBLICATIONS
Unit-I
Chapter-I
Fundamentals of Computers
Introduction
The computer is one of the most brilliant gifts of science. This device was originally developed by
Charles Babbage. Most countries have developed fast due to computerization. Writing a program
is essential for a computer. Speed, accuracy, reliability, and integrity are the main characteristics
of a computer.
Many of the routine activities today at home and in business are done by computers. The computer
has proved a friend and servant of science, technology and industry. Most offices, shops, factories
and industries use computers. The Internet is a storehouse of information. Telecommunication
and satellite imageries are computer based. Computers have made the world a global village today.
It is an electronic device for storing and analysing information fed into it, for calculating, or for
controlling machinery automatically. Charles Babbage developed this device first in 1812 followed
by George Boole in 1854, Howard and Aitten in 1937, Dr. John Nouchly and J. P. Eckert in 1946.
These computers were named the first generation equipment. Today, with the 'Artificial
Intelligence' technology, we are using fifth generation computers. Each new generation of
computers has been smaller, lighter, speedier and more powerful than the earlier ones. Now note-
book sized computers like laptop are fairly common. A computer has been dominating technology
since 1970s, and has now entered almost all walks of life.
Writing a program is essential for running a computer. This job is done by a software engineer. A
computer program is a complete list of instructions which the
computer accepts in order to solve a problem. There are many
different languages that can be used to programme a
computer. BASIC, COBOL, FORTRAN, C, C++, JAVA and
Visual Basic are some of them.
In less than 50 years, computers have influenced practically every field of activity. Many of the
routine activities today are being performed by computers. Use of computers has reduced the
paperwork. Now most of the work is done directly on the computers. The traffic in large cities is
controlled by computers. Automation in banks and railway stations has provided relief to the
public and staff alike. Ticketing and reservation have become more efficient and convenient.
Various types of games like chess and cards can also be played on computers.
In medical diagnosis, computers are being used to locate and investigate accurately and precisely
abnormalities and diseases. Business transactions and high volume of associated data are easily
managed by using computers.
The computer gives us many benefits. They can be used as typewriters. When equipped with
telephone modems, with the help of computer we can chat across the world. Teleconferencing and
video conferencing are also possible. The internet helps us to keep in touch with family and friends.
One can get information about every subject known to man, ranging from government law and
services. Trade fairs, conferences, market information, education, society and politics.
M&S PUBLICATIONS
In defence, they help radars, missile and rocket launching. They have opened new avenues of
shopping and entertainment. Telecommunication and satellite imagery is computer based.
Computerization can play an important role in rural areas in seed research, crop disease
management and software development for rural industries.
The computer also has its negative side. The rises of cybercrime, the use of chat rooms for indecent
discussion, and certain websites, which deal in pornographic material have been noticed. But the
advantages and importance outweigh the disadvantages. Through computerization, the world has
become a global village today.
“A computer is an electronic device which is capable of receiving the inputs (data from the
user), storing it for a desired period of time, manipulating it according to the set of
instructions (called program) and producing the output to the user in desired form. It
performs a variety of operations in accordance to the set of instructions.
Advantages of computer
The computer can outperform human beings in speed, memory and accuracy but still the
computer has limitations. There are following limitations of a computer.
Though computer is programmed to work efficiently, fast and accurately but it is
programmed by human beings to do so. Without a program, computer is nothing.
The computer cannot think itself. The concept of artificial intelligence shows that the
computer can think.
A Computer cannot care itself like a human. A computer is dependent still to human beings
for this purpose.
A computer can retrieve data very fast but this technique is linear. A human being's mind
does not follow this rule. A human mind can think randomly which a computer machine
cannot.
One of the main limits in the computer is of feeling. A computer cannot feel about some like
a human. A computer cannot meet human in respect of relations. Human can feel, think
and caring but a computer machine itself cannot.
Characteristics of computer
Let us identify the major characteristics of computer. These can be discussed under the headings
of speed, accuracy, diligence, versatility and memory.
Speed: - As you know computer can work very fast. It takes only few seconds for
calculations that we take hours to complete. You will be surprised to know that computer
can perform 1/3 millionth (1/3,000,000) of instructions and even more per second.
Therefore, we determine the speed of computer in terms of microsecond (10-6 part of a
second) or nano-second (10-9 part of a second). From this you can imagine how fast your
computer performs work.
M&S PUBLICATIONS
Accuracy: - The degree of accuracy of computer is very high and every calculation is
performed with the same accuracy. The accuracy level is determined on the basis of design
of computer. The errors in computer are due to human and inaccurate data.
Diligence: - A computer is free from tiredness, lack of concentration, fatigue, etc. It can
work for hours without creating any error. If millions of calculations are to be performed, a
computer will perform every calculation with the same accuracy. Due to this capability it
overpowers human being in routine type of work.
Versatility: -It means the capacity to perform completely different type of work. You may
use your computer to prepare payroll slips. Next moment you may use it for inventory
management or to prepare electric bills.
Power of Remembering: -Computer has the power of storing any amount of information
or data. Any information can be stored and recalled as long as you require it, for any
numbers of years. It depends entirely upon you how much data you want to store in a
computer and when to lose or retrieve these data.
No IQ: -Computer is a dumb machine and it cannot do any work without instruction from
the user. It performs the instructions at tremendous speed and with accuracy. It is you to
decide what you want to do and in what sequence. So a computer cannot take its own
decision as you can.
No Feeling: - It does not have feelings or emotion, taste, knowledge and experience. Thus
it does not get tired even after long hours of work. It does not distinguish between users.
Storage: -The Computer has an in-built memory where it can store a large amount of data.
You can also store data in secondary storage devices such as floppies, which can be kept
outside your computer and can be carried to other computers.
History and Generations of computers
The history of computer development is often referred to in reference to the different generations
of computing devices. A generation refers to the state of improvement in the product development
process. This term is also used in the different advancements of new computer technology. With
each new generation, the circuitry has gotten smaller and more advanced than the previous
generation before it. As a result of the miniaturization, speed, power, and computer memory has
proportionally increased. New discoveries are constantly being developed that affect the way we
live, work and play.
Generations of computers
The first computers used vacuum tubes for circuitry and magnetic
drums for memory, and were often enormous, taking up entire rooms.
A magnetic drum, also referred to as drum, is a metal cylinder coated
with magnetic iron-oxide material on which data and programs can be
stored. Magnetic drums were once used as a primary storage device
but have since been implemented as auxiliary storage devices.
M&S PUBLICATIONS
generation computers relied on machine language to perform operations, and they could only solve
one problem at a time. Machine languages are the only languages understood by computers. While
easily understood by computers, machine languages are almost impossible for humans to use
because they consist entirely of numbers. Computer Programmers, therefore, use either high level
programming languages or an assembly language programming. An assembly language contains
the same instructions as a machine language, but the instructions and variables have names
instead of being just numbers.
The UNIVAC and ENIAC computers are examples of first-generation computing devices. The
UNIVAC was the first commercial computer delivered to a business client, the U.S. Census Bureau
in 1951.
Advantages
Vacuum tubes were the only electronic component available during those days.
Vacuum tube technology made possible to make electronic digital computers.
These computers could calculate data in millisecond.
Disadvantages
The computers were very large in size.
They consumed a large amount of energy.
They heated very soon due to thousands of vacuum tubes.
They were not very reliable.
Air conditioning was required.
Constant maintenance was required.
Non-portable.
Costly commercial production.
Limited commercial use.
Very slow speed.
Limited programming capabilities.
Used machine language only.
Used magnetic drums which provide very less data storage.
Used punch cards for input.
Not versatile and very faulty.
Second Generation - 1956-1963: Transistors
Transistors replaced vacuum tubes and ushered in the second generation computer. Transistor is
a device composed of semiconductor material that amplifies a signal or opens or closes a circuit.
Invented in 1947 at Bell Labs, transistors have become
the key ingredient of all digital circuits, including
computers. Today's latest microprocessor contains
tens of millions of microscopic transistors.
Advantages
Smaller in size as compared to the first generation computers.
The 2nd generation Computers were more reliable
Used less energy and were not heated.
Wider commercial use
4
M&S PUBLICATIONS
Better portability as compared to the first generation computers.
Better speed and could calculate data in microseconds
Used faster peripherals like tape drives, magnetic disks, printer etc.
Used Assembly language instead of Machine language.
Accuracy improved.
Disadvantages
Cooling system was required
Constant maintenance was required
Commercial production was difficult
Only used for specific purposes
Costly and not versatile
Punch cards were used for input.
Third Generation - 1964-1971: Integrated Circuits
The development of the integrated circuit was the hallmark of the third generation of computers.
Transistors were miniaturized and placed on silicon chips, called semiconductors, which
drastically increased the speed and efficiency of computers.
A chip is a small piece of semi conducting material (usually silicon) on which an integrated circuit
is embedded. A typical chip is less than ¼-square inches and
can contain millions of electronic components (transistors).
Computers consist of many chips placed on electronic boards
called printed circuit boards. There are different types of chips.
For example, CPU chips (also called microprocessors) contain
an entire processing unit, whereas memory chips contain
blank memory.
Computer chips, both for CPU and memory, are composed of semiconductor materials.
Semiconductors make it possible to miniaturize electronic components, such as transistors. Not
only does miniaturization mean that the components take up less space, it also means that they
are faster and require less energy.
Instead of punched cards and printouts, users interacted with third generation computers through
keyboards and monitors and interfaced with an operating system, which allowed the device to run
many different applications at one time with a central program that monitored the memory.
Computers for the first time became accessible to a mass audience because they were smaller and
cheaper than their predecessors.
Advantages
Smaller in size as compared to previous generations.
More reliable.
Used less energy
Produced less heat as compared to the previous two generations of computers.
Better speed and could calculate data in nanoseconds.
Used fan for heat discharge to prevent damage.
Maintenance cost was low because hardware failure is rear.
Totally general purpose
Could be used for high-level languages.
Good storage
5
M&S PUBLICATIONS
Versatile to an extent
Less expensive
Better accuracy
Commercial production increased.
Used mouse and keyboard for input.
Disadvantages
Air conditioning was required.
Highly sophisticated technology required for the manufacturing of IC chips.
Fourth Generation - 1971-Present: Microprocessors
The microprocessor brought the fourth generation of computers, as
thousands of integrated circuits we rebuilt onto a single silicon chip. A
silicon chip that contains a CPU. In the world of personal computers,
the terms microprocessor and CPU are used interchangeably. At the
heart of all personal computers and most workstations sits a
microprocessor. Microprocessors also control the logic of almost all
digital devices, from clock radios to fuel-injection systems for
automobiles.
On large machines, CPUs require one or more printed circuit boards. On personal computers and
small workstations, the CPU is housed in a single chip called a microprocessor.
Two typical components of a CPU are
The arithmetic logic unit (ALU), which performs arithmetic and logical operations.
The control unit, which extracts instructions from memory and decodes and executes them,
calling on the ALU when necessary.
Advantages
More powerful and reliable than previous generations.
Small in size
Fast processing power with less power consumption
Fan for heat discharging and thus to keep cold.
No air conditioning required.
Totally general purpose
Commercial production
Less need have repair.
Cheapest among all generations
All types of High level languages can be used in this type of computers
Disadvantages
The latest technology is required for manufacturing of Microprocessors .
M&S PUBLICATIONS
Fifth Generation - Present and Beyond: Artificial Intelligence
Fifth generation computing devices, based on artificial intelligence, are still in development, though
there are some applications, such as voice recognition, that are being used today.
Games Playing: programming computers to play games such as chess and checkers
Expert Systems: programming computers to make decisions in real-life situations (for
example, some expert systems help doctors diagnose diseases based on symptoms)
Natural Language: programming computers to understand natural human languages
Neural Networks: Systems that simulate intelligence by attempting to reproduce the types
of physical connections that occur in animal brains.
Robotics: programming computers to see and hear and react to other sensory stimuli
Classification of computers
The different Types computers those are present in the current world with multi technology built
in them for the present world.
Desktop computers Handheld computers
Workstations Supercomputers
Notebook computers Mainframe computers
Tablet computers Minicomputers
Desktop computers
The most common computer used in today’s world is the desktop computers
which were specially built for personal use is it at home or work. These
computers are everywhere, from your office, to your house, schools,
laboratories and even public places like a public library, universities and so on.
Today’s computers are brilliant at task management than many years ago.
Today’s desktop computers can be used to communicate, produce music, edit photographs and
videos, play sophisticated games, and much more.
As the name implies, a desktop computer is a full size computer that is too big to be carried
around. Now a days, most desktop computers are equipped with two primaries hardware solutions
the monitor and a casing inside which is stored the central processing unit (CPU), the
motherboard, the graphic card, storage devices, buses, power supply and so on. This is also
equipped with a keyboard and mouse which are connected to their appropriate ports at the back
of the casing.
Workstations
A workstation is a specialized, single user computer that typically has more power and features
than a standard desktop computer. These machines are more popular in the lab of scientists,
engineers or even animators who require a system with greater than average speed and power to
perform sophisticated calculations, rendering, or high level tasks. Workstations often have larger
M&S PUBLICATIONS
and higher resolution monitors, and accelerated graphics. These higher specifications allow for
advanced architectural engineering design, modeling animation and even video editing.
Notebook computers
The portability of laptops is one of the most major reasons for the increased use
of laptops nowadays. They are the mobile computers that can be carried anywhere and used
conveniently.
Tablet PC
Tablet PC’s are some of the more new developments in portable, full featured computers. Tablet
PC’s just like a notebook offers the full range of functionalities except that they are lighter and
accepts input from pen/pointers known as a stylus.
Most interactions are done directly via the screen of the computer and some
tablet PC’s also allow for input via the user’s voice. As you know, even phones
these days accept voice commands to get things done.
Tablet PC’s can run specialized versions of standard programs and can be connected to a network
or to the internet. Certainly in most new models now a keyboard and a mouse can be attached as
well.
Supercomputers
Supercomputers are the most fastest and expensive modern computer systems. They are mostly
used for intense processing and forecasting such as forecasting the weather,
or super high resolution graphics such as ray traced images.
Government processes such as immigration clearances, and all other high
level functionalities are handled by a supercomputer. Supercomputers are
also extensively used in the military to manage and calculate or even analyze
full range of information from coordinates to traffic control and even launching systems.
Mainframe computers
Mainframe computers are used in large organizations such as insurance
companies and banks, where many people frequently need to use the same data.
In a traditional mainframe environment, each user accesses the mainframe’s
resources through a terminal (network terminal).
There are two kinds of terminal, one is a dumb terminal which does not process
or store data, just basic I/O and the intelligent terminal which can perform processing operations
but these terminals normally do not have any storage.
Mainframes are large and powerful systems to handle the processing of thousands of users at any
one time. Most large organizations implement mainframes due to their flexibilities in which
department computers can be allocated a certain functionality that is related to the department
in response to all programs.
Minicomputers
Minicomputers are small sized computers which have their capabilities between the range of a
personal desktop computer and a mainframe. Minicomputers were replaced by the
microcomputers which took over the reign of those mighty minicomputers due to their greater
processing power.
M&S PUBLICATIONS
Architecture of Computer
A computer can process data, pictures, sound and graphics. They can solve highly complicated
problems quickly and accurately. A computer performs basically five major computer operations
or functions irrespective of their size and make. These are
It accepts data or instructions by way of input.
It stores data.
It can process data as required by the user.
It gives results in the form of output.
It controls all operations inside a computer.
Input Unit
Storage Unit
The process of saving data and instructions permanently is known as storage. Data has to be fed
into the system before the actual processing starts. It is because the processing speed of Central
Processing Unit (CPU) is so fast that the data has to be provided to CPU with the same speed.
Therefore the data is first stored in the storage unit for faster access and processing. This storage
unit or the Primary storage of the computer system is designed to do the above functionality. It
provides space for storing data and instructions.
Processing Unit
The task of performing operations like arithmetic and logical operations is called processing. The
Central Processing Unit (CPU) takes data and instructions from the storage unit and makes all
sorts of calculations based on the instructions given and the type of data provided. It is then sent
back to the storage unit.
Output Unit
This is the process of producing results from the data for getting useful information. Similarly the
output produced by the computer after processing must also be kept somewhere inside the
computer before being given to you in human readable form. Again the output is also stored inside
the computer for further processing.
Control Unit
The manner how instructions are executed and the
above operations are performed. Controlling of all
operations like input, processing and output are
performed by control unit. It takes care of step by step
processing of all operations inside the computer.
After you enter data through the input device it is stored in the memory unit. The actual processing
of the data and instruction are performed by Arithmetic Logical Unit. The major operations
performed by the ALU are addition, subtraction, multiplication, division, logic and comparison.
Data is transferred to ALU from storage unit when required. After processing the output is returned
back to storage unit for further processing or getting stored.
M&S PUBLICATIONS
Input Devices
An input device is any device that provides input to a computer. There are dozens of possible input
devices, but the two most common ones are a keyboard and mouse. Every key you press on the
keyboard and every movement or click you make with the mouse sends a specific input signal to
the computer. These commands allow you to open programs, type messages, drag objects, and
perform many other functions on your computer.
Since the job of a computer is primarily to process input, computers are pretty useless without
input devices. Just imagine how much fun you would have using your computer without a
keyboard or mouse. Not very much. Therefore, input devices are a vital part of every computer
system. Some of the input devices are
Key Board
As the name implies, a keyboard is basically a board of keys. Along with the mouse, the keyboard
is one of the primary input devices used with a computer.
The keyboard's design comes from the original typewriter
keyboards, which arranged letters and numbers in a way
that prevented the type-bars from getting jammed when
typing quickly. This keyboard layout is known as the
QWERTY design, which gets its name from the first six
letters across in the upper-left-hand corner of the keyboard.
While the design of computer keyboards may have come from typewriters, today's keyboards have
many other keys as well. The other keys are
Numeric Keys
Function Keys
Alphabetical keys
Special Functional Keys
Symbolic Keys
Mouse
While most people don't want to see a mouse running around in their home,
they typically don't have a problem seeing one sitting by their computer. This
is because, along with the keyboard, the mouse is one of the primary input
devices used with today's computers. The name comes from the small shape of
the mouse, which you can move quickly back and forth on the mouse pad, and
the cord, which represents the mouse's tail. Of course, if you are using a
wireless mouse, the analogy does not work so well.
All mouse have at least one button, though most mouse have two or three. Some also have
additional buttons on the sides, which can be assigned to different commands. Most mouse’s also
have a scroll-wheel, which lets you scroll up and down documents and Web pages by just rolling
the wheel with your index finger.
Early mouses tracked movement using a ball in the bottom of the mouse. This "mouse ball" pushed
against different rollers as it moved, measuring the mouse's speed and direction. However, now
most mouse use optical technology, which uses a beam of light to track the mouse's motion.
Optical mouse are more accurate than roller-based mouse and they have the added bonus of not
getting dirty inside.
10
M&S PUBLICATIONS
Joy stick
Scanner
Web Cam
Webcams are typically small cameras that either attach to a user's monitor or sit
on a desk. Most webcams connect to the computer via USB, though some use a
Fire wire connection. Webcams typically come with software that allows the user
to record video or stream the video on the Web. If the user has a website that
supports streaming video, other users can watch the video stream from their Web browsers.
Light Pen
This device reads bar codes and coverts them into electric pulses to be processed
by a computer. A bar code is nothing but data coded in form of light and dark
bars.
This devices converts spoken words to M/C language form. A micro phone is
used to convert human speech into electric signals. The signal pattern is then
transmitted to a computer when it’s compared to a dictionary of patterns that
have been previously placed in a storage unit of computer. When a close
match is found, the word is recognized.
11
M&S PUBLICATIONS
Output Device
Data generated by a computer is referred to as output. This includes data produced at a software
level, such as the result of a calculation, or at a physical level, such as a printed document.
Devices that produce physical output from the computer are creatively called output devices. The
most commonly used output device is the computer's monitor, which displays data on a screen.
Devices such as the printer and computer speakers are some other common output devices.
Monitor
The term "monitor" is often used synonymously with "computer screen" or "display." The monitor
displays the computer's user interface and open programs, allowing the user to interact with the
computer, typically using the keyboard and mouse.
Older computer monitors were built using cathode ray tubes (CRTs),
which made them rather heavy and caused them to take up a lot of
desk space. Most modern monitors are built using LCD technology
and are commonly referred to as flat screen displays. These thin
monitors take up much less space than the older CRT displays.
Speakers
Speakers are one of the most common output devices used with computer
systems. Some speakers are designed to work specifically with computers,
while others can be hooked up to any type of sound system. Regardless of
their design, the purpose of speakers is to produce audio output that can
be heard by the listener.
Speakers are transducers that convert electromagnetic waves into sound waves. The speakers
receive audio input from a device such as a computer or an audio receiver.
Printer
A printer is an output device that prints paper documents. This includes text
documents, images, or a combination of both. The printed output produced
by a printer is often called a hard copy, which is the physical version of an
electronic document. While some printers can only print black and white hard
copies, most printers today can produce color prints.
Projector
Projector is a device that uses light and lenses to take an image and project a magnified image
onto a larger screen or wall. Projectors can magnify still or moving images depending on how they
are built. The image must be shone through a sealed tube or frame when passing through the
lenses to maintain focus.
12
M&S PUBLICATIONS
Digital projectors are the modern replacement to more traditional transparency
projectors. Transparency projectors work by shining light through a semi-
transparent material, such as slides or film. Digital projectors, by contrast,
project a digital image directly from a computer through a lens on to a screen.
There are four technologies which may be used in digital projectors.
LCD (Liquid Crystal Display) digital projectors are much lighter and more portable.
With the advent of new LCD technologies, digital projectors have been developed
which have very clear and crisp fidelity even at large projection sizes. The LCD used
in digital projectors is approximately the size of a small color slide, and in fact the projectors
operate very much like a traditional slide projector. The main difference is that the slide is
constantly changing.
13
M&S PUBLICATIONS
Central Processing unit (CPU)
The internal components of a computer are foreign to many but their functions are not difficult to
understand. The CPU is one of the most basic and essential parts of a computer. The CPU does
the thinking and number crunching required by the computer's programs and hardware. RAM
sends data to the CPU to be processed. A higher processor speed increases your computer's speed
because it does the thinking faster.
Computer central processing unit (CPU) is the brain of the computer. This chip runs all processes
on a computer. A CPU socket holds the CPU and is part of a computer motherboard.
"Hertz" is a timing measurement that is defined in terms of "cycles per second." It is used to
measure frequencies, such as sound, electricity or the clock rate of a central processing unit. The
speed of CPU is measured by megahertz and gigahertz. The expression, "megahertz," denotes 1
million cycles per second, "Gigahertz" means 1 billion cycles per second.
A register is a small amount of very fast computer memory used to speed the execution of computer
programs by providing quick access to commonly used values—typically, the values being in the
midst of a calculation at a given point in time. Most computers move data from main memory into
registers, operate on them, and then move the result back into main memory. Registers are
normally measured by the number of bits they can hold, for example, an "8-bit register" or a "32-
bit register".
CU - Control Unit
The part of the Central Processor which manages the execution of instructions. The two registers
inside it are the Program Counter and Instruction Register. The control unit
Fetches (gets) each instruction after the other
Decodes it
Controls the timing and execution of the instruction
ALU - Arithmetic Logic Unit
The arithmetic logic unit/arithmetic-logic unit (ALU) of a computer's CPU is a part of the execution
unit, a core component of all CPUs. ALU’s are capable of calculating the results of a wide variety
of basic arithmetical computations. Most ALU’s will perform the following operations
Integer arithmetic operations (addition, subtraction, multiplication)
Bitwise logic operations (and, not, or, xor)
Bit-shifting operations (shifting or rotating a word by a specified number of bits to the left
or right, with or without sign extension).
14
M&S PUBLICATIONS
Memory
Memory is one of the most important things that is incorporated into computers. There are various
computer memory types installed, depending upon the actual need for functioning and
specifications of the system. The computer memory relates to the many devices and components
that are responsible for storing data and applications on temporary or permanent bases. It enables
a person to retain the information that is stored on the computer. Without it, the processor would
not be able to find a place which is needed to store the calculations and processes.
RAM is a location within the computer system which is responsible for stacking away data on a
temporary basis, so that it can be promptly accessed by the processor. The
information stored in RAM is typically loaded from the computer's hard disk,
and includes data related to the operating system and certain applications.
When the system is switched off, RAM loses all the stored information. The data
remains stored and can be retained only when the system is running.
When the RAM gets full, the computer system is more likely to operate at a slow
speed. The data can be retrieved in any random order. Rams are classified into 2 types which are
as follows
SRam
DRam
Static Ram
"SRAM is a type of RAM that stores data using a static method, in which the data remains constant
as long as electric power is supplied to the memory chip. This is different than DRAM (dynamic
RAM), which stores data dynamically and constantly needs to refresh the data stored in the
memory. Because SRAM stores data statically, it is faster and requires less power than DRAM.
However, SRAM is more expensive to manufacture than DRAM because it is built using a more
complex structure. This complexity also limits the amount of data a single chip can store, meaning
SRAM chips cannot hold as much data as DRAM chips.
15
M&S PUBLICATIONS
Dynamic Ram
Stands for "Dynamic Random Access Memory." DRAM is a type of RAM that stores each bit of data
on a separate capacitor. This is an efficient way to store data in memory, because it requires less
physical space to store the same amount of data than if it was stored statically. Therefore, a DRAM
chip can hold more data than an SRAM (static RAM) chip of the same size can.
The capacitors in DRAM need to constantly be refreshed to keep their charge, so DRAM requires
more power than SRAM. DRAM is the most common type of memory found in personal computer
systems.
This type of memory is active, regardless of whether the system is turned on or is switched off. It
is a kind of permanent non-volatile storage memory. As the name 'read only'
suggests, the contents in it cannot be changed or modified. It is an integrated
circuit which is pre-programmed with important data that should necessarily
be present for the computer to carry out its normal functionalities.
This term is pronounced like "cash" not "catch," and definitely not "cashé." There are many
different types of caches but they all serve the same purpose. A cache stores recently-used
information in a place where it can be accessed extremely fast.
Another common type of cache is a disk cache. This stores information you have recently read
from your hard disk in the computer's RAM, or memory. Since accessing RAM is much faster than
reading data off the hard disk, this can help you access common files and folders on your hard
drive much faster.
Another type of cache is a processor cache which stores small amounts of information right next
to the processor. This helps make the processing of common instructions much more efficient,
thereby speeding up computation time.
Secondary Memory
Secondary storage technology refers to storage devices and storage media that are not always
directly accessible by a computer. This differs from primary storage technology. Examples of
secondary storage devices include external hard drives, USB flash drives, and tape drives. These
devices must be connected to a computer's external I/O ports in order to be accessed by the
system. They may or may not require their own power supply. Also include recordable CDs and
DVDs, floppy disks, and removable disks.
Secondary storage technology is not always accessible by a computer; it is commonly used for
archival and backup purposes. If a computer stops functioning, a secondary storage device may
be used to restore a recent backup to a new system. Therefore, if you use a secondary storage
device to back up your data, make sure you run frequent backups and test the data on a regular
basis.
16
M&S PUBLICATIONS
Some of the External Storage components are
Magnetic Tapes
Hard Disk
Floppy Disk
CD/DVD Drive
USB Drive
Magnetic Tapes
Utilized as a storage device since the early days of radio, magnetic tape is an external storage
device that can be used for making copies of audio, video and data. The tape is employed with the
use of a machine referred to as a tape drive. Tape drives run the magnetic tape
during the recording process and also store the tape onto a reel for easy retrieval.
The appearance of magnetic tape is similar in all of its incarnations. The tape is
a simple strip of plastic that is very narrow in appearance. A thin oxide coating
on the plastic makes it possible for the tape to retain electronically encrypted
data that can range from voice to audio to data information. This makes
magnetic tape an ideal method to back up customer databases, computer generated detail, and
billing database information.
Hard Disk
When you save data or install programs on your computer, the information is typically written to
your hard disk. The hard disk is a spindle of magnetic disks, called platters, that record and store
information. Because the data is stored magnetically, information recorded to the hard disk
remains intact after you turn your computer off. This is an important distinction between the hard
disk and RAM, or memory, which is reset when the computer's power is turned off.
Data sent to and from the hard disk drive is interpreted by the disk controller, which tells the hard
disk drive what to do and how to move the components within the drive. All information stored on a
traditional hard disk drive is done magnetically. After completing the above steps, if the computer needs to
read information from the hard disk drive it would read the magnetic polarities on the platter. One side of the
magnetic polarity is 0 and the other is 1, reading this as binary data the computer can understand what the data
is on the platter. For the computer to write information to the platter, the read/write head aligns the magnetic
polarities, writing 0's and 1's that can be read later. Basic Hard drive components
1. Disk platters
2. Read/ write head
3. Spindle motor
4. Head actuator mechanism
5. Logic board
6. Cable and connectors
7. Configuration items
The hard disk spins the disk as 3600, 5400, and up to 7200 or even more RPM (rotation per
minute).
Floppy Disk
-
Floppy disks have an interesting name, considering they do not appear to be
"floppy." However, if you take the actual disk out of
the protective casing, you will discover that the disk
is, in fact, rather flexible. It is coated with iron oxide
and stores data magnetically, just like a hard disk.
M&S PUBLICATIONS
to them by the user. The first 8 inch disks only held 80KB of data, but later versions could hold
as much as 800KB.
Flash Drives
Flash drives have many names — jump drives, thumb drives, pen drives, and USB keychain drives.
Regardless of what you call them, they all refer to the same thing, which is a small data storage
device that uses flash memory and has a built-in USB connection.
Flash drives are typically no more than two to three inches in length and less
than an inch in width. Their size and shape may resemble a thumb or a small
pen. Because of their small form factor, they are highly portable and can easily
fit in a pocket or on a keychain.
Early flash drives could store only a few megabytes of data, but modern flash
drives can store several gigabytes of information. Since they are small in size
but have large storage capacities, flash drives have replaced most previous
portable data storage mediums such as floppy disks and removable hard disks like Zip disks.
Because they have a built-in USB connection, flash drives also don't require a special disk drive
to be used. Instead, they can be used on any computer with a USB port, which nearly all modern
computers have.
18
M&S PUBLICATIONS
Operating System
An Operating System (OS) is an interface between a computer user and computer hardware. An
operating system is a software which performs all the basic tasks like file management, memory
management, process management, handling input and output, and controlling peripheral devices
such as disk drives and printers.
An operating system or OS, is a software program that provides an interface between the user and
the computer and manages thousands of applications and enables the computer hardware to
communicate and operate with the computer software.
Some of important functions of an operating System.
Memory Management
Processor Management
Device Management
File Management
Security
Control over system performance
Job accounting
Error detecting aids
Coordination between other software and users
Operating systems are there from the very first computer generation and they keep evolving with
time. Some of the important types of operating systems which are most commonly used.
Real-time Operating System: It is a multitasking operating system that aims at executing
real-time applications. Real-time operating systems often use specialized scheduling
algorithms so that they can achieve a deterministic nature of behavior. The main object of
real-time operating systems is their quick and predictable response to events. They either
have an event-driven design or a time-sharing one. An event-driven system switches
between tasks based of their priorities while time-sharing operating systems switch tasks
based on clock interrupts.
Multi-user and Single-user Operating Systems: Computer operating systems of this type
allow multiple users to access a computer system simultaneously. Time-sharing systems
can be classified as multi-user systems as they enable a multiple user access to a computer
through time sharing. Single-user operating systems, as opposed to a multi-user operating
system, are usable by only one user at a time.
Multi-tasking and Single-tasking Operating Systems: When a single program is allowed
to run at a time, the system is grouped under the single-tasking system category, while in
case the operating system allows for execution of multiple tasks at a time, it is classified as
a multi-tasking operating system.
Distributed Operating System: An operating system that manages a group of independent
computers and makes them appear to be a single computer is known as a distributed
operating system.
Embedded System: The operating systems designed for being used in embedded computer
systems are known as embedded operating systems. They are designed to operate on small
machines like PDAs with less autonomy. They are able to operate with a limited number of
resources. They are very compact and extremely efficient by design.
Batch Processing and Interactive Systems: Batch processing refers to execution of
computer programs in 'batches' without manual intervention. In batch processing systems,
programs are collected, grouped and processed on a later date. There is no prompting the
user for inputs as input data are collected in advance for future processing. Input data are
collected and processed in batches, hence the name batch processing. IBM's z/OS has
19
M&S PUBLICATIONS
batch processing capabilities. As against this, interactive operating requires user
intervention. The process cannot be executed in the user's absence.
Software
A set of instructions given to computer to solve a particular problem is called software. Software
is also known as program. Computer software specifies a sequence of operations to be performed
by computer. A computer works according to instructions written in software.
Software is a generic term for organized collections of computer data and instructions, often
broken into two major categories System Software & Application Software.
System Software
System software is responsible for controlling, integrating, and managing the individual hardware
components of a computer system so that other software and the users of the system see it as a
functional unit without having to be concerned with the low-level details such as transferring data
from memory to disk, or rendering text onto a display. Generally, system software consists of an
operating system and some fundamental utilities such as disk formatters, file managers, display
managers, text editors, user authentication (login) and management tools, and networking and
device control software.
Microsoft Solaris
Windows XP Windows Vista Nexenta
Windows XP Media Center Windows 7 OSUnix
Windows Server 2003 Windows 8 Open Solaris
Windows Server 2008 MS-DOS
20
M&S PUBLICATIONS
Chapter-II
Computer program
Languages are used for Communication with the System. As we know that there are also Some
Human Languages like English, Punjabi and Hindi those are used for Communicating with the
Other Humans. As we know that different Humans Understands different Languages.
So, there are many Languages developed those are used for communication with the humans. Like
this way when a User wants to perform any operation then a user must have to use soma program
or some request. And the system will the respond to the request of the user.
For making a request to the system, a user can use any programs, and the programs are the
collection of statements and these statements are written into the some programming languages.
So that at that time there are many languages those are also called as the programming languages
because they are used for making a program So that they are called as the programming
languages.
As we know that there are many programming languages developed and each language have its
different purpose. Programming languages are used for making some software’s those may be an
application or any system software. And a program generally contains the instructions those are
executed in the form of sequence.
A computer program is a collection of instructions that performs a specific task when executed by
a computer. A computer requires programs to function, and typically executes the program's
instructions in a central processing unit.
A computer program is usually written by a computer programmer in a programming language.
From the program in its human-readable form of source code, a compiler can derive machine
code—a form consisting of instructions that the computer can directly execute. Alternatively, a
computer program may be executed with the aid of an interpreter.
A program is like a recipe. It contains a list of ingredients (called variables) and a list of directions
(called statements) that tell the computer what to do with the variables. The variables can represent
numeric data, text, or graphical images.
There are many programming languages - C, C++, Pascal, BASIC, FORTRAN, COBOL, and LISP are
just a few. These are all high-level languages. One can also write programs in low-level
languages called assembly languages, although this is more difficult. Low-level languages are
closer to the language used by a computer, while high-level languages are closer to human
languages.
What does Programming Language mean?
M&S PUBLICATIONS
An algorithm is described using the programming language. Programming languages are typically
called computer languages, however, some authors deem programming languages to be subsets
of computer languages. Since the oldest forms of programming languages like COBOL and
FORTRAN, thousands of computer languages have been developed.
Generations of Programming Languages
There are Many Languages those are developed and those will be discussed, all the Programming
Languages also developed in the Form of Some Generations those are as Explained below
First Generation Language or Machine Language: This is also called as the First
Generation Computer Languages. And in these Machine
Languages has developed. The Machine Language Programs
contains all the instructions in the Binary Form and we know
that the Program which has written into the Machine
Language are easily understandable to the computer System.
So that it is very difficult to understand for the user because
all the instructions are written into the Form of 0 and
1. Basically this Language was used for writing the Machine
Instructions Means how the Registers will Work and how they
will be Work for Performing the Requests of the users. So that
we can also say that these Languages are used for Internal Structure of the computer
System.
But the Main Advantage is that this is very easy for the Computer and this will also increase
the Speed of Processing of the Computer System. And the Main Limitation is that this will
consume lots of time of user, if a user wants to understand any Program and this is very
difficult to learn. But the Programs those are written into the Machine Languages are never
need to translate into the other Languages.
22
M&S PUBLICATIONS
Fourth Generation Language Program: The Fourth Generation Language is not has been
developed yet. The Fourth Generation will also be the Same High Level Language which
contains the Set of Instructions those are fewer and those will be Understandable to the
user. And the Programs those will be written into the 4GL will also be easier to understand
and also contains Some Language Translator for Converting the High Level Languages into
the Machine Languages.
Always remember that the Programming Languages are also developed by seeing the
Programming Environment in which we are Working Means the Languages are also
developed by using Some Environments. The Benefit and advantage of any Programming
Language will be set According to the Environment in which we are working. Mostly in
Today’s Environment Multi Computers are connected with Each other and they are
designed for sharing the other resources those are stored on the other computers so that
now the programming languages are designed as they can be used in the networking
environment.
What does Programming Logic mean?
23
M&S PUBLICATIONS
Computer Software Definition
Software is a generic term for organized collections of computer data and instructions, often
broken into two major categories: system software that provides the
basic non-task-specific functions of the computer, and application
software which is used by users to accomplish specific tasks.
System software is responsible for controlling, integrating, and
managing the individual hardware components of a computer system
so that other software and the users of the system see it as a
functional unit without having to be concerned with the low-level
details such as transferring data from memory to disk, or rendering
text onto a display. Application software, on the other hand, is used
to accomplish specific tasks other than just running the computer
system.
Software is created with programming languages and related utilities, which may come in several
of the above forms: single programs like script interpreters, packages containing a compiler, linker,
and other tools; and large suites that include editors, debuggers, and other tools for multiple
languages.
24
M&S PUBLICATIONS
Compiler and Interpreter
Compile is the process of creating an executable program from code written in a compiled
programming language. Compiling allows the computer to run and understand the program
without the need of the programming software used to create it. When a program is compiled it is
often compiled for a specific platform.
The first compiler was developed by Grace Hopper while working on the Harvard Mark I computer.
Today, most high-level languages will include
their own compiler or have toolkits available
that can be used to compile the program. A
good example of a compiler used
with C and C++ is the Alt+F9 command.
Depending on how big the program is it
should take a few seconds or minutes to
compile and if no errors are encountered
while being compiled an executable file is
created.
A compiler is a software program that compiles program source code files into an executable
program. It is included as part of the integrated development environment IDE with most
programming software packages.
The compiler takes source code files that are written in a high-level language, such as C, BASIC,
or Java, and compiles the code into a low-level language, such as machine code or assembly code.
This code is created for a specific processor type, such as and Intel Pentium or PowerPC. The
program can then be recognized by the processor and run from the operating system.
After a compiler compiles source code files into a program, the program cannot be modified.
Therefore, any changes must be made in the source code and the program must be recompiled.
Fortunately, most modern compilers can detect what changes were made and only need to
recompile the modified files, which saves programmers a lot of time. This can help reduce
programmers' 100 hour work weeks before project deadlines to around 90 or so.
Compilation
Compilation is the process the computer takes to convert a high-level programming language into
a machine language that the computer can understand. This is done by using a compiler.
Interpreter
An interpreter translates code into machine code, instruction by instruction - the
CPU executes each instruction before the interpreter moves on to translate the next instruction.
Interpreted code will show an error as soon as it
hits a problem, so it is easier to debug
than compiled code.
An interpreter does not create an independent
final set of source code - source code is created
each time it runs. Interpreted code is slower to
execute than compiled code.
Interpreted languages include JavaScript, PHP, Python and Ruby. Interpreted languages are also
called scripting languages. These are ideal for using within dynamic web applications. They are
used for client-side and server-side coding, as they are small programs that are executed within
the browser.
While interpreters offer several advantages for running small programs, interpreted languages also
have some limitations. The most notable is the fact that interpreted code requires and interpreter
to run. Therefore, without an interpreter, the source code serves as a plain text file rather than an
executable program. Additionally, programs written for an interpreter may not be able to use built-
25
M&S PUBLICATIONS
in system functions or access hardware resources like compiled programs can. Therefore, most
software applications are compiled rather than interpreted.
Interpreter Compiler
Scans the entire program and translates it as
Translates program one statement at a time.
a whole into machine code.
It takes less amount of time to analyze the It takes large amount of time to analyze the
source code but the overall execution time is source code but the overall execution time is
slower. comparatively faster.
Generates intermediate object code which
No intermediate object code is generated,
further requires linking, hence requires more
hence are memory efficient.
memory.
Continues translating the program until the It generates the error message only after
first error is met, in which case it stops. scanning the whole program. Hence
Hence debugging is easy. debugging is comparatively hard.
Programming language like Python, Ruby use Programming language like C, C++ use
interpreters. compilers.
26
M&S PUBLICATIONS
Program Development Life Cycle (PDLC)
The program development life cycle was introduced in the 1970s, and is still in wide spread use
today. Program Development Life Cycle is part of SDLC’s implementation phase and provides
an organized plan for breaking down the task of program development into manageable chunks,
each of which must be successfully completed before moving on to the next phase.
The Program Development Life Cycle is a set of phases and steps that are followed by developers
to define, design, develop and maintain a computer program. Typical phases of the life cycle are:
Gather and Analyze the Program Requirements: The developers must obtain the program
requirements from the users and document the
requirements. Typically, a standard form is
used to develop the requirements.
Design the User Interface: After
understanding the requirements, the next step
is to design the user interface. Typically a
business information system consists of more
than one program – it may have several forms,
few reports, and other programs. The users
interface defines all the input forms, output
reports, programs, and menu system to
organize all these objects.
Design the Program: A business function when implemented in a computer system is
termed as a program. Before a program is developed, it must be designed. Program
developers use tools such as pseudo code, flow chart, and hierarchy chart to design
programs.
Code the Program: After a program is designed, it is implemented. A program code is a set
of instructions developed by a programmer to carry out the business functionality in a
particular language such as VB, C#, Java, ASP, etc.
Test the Program: As the program is being coded, and after the code is completed it must
be tested to see that program is running properly and it produces required outputs with
appropriate input data.
Document the Program/System: As a program is being coded, and after the coding is
completed, the developers should document the program. Documenting a program means
writing down some instruction for the users, the purpose of the program, the way it
performs the tasks, the inputs and the outputs expected. Once each program or sub-
program is documented, it is necessary to create documentation for the whole business
information system.
Maintain the Program/System: After the programs are developed and documented, it is
placed into operation. During the operation, a program may fail to perform its objective and
it might be necessary to add new functionality to a program or system. Changing program
design, coding, and updating programs are part of maintenance.
27
M&S PUBLICATIONS
System (Software) Development Life Cycle (SDLC)
System Development is the creation of new system or modification of old system. System
Development involves number of stages starting from System Study to System implementation
and maintenance. SDLC is an organized way to build an Information System. SDLC, in fact, is a
sequence of events carried out by Systems Analysts, System Designers and users to develop and
implement an Information System.
The system development life cycle (SDLC) can also be defined as, a framework for developing
computer based information system. In order words, SDLC is the overall process of developing
information system through a multi-step process from investigation of initial requirements
through analysis, design, implementation and maintenance. These
activities are carried out in different phases, which are mentioned below:
1. Problem Definition
2. System Analysis
3. System Design
4. System Development
5. System Testing
6. System Implementation
7. System Evaluation
8. System Support and Maintenance
All these phases, together, are called a life cycle because they cover the entire life of an Information
System.
Problem Definition
System definition is the process of defining the current problem, determining why a new system
is needed and identifying the objectives of the proposed system. In this phase the main aim is to
answer “Why do we need a new system?” and “What are the objectives of the new system?”
System Analysis
During System Analysis Project team focus on completing two tasks:
Analyzing the current system and developing possible solution to the problem.
Selecting the best solution and defining its functionality.
System Design
System Design is the process of planning a new business system to replace the old. But before
this planning can be done, we must thoroughly understand the old system. Once the analysis is
complete, the System Analyst has a firm understanding of what is to be done. The next step is how
the problem can be solved. The major objectives of Systems Design are:
1. Identification of reports and outputs the new system should produce.
2. Sketch the input screen and layout of menus options.
3. Description of data to be input, calculated and stored.
4. Individual data items, database and calculation procedures.
System Development
During the development phase, Programming plays a key role. They create and customize the
software for all the parts of the system. The actual coding and writing of the program is done at
this stage.
The overall system is broken up into number of components. Then the programmers on the project
team are assigned to specific components. The programmers write the necessary code.
System Testing
Testing is the process of executing a program with the intent of finding an error. Testing is an
integral part. The project team tests each component separately (unit testing), and then tests the
components of the system with each other. The major objectives of Systems testing are:
28
M&S PUBLICATIONS
White Box Testing - In this testing, a programmer can test cases that guarantee that every
individual part in a program has been exercised at least once, all logical decisions on their
true and false sides are executed, all loops are executed properly or not and internal data
structures to ensure their validity are exercised. In other words, white box testing is a
method of testing software that is based on knowledge of how the software is intended to
function. White box testing is also called as structural testing or glass-box testing.
Black Box Testing - Black box testing focuses on how the software functions without
references to how it is designed. The primary concern is whether the program works or not,
how it is constructed. Black box testing is also known as functional testing. A programmer
attempts to find errors in the following categories:
1. Incorrect or missing functions.
2. Interface errors.
3. Errors in data structures or external database access
4. Performance errors
5. Initialization and termination errors.
System Implementation
In this phase, the project team installs the new software and hardware, which has been tested.
The users then start using the system to perform their jobs in user environment. In this phase,
the user moves from old system to new system. This is called conversion.
System Conversion
Direct Conversion
Parallel Conversion
Phased Conversion
Pilot Conversion
System Evaluation
The system evaluation is performed to identify its strengths and weakness. The actual evaluation
can occur along any of the following dimensions:
1. Operational Evaluation
2. Organization Impact Evaluation
3. User Manager Assessment Evaluation
4. Development Performance Evaluation
System Maintenance
Once installed, the software is often used for many years. However, both the organization and the
users change. The environment may also change over a period of time. Therefore, software has to
be maintained time to time. That is, modifications and changes will be made to the software files
or procedures to meet user’s requirement. All these activities fall within system maintenance.
Some errors in the system are also corrected during this phase. Changes, or upgrades, to the
systems are made regularly during the remaining life span of the system.
29
M&S PUBLICATIONS
Chapter-III
Algorithm
What is an Algorithm?
An algorithm is defined as a step-by-step procedure or method for solving a problem by a computer
in a finite number of steps. Steps of an algorithm definition may include branching or repetition
depending upon what problem the algorithm is being developed for. While defining an algorithm
steps are written in human understandable language and independent of any programming
language. We can implement it in any programming language of our choice.
Besides merely being a finite set of rules which gives a sequence of operations for solving a specific
type of problem, a well-defined algorithm has five important features:
Finiteness. An algorithm must always terminate after a finite number of steps.
Definiteness. Each step of an algorithm must be precisely defined, the actions to be carried
out must be rigorously and unambiguously specified for each case.
Input. An algorithm has zero or more inputs, i.e., quantities which are given to it initially
before the algorithm begins.
Output. An algorithm has one or more outputs i.e., quantities which have a specified
relation to the inputs.
Effectiveness. An algorithm is also generally expected to be effective. This means that all
of the operations to be performed in the algorithm must be sufficiently basic that they can
be done exactly and in a finite length of time.
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
Algorithm may be represented in various ways. There are four ways of stating algorithms. There
steps are as follows:
Step-form
Pseudo-code
Flow chart
Step-Form Algorithm
This form of algorithm is the simplest and consists of a sequence of numbered steps or points. It
is the easiest to learn at first since it is rather like a "to-do" list however once you have mastered
other ways of stating algorithms you are unlikely to continue using this form.
30
M&S PUBLICATIONS
Pseudo code
Pseudo code is a method of describing computer algorithms using a combination of natural
language and programming language. It allows the programmer to formulate their thoughts on the
organization and sequence of a computer algorithm without the need for actually following the
exact coding syntax. Although pseudo code is frequently used there are no set of rules for its exact
implementation. In general, here are some rules that are frequently followed when writing pseudo
code:
The usual symbols are used for arithmetic operations (+, -, *, /, **).
Symbolic names are used to indicate the quantities being processed.
Certain keywords can be used, such as PRINT, WRITE, READ, etc.
Indentation should be used to indicate branches and loops of instruction.
Pseudo code
Input: An integer Limit
Output: Two integers: Number and Sum
1. Enter Limit
2. Set Number = 0.
3. Set Sum = 0.
4. Repeat the following:
If Sum > Limit, terminate the repetition, otherwise.
Increment Number by one.
Add Number to Sum and set equal to Sum.
5. Print Number and Sum.
Flow Chart
A flow chart is a graphical or symbolic representation of a process.
Each step in the process is represented by a different symbol and
contains a short description of the process step. The flow chart
symbols are linked together with arrows showing the process flow
direction.
Common Flowchart Symbols
Different flow chart symbols have different meanings. The most
common flow chart symbols are:
Terminator: An oval flow chart shape indicating the start or
end of the process.
Process: A rectangular flow chart shape indicating a normal process flow step.
Decision: A diamond flow chart shape indication a branch in the process flow.
Connector: A small, labeled, circular flow chart shape used to indicate a jump in the
process flow. (Shown as the circle with the letter “A”, below.)
Data: A parallelogram that indicates data input or output (I/O) for a process.
Document: Used to indicate a document or report (see image in sample flow chart below).
31
M&S PUBLICATIONS
Flowchart Basic Procedure
Materials needed: sticky notes or cards, a large piece of flipchart paper or newsprint, marking
pens.
A technique for organizing and coding computer programs in which a hierarchy of modules is
used, each having a single entry and a single exit point, and in which control is passed downward
through the structure without unconditional branches to higher levels of the structure. Three
types of control flow are used: sequential, test, and iteration.
Structured programming frequently employs a top-down design model, in which developers map
out the overall program structure into separate subsections. Structured programming was first
suggested by Corrado Bohm and Guiseppe Jacopini. The two mathematicians demonstrated that
any computer program can be written with just three structures: decisions, sequences, and loops.
Almost any language can use structured programming techniques to avoid common pitfalls of
unstructured languages. Unstructured programming must rely upon the discipline of the
developer to avoid structural problems, and as a consequence may result in poorly organized
programs. Most modern procedural languages include features that encourage structured
programming. Object-oriented programming (OOP) can be thought of as a type of structured
programming, uses structured programming techniques for program flow, and adds more
structure for data to the model.
32
M&S PUBLICATIONS
Chapter-IV
C-Programming Language
Language
We human beings communicate with each other’s in different language such as Urdu, French,
Punjabi and Arabic etc. Similarly to communicate with the computers we have to use specific
languages and for this purpose hundreds of languages have been develop in which few of them
has gained international reputation. C language is one of them. Language can be categories
broadly into three categories.
Machine Level Language
The most elementary and first type of computer, which was invented, was machine language.
Machine language was machine dependent. A program written in machine language cannot be run
on another type of computer without significant alterations. Machine language is sometimes also
referred as the binary language.
As computer became more popular, it became quite apparent that machine language programming
was simply too slow and tedious for most programmers. Assembly languages are also called as low
level language instead of using the string of member’s programmers began using English like
abbreviation to represent the elementary operation. The language provided an opportunity to the
programmers to use English like words that were called MNEMONICS.
The assembly languages started using English like words, but still it was difficult to learn these
languages. High level languages are the computer language in which it is much easier to write a
program than the low level language. A program written in high level language is just like gibing
instruction to person in daily life. It was in 1957 that a high level language called FORTRAN was
developed by IBM which was specially developed for scientist and engineers other high level
languages are COBOL which is widely used for business data processing task. BASIC language
which is developed for the beginners in general purpose programming language. We can use C
language for almost any programming task
User-friendly
Similar to English with vocabulary of words and symbols
Therefore it is easier to learn.
They require less time to write.
They are easier to maintain.
Problem oriented rather than 'machine' based.
High-level language programs can be translated.
It is independent of the machine on which it is
used
Turbo C++ Integrated Development Environment
IDE is nothing but Integrated Development Environment in which one can develop, run, test and
debug the application. The Turbo C++ IDE appears as shown in figure.
The C Developing Environment is a screen display with windows and pull-down menus. The
program listing, error messages and other information are displayed in separate windows.
33
M&S PUBLICATIONS
The menus may be used to invoke all the operations necessary to develop the program, including
editing, compiling, linking, and debugging and program execution. If the menu bar is inactive, it
may be invoked by pressing the [F10] function key. To select different menu, move the highlight
left or right with cursor (arrow) keys. You can also revoke the selection by pressing the key
combination for the specific menu.
Invoking the Turbo C IDE
The default directory of Turbo C compiler is c:\tc\bin. So to invoke the IDE from the windows you
need to double click the TC icon in the directory c:\tc\bin. The alternate approach is that we can
make a shortcut of tc.exe on the desktop.
Opening New Window in Turbo C
To type a program, you need to open an Edit Window. For this, open file menu and click “new”. A
window will appear on the screen where the program may be typed.
Writing a Program in Turbo C
When the Edit window is active, the program may be typed. Use the certain key combinations to
perform specific edit functions.
To save the program, select save command from the file menu. This function can also be performed
by pressing the [F2] button. A dialog box will appear asking for the path and name of the file.
Provide an appropriate and unique file name. You can save the program after compiling too but
saving it before compilation is more appropriate.
The source file is required to be turned into an executable file. This is called “Making” of the .exe
file. The steps required to create an executable file are:
Create a source file, with a .c extension.
Compile the source code into a file with the .obj extension.
Link your .obj file with any needed libraries to produce an executable program.
All the above steps can be done by using Run option from the menu bar or using key
combination Ctrl+F9 (By this linking & compiling is done in one step).
34
M&S PUBLICATIONS
History of C Language
C is a programming language which born at “AT & T’s Bell Laboratories” of USA in 1972. It was
written by Dennis Ritchie. This language was created for a specific purpose: to design the UNIX
operating system (which is used on many computers). In the late 70’s C began to replace
widespread well-known languages of that time like PL/I, ALGOL etc. Programmers everywhere
began using it to write all sorts of programs. Soon, however, different organizations began applying
their own versions of C with a subtle difference. This posed a serious problem for system
developers. To solve this problem, the American National Standards Institute (ANSI) formed a
committee in 1983 to establish a standard definition of C.
In today's world of computer programming, there are many high-level languages to choose from,
such as Pascal, BASIC, and Java. But C stands apart from all these languages. This is due to its
many desirable qualities. It is a robust language whose rich set of built-in functions and operators
can be used to write any complex logic program. The C language compiler combines the capabilities
of a low level language with the features of a high level language. Therefore the language is suitable
for writing both system software as well as business packages & other software.
Program written in c are very efficient and fast. This is due to its variety of data types and
powerful operators.
C is a powerful and flexible language which helps system developers to deliver various
complex tasks with ease.
C is popular among professional programmers for programming, as a result, a wide variety
of C compilers and helpful accessories are available.
C is highly portable language. This means that a C program written for one computer
system can be run on another system with little or no modification.
C’s another striking feature is its ability to extend itself. A C program is basically a
collection of various function supported by C library (also known as header files). We can
also add our own functions to the C library.
Writing C program with user-defined functions makes program more simple and easy to
understand. Breaking a problem in terms of functions makes program debugging,
maintenance and testing easier.
Applications of C
Mainly C Language is used for Develop Desktop application and system software. Some application
of C language are given below.
C programming language can be used to design the system software like operating system
and Compiler.
To develop application software like database and spread sheets.
For Develop Graphical related application like computer and mobile games.
To evaluate any kind of mathematical equation use c language.
C programming language can be used to design the compilers.
UNIX Kernel is completely developed in C Language.
For Creating Compilers of different Languages which can take input from other language
and convert it into lower level machine dependent language.
C programming language can be used to design Operating System.
C programming language can be used to design Network Devices.
35
M&S PUBLICATIONS
C Fundamentals
C-Program Structure
Syntax:
<Header Files>
main()
{
Variables;
Comments;
Input/out put statements;
}
Preprocessor Commands
These commands tell the compiler to do preprocessing before doing actual compilation.
Preprocessor command which tells a C compiler to include header file before going to actual
compilation.
Functions
Functions are main building blocks of any C Program. Every C Program will have one or more
functions and there is one mandatory function which is called main() function. This function is
prefixed with keyword void which means this function returns an no value when it exits.
Variables
Variables are used to hold numbers, strings and complex data for manipulation.
Expressions combine variables and constants to create new values. Statements are expressions,
assignments, function calls, or control flow statements which make up C programs.
Comments
Comments are used to give additional useful information inside a C Program. All the comments
will be put inside /*...*/. A comment can span through multiple lines.
C is a case sensitive programming language. It means in C printf() and Printf() will have
different meanings.
C has a free-form line structure. End of each C statement must be marked with a semicolon.
Multiple statements can be one the same line.
White Spaces (tab space and space bar) are ignored.
Statements can continue over multiple lines.
36
M&S PUBLICATIONS
Simple C Program
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“This is my first c-program…….”);
printf(“Written by My students………..”);
}
The very first line #include <stdio.h>,<conio.h>tells the compiler to include a header file “stdio.h”
,”conio.h” in the program. Header file in C is nothing but collection of various functions. Here we
are using printf() from stdio.h header file. The next line is void main() which is the beginning of the
program. Every program must have a main() because program starts execution from this function.
But what does the keyword void means before the main(). This means that main function will not
return any value to the compiler. I know this is tough to understand now; these things will be
discussed in detailed in function page.
The curly open and close braces { } defines the scope of the “main()” function means “main()”
function’s boundaries. At the end of the line there is a semicolon (;) which is the end of that
statement. C statements always end with a semicolon (;). One thing you should keep in your mind
that in C program, instructions declared in “main()”, are executed from top to bottom.
Execution of C Program
Creating a program
An editor like C editor using Turbo C to create a C
program. This file contains a source code which consists of executable code. The file should be
saved as '*.c' extension only.
The next step is to compile the program. The code is compiled by using compiler. Compiler
converts executable code to binary code i.e. object code using Alt+F9 key combination.
37
M&S PUBLICATIONS
Characteristics of C
We briefly list some of C's characteristics that define the language and also have lead to its
popularity as a programming language. Naturally we will be studying many of these aspects
throughout the course.
Small size
Extensive use of function calls
Loose typing -- unlike PASCAL
Structured language
Low level (Bit Wise) programming readily available
Pointer implementation - extensive use of pointers for memory, array, structures and
functions.
Now become a widely used professional language for various reasons.
It has high-level constructs.
It can handle low-level activities.
It produces efficient programs.
It can be compiled on a variety of computers.
The C Character set
The characters used to form words, numbers and expressions depend upon the computer on which
the program runs. The Characters in C are classified in to four categories.
Letters a to z & A to Z
Digits 0-9
White Spaces horizontal space, vertical space, new line etc.
Special characters {,} ,[,] ,<,> ,?,/,(,),*,&,%,#,@,!,,etc.
The C Keywords
The C keywords are reserved words by the compiler. All the C keywords have been assigned fixed
meaning. The Keywords cannot be used as variable names because they have been assigned fixed
jobs. It is suggested not to mix up keywords with variable names.
Identifiers are names of variables, functions and arrays. They are user-defined names, consisting
of sequence of letters and digits, with the letters as the first character. Lower case letters are
preferred. However, the upper case letters are also permitted. The (_) under score symbol can be
used as an identifier.
Constants
The Constants in C are applicable to the values, which do not change during the execution of a
program. There are 2 types of constants in C. They are
Numeric Constants
Character Constants
38
M&S PUBLICATIONS
Variables
A variable is just a named area of storage that can hold a single value (numeric or character). The
C language demands that you declare the name of each variable that you are going to use and its
type, before you actually try to do anything with it. Its value may be changed during the program
execution of a program. A variable name may be declared based on the meaning of the operation.
The Programming language C has two main variable types.
Local Variables
Global Variables
Local Variables
Local variables scope is confined within the block where it is defined.
Local variables must always be defined at the top of a block.
When a local variable is defined - it is not initialized by the system, you must initialize it
yourself.
When execution of the block starts the variable is available, and when the block ends the
variable 'dies'.
Global Variables
Data Type Initialize
Global variable is defined at the top of the program file and it can be int 0
visible and modified by any function that may reference it. Global
char '\0'
variables are initialized automatically by the system when you define
them! float 0
They must begin with a character without spaces but underscore is permitted.
The length of the variable varies from compiler to compiler. Generally most of the compilers
support 8 characters excluding extension. However, the ANSI standard recognizes the
maximum length of a variable up to 31 characters.
The variable should not be a C keyword.
The variable names may be a combination of upper and lower characters. For example Sum
and sum are not the same.
The variable name should not start with a digit.
If same variable name is being used for global and local variable then local variable takes
preference in its scope. But it is not a good practice to use global variables and local variables with
the same name.
39
M&S PUBLICATIONS
Integer types
Integers are whole numbers with a range of values, range of values are machine dependent.
Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to
+32767 (that is, -215 to +215-1). A signed integer use one bit for storing sign and rest 15 bits for
number.
To control the range of numbers and storage space, C has three classes of integer storage namely
short int, int and long int. All three data types have signed
and unsigned forms. A short int requires half the amount
of storage than normal integer. Unlike signed integer,
unsigned integers are always positive and use all the bits for the magnitude of the number.
Therefore the range of an unsigned integer will be from 0 to 65535. The long integers are used to
declare a longer range of values and it occupies 4 bytes of storage space.
Syntax:
int <variable name>;
Floating Point Types
The float data type is used to store fractional numbers (real numbers) with 6 digits of precision.
Floating point numbers are denoted by the keyword float.
When the accuracy of the floating point number is
insufficient, we can use the double to define the number.
The double is same as float but with longer precision and takes double space (8 bytes) than float.
Syntax:
float <variable name>;
double <variable name>;
Character Type
Character type variable can hold a single character. Characters have range between 0 and 255;
characters have values from –128 to 127.
Syntax:
char <variable name>;
Example: char ch = ‘a’;
void Type:
The void data type is usually used with function to specify its type. Like in our first C program we
declared “main()” as void type because it does not return any value.
Enum
The enum type specifier is short for "enumerated data type". The user can define a fixed set of
words that a variable of type enum can take as its value. The words are assigned integer values by
the compiler so that code can compare enum variables.
Syntax
enum identifier { enumerator-list };
40
M&S PUBLICATIONS
Input / Output functions
Input Output operations are useful for program that interact with user, take input from the user
and print messages. The standard library for input output operations used in C is stdlib. When
working with input and output in C there are two important streams
Standard input: - Standard input or stdin is a data stream for taking input from devices
such as the keyboard.
Standard output: - Standard output or stdout is a data stream for sending output to a
device such as a monitor console.
Some of the input/Out put functions are as follows.
Printf: - The usually used output statement is printf(). It is one of the library functions.
Syntax
printf (“format string”, argument list);
Format string may be a collection of escape sequence or/and conversion specification
and string constant. The format string directs the printf function to display the entire
text enclosed within the double quotes without any change.
Escape sequence Escape Meaning
Sequence
Escape sequence is a pair of character. The first letter is \n New Line
a slash followed by a character. Escape sequence help us \t Tab
to represent within the format string invisible and non- \b Back Space
printed character although there are physically two
\a Beep Sound
characters in any escape sequence. It actually represents
\o Null Character
only one. The various escape sequences are
\? Question Mark
Conversion Meaning \\ Slash
Character \’ Single Quote
%d Signed Decimal Integer \” Double Quote
%i Single Decimal Integer Conversion specification
%f Floating Point Value
Conversion specification is also a pair of character.
%c Single Character It is preceded by % and followed by a quote which
%e Floating point Value may be a character. The Conversion specification
with Exponent inscribes the printf() function that it could print
%o Octal Integer some value at that location in the text. The
%s String /Group of Characters Conversion characters supported by C are
%u Un Signed Decimal Integer
%x Hexa-Decimal Integer Scanf: -The usually used input statement is
scanf () function.
Syntax
scanf (“format string”, argument list);
The format string must be a text enclosed in double quotes. It contains the
information for interpreting the entire data for connecting it into internal
representation in memory.
The argument list contains a list of variables each proceeded by the address list and
separated by comma. The number of argument is not fixed; however corresponding
to each argument there should be a format specifier. Inside the format string the
number of argument should tally with the number of format specifier.
Putchar: - putchar function displays a single character on the screen
Getchar: - getchar function will accept a character from the console or from a file, displays
immediately while typing and we need to press Enter key for proceeding.
Syntax
getchar(void);
41
M&S PUBLICATIONS
It returns the char that they read. If end-of-file or an error is encountered getchar() functions
return EOF.
The function "getchar()" reads a single character from the standard input device, the
keyboard being assumed because that is the standard input device.
Gets: - It is used to scan a line of text from a standard input device. The gets() function will
be terminated by a newline character. The newline character won't be included as part of
the string. The string may include white space characters.
Syntax
gets(Arguments);
gets() function is declared in the header file stdio.h. It takes a single argument. The
argument must be a data item representing a string. On successful completion, gets() shall
return a pointer to string s.
Puts: - It is used to display a string on a standard output device. The puts() function
automatically inserts a newline character at the end of each string it displays, so each
subsequent string displayed with puts() is on its own line. puts() returns non-negative on
success.
42
M&S PUBLICATIONS
Operators in C
C programming language provides several operators to perform different kind to operations. There
are operators for assignment, arithmetic functions, logical functions and many more. These
operators generally work on many types of variables or constants, though some are restricted to
work on certain types. Most operators are binary, meaning they take two operands. A few are
unary and only take one operand. Operators can be classified based on the type of operations they
perform.
Arithmetic Operators
Increment and Decrement Operators
Relational Operators
Logical Operators
Assignment Operators
Bitwise Operator
Misc. Operator
Arithmetic Operator
The arithmetic operator is a binary operator, which requires two operands to perform its operation
of arithmetic.
Operator Use Description
Example + Op1+Op2 Adds OP1 and OP2
#include <stdio.h> - Op1-Op2 Subtracts OP1 and OP2
void main() * Op1*Op2 Multiplies OP1 and OP2
{ / Op1/Op2 Divides OP1 and OP2
int a = 100; % Op1%Op2 Computes the reminder of OP1 and OP2
int b = 3;
int c;
c = a + b;
printf( "a + b = %dn", c );
c = a - b;
printf( "a - b = %dn", c );
printf( "a * b = %dn", a * b );
c = a / b;
printf( "a / b = %dn", c );
c = 100 % 3;
printf( "a % b = %dn", c );
}
Increment and Decrement Operator
These operators also fall under the broad category or unary operators but are quite distinct than
unary minus. The increment and decrement operators are very useful in C language. They are
extensively used.
Operator Use Description
Example + Op++ Increment by 1; to the value of op before it is
#include <stdio.h> incremented
void main() + ++Op Increment by 1; to the value of op after it is
{ incremented
int a = 7; - Op-- Decrementing by 1; to the value of op before it
int b; is decremented
++a; - --OP Decrementing by 1; to the value of op before it
a++; is decremented
b = a++;
printf( "a = %d, b = %dn", a, b );
b = ++a;
printf( "a = %d, b = %dn", a, b );
float f = 4.05;
43
M&S PUBLICATIONS
float pi = --f + 0.09159;
printf( "f = %f, pi = %.5fn", f, pi );
}
Relational Operators
Relational operators compare between two operands and return in terms of true or false i.e. 1 or
0. In C and many other languages a true value is denoted by the integer 1 and a false value is
denoted by the integer 0. Relational operators are used in conjunction with logical operators and
conditional & looping statements.
Operators Use Description
> Op1>Op2 Op1 is greater than Op2
>= Op1>=Op2 Op1 is greater than or equal to OP2
< Op1<Op2 Op1 is less than Op2
<= Op1<=Op2 Op1 is less than or equal to Op2
== Op1= =Op2 Op1 and Op2 are equal
!= Op1!=Op2 Op1 and Op2 are not equal
Logical Operators
A logical operator is used to compare or evaluate logical and relational expressions. There are three
logical operators available in the C language.
Operators Use Description
&& Op1&&Op2 Op1 and Op2 are both true.
|| Op1||Op2 Either of Op1 or Op2 is true
& Op1&Op2 Op1 and Op2 are both true
! !op Op is false
| Op1 |Op2 Either of Op1 Or Op2 is true.
If Op1 and OP2 are different that is if one or the other of
^ Op1^Op2
the operand is true but not both.
Assignment Operators
An assignment operation assigns the value of the right-hand operand to the storage location
named by the left-hand operand. Therefore, the left-hand operand of an assignment operation
must be a modifiable l-value. After the assignment, an assignment expression has the value of the
left operand but is not an l-value.
Operator Use Equivalent
Example += Op1+=Op2 Op1=Op1+Op2
-= Op1-=Op2 Op1=Op1-Op2
#include <stdio.h>
*= Op1*=Op2 Op1=Op1*Op2
void main()
/= Op1/=Op2 Op1=Op1/Op2
{
int a = 8.3; %= Op1%=Op2 Op1=Op1%Op2
float b = 1.343f;
int c;
printf( "a = %d, b = %fn", a, b );
a += 2;
b *= a;
printf( "a = %d, b = %fn", a, b );
a %= 4;
b -= 0.43;
printf( "a = %d, b = %fn", a, b );
a = c = 5;
printf( "a = %dn", a );
a <<= c - 3;
printf( "a = %dn", a );
a &= c;
44
M&S PUBLICATIONS
printf( "a = %dn", a );
}
Bitwise Operators
C's bitwise operators work on the bits stored in integral types. They work similar to the logical
operators except that instead of working on true and false values they work with ones and zeroes.
Example Operator Description
~ Complement
#include <stdio.h> & And
void main()
| Or
{
^ Exclusive Or
int a = 0xFFFF;
>> Left Shift
char b = 0xAA;
unsigned char c = 0xAA; << Right Shift
int d;
printf("~b = 0x%Xn", ~b );
printf("a & b = 0x%Xn", a & b );
printf("a & c = 0x%Xn", a & c );
a = 0xA0;
b = 0x83;
printf("a | b = 0x%Xn", a | b );
a = 0xFFFF;
d = 0x18CF;
printf("a ^ d = 0x%Xn", a ^ d );
a = 20;
printf("d << %d = 0x%Xn", a, d << a );
d = 0x800018CF;
a = 5;
printf("d >> %d = 0x%Xn", a, d >> a );
getch();
}
Misc. Operator
Conditional Operator (? :)
This operator is the conditional operator, which has the same usage in as if else control statement.
The format of this operator as follows:
Syntax
condition ? expression : expression
Program
#include <stdio.h>
void main()
{
int num1, num2;
int answer;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
answer = num2==0 ? -1 : num1/num2;
printf("%d divided by %d is %s\n", num1, num2,
answer==-1 ? "undefined" : answer%2==0 ? "even" : "odd");
getchar();
}
45
M&S PUBLICATIONS
Programming Expression
An expression is a combination of variables constants and operators written according to the
syntax of C language. In C every expression evaluates to a value i.e., every expression results in
some value of a certain type that can be assigned to a variable.
Important Points
46
M&S PUBLICATIONS
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
|| Logical OR left-to-right
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
47
M&S PUBLICATIONS
Type Casting
Typecasting concept in C language is used to modify a variable from one date type to another data
type. New data type should be mentioned before the variable name or value in brackets which to
be typecast.
Note:
It is best practice to convert lower data type to higher data type to avoid data loss.
Data will be truncated when higher data type is converted to lower. For example, if float is
converted to int, data which is present after decimal point will be lost.
Types of typecasting in C
#include <stdio.h>
void main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
getch();
}
Usual Arithmetic Conversion
48
M&S PUBLICATIONS
UNIT-II
Chapter-V
Control Structures in C-Programming
A program consists of a number of statements which are usually executed in sequence. Programs
can be much more powerful if we can control the order in which statements are run.A control
structure or a control statement is a statement that controls program execution. C has the control
structures found in most other languages. All involve the use of logical expression to affect the
flow of execution, so it is important to recall that any expression will be automatically converted
into a logical expression if necessary, by interpreting it.
Decision Making Statements
Looping Statements
Decision Making Statements / Conditional Statements:
C program executes program sequentially. Sometimes, a program requires
checking of certain conditions in program execution. C provides various
key condition statements to check condition and execute statements
according conditional criteria. These statements are called as 'Decision
Making Statements' or 'Conditional Statements.' The different conditional
statements used in C.
1. If Statement
2. If-Else Statement
3. Nested If-Else Statement
4. Switch Case
If Statement
This is a conditional statement used in C to check condition or to control the
flow of execution of statements. This is also called as 'decision making statement
or control statement.' The execution of a whole program is done in one direction
only.
Syntax:
if (condition)
{
Statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow goes
inside the braces and executes the block of statements associated with it. If it returns false, then
program skips the braces. If there are more than 1 (one) statements in if statement then use { }
braces else it is not necessary to use.
Program
#include <stdio.h>
#include <conio.h>
void main()
{
int a;
a=5;
clrscr();
if(a>4)
printf("\nValue of A is greater than 4 !");
if(a==4)
printf("\n\n Value of A is 4 !");
getch();
}
49
M&S PUBLICATIONS
Nested if Statement
The nested if statement in C programming language is used when
multiple conditions need to be tested. The inner statement will execute
only when outer if statement is true otherwise control won't even reach
inner if statement.
Placing If statement inside another IF Statement is called Nested If in C
Programming. If Else allows us to print different statements depending
upon the expression result (TRUE, FALSE). Sometimes we have to check further even when the
condition is TRUE. In these situation, we can use Nested IF statements but be careful while using
it.
Syntax
if(condition_expression_one)
{
statement1;
if(condition_expression_two)
{
condition_expression_two both are true */
statement2;
}
}
Program
#include <stdio.h>
void main ()
{
int a = 100;
int b = 200;
if( a == 100 )
{
if( b == 200 )
{
printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
getch();
}
If-Else Statement
This is also one of the most useful conditional statements used in C to check conditions.
Syntax
if(condition)
{
true statements;
}
else
{
false statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow goes
inside the braces and executes the block of statements associated with it. If it returns false, then
it executes the else part of a program.
50
M&S PUBLICATIONS
Program
#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter Number :");
scanf("%d",&no);
if(no%2==0)
printf("\n\n Number is even !");
else
printf("\n\n Number is odd !");
getch();
}
Nested If-Else Statement
It is a conditional statement which is used when we want to check more than one condition at a
time in a same program. The conditions are executed from top to bottom checking each condition
whether it meets the conditional criteria or not. If it found the condition is true then it executes
the block of associated statements of true part else it goes to next condition to execute.
Syntax:
if(condition)
{
Statements;
}
else if(condition)
{
Statements;
}
else if(condition)
{
Statements;
}
.
.
else
{
Statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow goes
inside the braces otherwise control goes to else block again checks the next condition. If it is true
then it executes the block of statements associated with it until the required condition is true else
executes else part.
Program
#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter Number :");
scanf("%d",&no);
51
M&S PUBLICATIONS
if(no>0)
{
printf("\n\n Number is greater than 0 !");
}
else if(no==0)
{
printf("\n\n It is 0 !");
}
else if(no<0)
{
printf("Number is less than 0 !");
}
else
{
printf("Number is gretaer than 0 !");
}
getch();
}
Switch case Statement
This is a multiple or multi way branching decision making statement. When we use nested if-else
statement to check more than 1 condition then the complexity of a program increases in case of a
lot of conditions. The program is difficult to read and maintain. So to overcome this problem, C
provides 'switch case'.
Switch case checks the value of an expression against a case values, if condition matches the case
values then the control is transferred to that point.
Syntax
switch(expression)
{
case expr1:
statements;
break;
case expr2:
statements;
break;
.
.
case exprn:
statements;
break;
default:
statements;
}
In above syntax, switch, case, break are keywords. expr1, expr2 are known as 'case labels.'
Statements inside case expression need not to be closed in braces. Break statement causes an exit
from switch statement. Default case is optional case. When neither any match found, it executes.
Program
#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
52
M&S PUBLICATIONS
printf("\n Enter any number from 1 to 3 :");
scanf("%d",&no);
switch(no)
{
case 1:
printf("\n\n It is 1 !");
break;
case 2:
printf("\n\n It is 2 !");
break;
case 3:
printf("\n\n It is 3 !");
break;
default:
printf("\n\n Invalid number !");
}
getch();
}
Conditional Operator in C
Conditional operator is Ternary Operator that is it takes 3 operands. The general syntax of this
operator is as:
Syntax
expression1 ? expression2 : expression3;
Besides Operator Precedence and Associativity, It, like the logical operators, does exert some
control on the order of evaluation of the entire expression. Basically, conditional operator is same
as if-else construct. Using ?: reduce the number of line codes and improve the performance of
application
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c, large;
clrscr();
printf("Enter any three number: ");
scanf("%d%d%d",&a,&b,&c);
large=a>b ? (a>c?a:c) : (b>c?b:c);
printf("Largest Number is: %d",large);
getch();
}
A loop' is a part of code of a program which is executed repeatedly. A loop is used using condition.
The repetition is done until condition becomes condition true. A loop declaration and execution
can be done in following ways.
Check condition to start a loop
Initialize loop with declaring a variable.
Executing statements inside loop.
Increment or decrement of value of a variable.
53
M&S PUBLICATIONS
Types of looping statements
while(condition)
{
statements;
increment/decrement;
}
In above syntax, the condition is checked first. If it is true, then the program control flow goes
inside the loop and executes the block of statements associated with it. At the end of loop
increment or decrement is done to change in variable value. This process continues until test
condition satisfies.
Program
#include <stdio.h>
#include <conio.h>
void main()
{
int a;
clrscr();
a=1;
while(a<=5)
{
printf("\n TechnoExam");
a+=1 // i.e. a = a + 1
}
getch();
}
Do-While Loop
do
{
statements;
(increment/decrement);
}while(condition);
In above syntax, the first the block of statements are executed. At the end of loop, while statement
is executed. If the resultant condition is true then program control goes to evaluate the body of a
loop once again. This process continues till condition becomes false. When it becomes false, then
the loop terminates.
54
M&S PUBLICATIONS
Program
#include <stdio.h>
#include <conio.h>
void main()
{
int a;
clrscr();
a=1;
do
{
printf("\n\t TechnoExam"); // 5 times
a+=1; // i.e. a = a + 1
}while(a<=5);
a=6;
do
{
printf("\n\n\t Technowell"); // 1 time
a+=1; // i.e. a = a + 1
}while(a<=5);
getch();
}
For Loop
This is an entry controlled looping statement. In this loop structure, more than one variable can
be initialized. One of the most important features of this loop is that the three actions can be taken
at a time like variable initialization, condition checking and increment/decrement. The for loop
can be more concise and flexible than that of while and do-while loops.
Syntax
for(initialization; test-condition; incre/decre)
{
statements;
}
Initialization: The Initialization statement allows us to declare
and initialize any loop variables. It is executed only once at the
beginning of the for loop.
Condition: After initialization, condition expression is
evaluated. It is a Boolean expression which decides whether to
go inside the loop and iterate or terminate for loop. if condition
expression evaluates to true, the code block inside for loop gets
executed otherwise it will terminate for loop and control goes to the next statement
after the for loop.
Update: After code block of for loop gets executed, control comes back to update
statements. It allow us to modify any loop variable for next iteration of loop.
Features
More concise
Easy to use
Highly flexible
More than one variable can be initialized.
More than one increment can be applied.
More than two conditions can be used.
In above syntax, the given three expressions are separated by ';' (Semicolon)
55
M&S PUBLICATIONS
Program
#include <stdio.h>
#include <conio.h>
void main()
{
int a;
clrscr();
for(i=0; i<5; i++)
{
printf("\n\t TechnoTip); // 5 times
}
getch();
}
Continue Statement in C
The continue statement in C programming language is used to skip some statements inside the
body of the loop and continues the next iteration of the loop. The continue statement only skips
the statements after continue inside a loop code block.
The continue statement is used with conditional if statement. Use of continue statement, change
the normal sequence of execution of statements inside loop.
Syntax
continue;
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
for(i=1; i<=10; i++)
{
if(i==3)
{
continue;
}
printf("%d \n",i);
}
getch();
}
C goto statement
The goto statement is known as jump statement in C language. It is used to
unconditionally jump to other label. It transfers control to other parts of the
program. It is rarely used today because it makes program less readable and
complex.
Syntax
goto label;
56
M&S PUBLICATIONS
Program
#include <stdio.h>
#include <conio.h>
void main()
{
int age;
clrscr();
ineligible:
printf("You are not eligible to vote!\n");
printf("Enter you age:\n");
scanf("%d", &age);
if(age<18)
goto ineligible;
else
printf("You are eligible to vote!\n");
getch();
}
Break statement in C
57
M&S PUBLICATIONS
Chapter-VI
Array’s in C
Array is a collection of same type elements under the same variable identifier referenced by index
number. Arrays are widely used within programming for different purposes such as sorting,
searching and etc. Arrays allow you to store a group of data of a single type. Arrays are efficient
and useful for performing operations.
Arrays are of two types single dimension array and multi-dimension array. Each of these array
types can be of either static array or dynamic array. Static arrays have their sizes declared from
the start and the size cannot be changed after declaration. Dynamic arrays that allow you to
dynamically change their size at runtime, but they require more advanced techniques such as
pointers and memory allocation.
Arrays can be declared using any of the data types
available in C. Array size must be declared using
constant value before initialization. A single
dimensional array will be useful for simple
grouping of data that is relatively small in size.
These elements are accessed by numbers called as
subscripts or index numbers.
Features
Array size should be positive number only.
String array always terminates with null character ('\0').
Array elements are countered from 0 to n-1.
Useful for multiple reading of elements (numbers).
Advantage of array
Code Optimization: Less code is required, one variable can store numbers of value.
Easy to traverse data: By using array easily retrieve the data of array.
Easy to sort data: Easily short the data using swapping technique
Random Access: With the help of array index you can randomly access any elements
from array.
Less amount of code: Using array we can aggregate N variables of same data type
in a single data structure. Otherwise we have to declare N individual variables.
Easy access of elements: We can access any element of array using array name
and index. We can access all elements serially by iterating from index 0 to size-1
using a loop.
Easy to implement algorithms: Certain algorithms can be easily implemented
using array like searching and sorting, finding maximum and minimum elements.
Random Access: We can access any elements of array in O (1) time complexity.
Dis-Advantage of array
Fixed Size: Whatever size, we define at the time of declaration of array, we cannot change
their size, if you need more memory in that time you cannot increase memory size, and if
you need less memory in that case also wastage of memory.
Single Dimensional Array
The array which is used to represent and store data in a linear form is called as 'single or one
dimensional array.'
Syntax
<data type> array_name[size_of_array];
58
M&S PUBLICATIONS
Initializing on Declaration
If you know the values you want in the array at declaration time, you can initialize an array as
follows:
Syntax
<data type> array_name[size_of_array] = {element 1, element 2, ...};
array_name: It is a valid C identifier representing the name of the array.
array_size: It is the maximum number of elements which can be stored in array. It
must be an integer constant greater than zero.
data_type: It represents the data type of the elements to be stored in array.
Program
#include <stdio.h>
#include <conio.h>
void main()
{
int a[3], i;;
clrscr();
printf("\n\t Enter three numbers : ");
for(i=0; i<3; i++)
{
scanf("%d", &a[i]); // read array
}
printf("\n\n\t Numbers are : ");
for(i=0; i<3; i++)
{
printf("\t %d", a[i]); // print array
}
getch();
}
Multi-Dimensional Arrays
The array which is used to represent and store data in a tabular form is called as 'two dimensional
array.' Such type of array specially used to represent data in a matrix form.
Syntax
<data-type> <array_nm> [row_size][column-size];
Declaring Multidimensional Arrays
Just like single dimension array, you can initialize the multidimensional array also upon
declaration as well as initialize by assignment.
Syntax
<data type> array_name[size_of_row[size_of_column]= {
{element 1, element 2, element 3,. . . . . .},(. . . },{. . . },{. . .
.
.
. }};
59
M&S PUBLICATIONS
Accessing Elements in Multidimensional Arrays
M&S PUBLICATIONS
Syntax
char string_name[size];
When compiler assigns string to character array then it automatically supplies null character
('\0') at the end of string. Thus, size of string = original length of string + 1.
To read a string, we can use scanf() function with format specifier %s.
To write a string, we can use printf() function with format specifier %s.
'string.h' is a header file which includes the declarations, functions, constants of string handling
utilities. These string functions are widely used today by many programmers to deal with string
operations. Some of the standard member functions of string.h header files are as follows.
Program
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char str[50];
clrscr();
printf("\n\t Enter your name : ");
gets(str);
printf("\nLower case of string: %s",strlwr(str));
printf("\nUpper case of string: %s",strupr(str));
printf("\nReverse of string: %s",strrev(str));
printf("\nLength of String: %d",strlen(str));
getch();
}
61
M&S PUBLICATIONS
Ctype.h library functions
All C inbuilt functions which are declared in ctype.h header file are given below. The source code
for ctype.h header file is also given below for your reference. “ctype.h” header file support all the
below functions in C language.
Function Description
62
M&S PUBLICATIONS
Program
#include <stdio.h>
void main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isdigit ( ch ) )
printf ( "\nEntered character is digit" ) ;
else
printf ( "\nEntered character is not digit" ) ;
getch();
}
getch();
}
C – isspace() function: isspace( ) function in C language checks whether given character is
space or not.
int isspace( int x );
#include <stdio.h>
void main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isspace ( ch ) )
printf ( "\nEntered character is space" ) ;
else
printf ( "\nEntered character is not space" ) ;
getch();
}
C – islower() function: islower( ) function in C language checks whether given character is lower
case or not.
int islower( int x );
63
M&S PUBLICATIONS
Program
#include <stdio.h>
void main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( islower ( ch ) )
printf ( "\nEntered character is lower case character") ;
else
printf("\nEntered character is not lower case character");
getch();
}
C – isupper() function: isupper( ) function in C language checks whether given character is upper
case or not.
int isupper ( int x );
Program
#include <stdio.h>
void main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isupper ( ch ) )
printf ("\nEntered character is uppercase character");
else
printf("\nEntered character is not uppercase character");
getch();
}
64
M&S PUBLICATIONS
Control characters in C language are ‘\a’ (alert), ‘\b’ (backspace), ‘\f’ (form feed), ‘\n’ (new line),
‘\r’ (carriage return), ‘\t’ (horizontal tab), ‘\v’ (vertical tab) and ‘\0’ (null).
Note:
‘\a’ – Alert character is used to produce visible or audible alert in output.
‘\b’ -It is used to move the position of pointer to one position back in current line.
‘\f’ – form feed character is used to start a new page.
‘\n’- new line character moves to the next line from the current line.
‘\r’ – carriage return is used to move the position to the beginning of current line.
‘\t’ – It is used to move the pointer to the horizontal tab space in current line.
Program
#include <stdio.h>
void main()
{
char ch[5] ="abc\a";
int i = 0;
while(1)
{
if(iscntrl(ch[i]))
{
printf ( "control character is found at " \" %dth position\n", i+1);
break;
}
i++;
}
getch();
}
C – isprint() function: isprint( ) function in C language checks whether given character is printable
character or not.
int isprint( int x )
Program
#include <stdio.h>
void main()
{
char string[50] ="fresh2refresh \n string";
int i = 0;
while(1)
{
if(isprint(string[i]))
{
putchar(string[i]);
i++;
}
else
break;
}
getch();
}
C – ispunct() function: ispunct( ) function in C language checks whether given character is
punctuation or not.
int ispunct( int x );
65
M&S PUBLICATIONS
Program
#include <stdio.h>
void main()
{
char ch = '!';
if ( ispunct ( ch ) )
printf ( "Character is a punctuation character" ) ;
else
printf ( "\nCharacter is not a punctuation character" ) ;
getch();
}
C – isgraph() function: isgraph( ) function in C language checks whether given character is
graphical character or not.
int isgraph( int x );
All printable characters are graphical characters except space ( ‘ ‘ ).
Program
#include <stdio.h>
void main()
{
char string[50] ="fresh 2 refresh \n string";
int i = 0;
while(1)
{
if(isgraph(string[i]))
{
putchar(string[i]);
i++;
}
else
break;
}
getch();
}
66
M&S PUBLICATIONS
C – toupper() function: toupper( ) function in C language checks whether given character is
alphabetic and converts to uppercase.
int toupper( int x );
Program
#include <stdio.h>
void main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if(isalpha(ch))
printf("\nEntered character is converted into "\"upper character : %c\n",toupper(ch));
else
printf("Entered character is not an alphabetic");
getch();
}
Write a C program to input N numbers in array and find the sum of all array elements using
for for loop.
Algorithm to find sum of all array elements
67
M&S PUBLICATIONS
Write a program in c for addition of two matrices
Let A and B are two matrices of dimension M X N and S is the sum matrix(S = A +
B). Below mentions steps explains how we can find sum of two matrices.
To add two matrices we have to add their corresponding elements. For example, S[i][j] =
A[i][j] + B[i][j].
Traverse both matrices row wise (first all elements of a row, then jump to next row) using
two loops (check line number 30 and 31 of below program).
For every element A[i][j], add it with corresponding element B[i][j] and store the result in
Sum matrix at S[i][j].
#include <stdio.h>
#include <conio.h>
void main()
{
int rows, cols, rowCounter, colCounter;
int firstmatrix[50][50], secondMatrix[50][50], sumMatrix[50][50];
printf("Enter Rows and Columns of Matrix\n");
scanf("%d %d", &rows, &cols);
printf("Enter first Matrix of size %dX%d\n", rows, cols);
for(rowCounter = 0; rowCounter < rows; rowCounter++)
{
for(colCounter = 0; colCounter < cols; colCounter++)
{
scanf("%d", &firstmatrix[rowCounter][colCounter]);
}
}
printf("Enter second Matrix of size %dX%d\n", rows, cols);
for(rowCounter = 0; rowCounter < rows; rowCounter++)
{
for(colCounter = 0; colCounter < cols; colCounter++)
{
scanf("%d", &secondMatrix[rowCounter][colCounter]);
}
}
for(rowCounter = 0; rowCounter < rows; rowCounter++)
{
for(colCounter = 0; colCounter < cols; colCounter++)
{
sumMatrix[rowCounter][colCounter] = firstmatrix[rowCounter][colCounter]+
secondMatrix[rowCounter][colCounter];
}
}
printf("Sum Matrix\n");
for(rowCounter = 0; rowCounter < rows; rowCounter++)
{
for(colCounter = 0; colCounter < cols; colCounter++)
{
printf("%d ", sumMatrix[rowCounter][colCounter]);
}
printf("\n");
}
getch();
}
68
M&S PUBLICATIONS
Write a program in c to multiply a scalar number (real number) and a matrix
#include <stdio.h>
#include <conio.h>
void main()
{
int rows, cols, rowCounter, colCounter, scalar;
int inputMatrix[50][50];
printf("Enter Rows and Columns of Matrix\n");
scanf("%d %d", &rows, &cols);
printf("Enter Matrix of size %dX%d\n", rows, cols);
for(rowCounter = 0; rowCounter < rows; rowCounter++)
{
for(colCounter = 0; colCounter < cols; colCounter++)
{
scanf("%d", &inputMatrix[rowCounter][colCounter]);
}
}
printf("Enter a number to multiply with matrix \n");
scanf("%d", &scalar);
for(rowCounter = 0; rowCounter < rows; rowCounter++)
{
for(colCounter = 0; colCounter < cols; colCounter++)
{
inputMatrix[rowCounter][colCounter] = inputMatrix[rowCounter][colCounter]
*scalar;
}
}
printf("Product Matrix\n");
for(rowCounter = 0; rowCounter < rows; rowCounter++)
{
for(colCounter = 0; colCounter < cols; colCounter++)
{
printf("%d ", inputMatrix[rowCounter][colCounter]);
}
printf("\n");
}
getch();
}
Write a program in c to swap the content of two strings
Algorithm to swap two strings using strcpy
This algorithm of swapping string is similar to the algorithm of swapping integers using a
temporary variable. Let firstString and secondString are two input strings and tempString is a
temporary string whose size is equal to or more than the size of firstString.
M&S PUBLICATIONS
gets(firstString);
printf("Enter second String \n");
gets(secondString);
strcpy(tempString, firstString);
strcpy(firstString, secondString);
strcpy(secondString, tempString);
printf("After Swapping\n");
printf("First String: %s\nSecond String: %s", firstString, secondString);
getch();
}
Write a c program to check whether a number is palindrome or not
Algorithm to check a number is palindrome or not
Take a number as input from user and store it in an integer variable(Let's call it
inputNumber).
Reverse the digits of inputNumber, and store it in another integer variable(Let's call
it reverseNumber).
Compare inputNumber and reverseNumber.
If both are equal then inputNumber is palindrome otherwise not a palindrome.
#include <stdio.h>
#include <conio.h>
void main()
{
int inputNumber, reverseNumber = 0, rightDigit, temp;
printf("Enter a number \n");
scanf("%d", &inputNumber);
temp = inputNumber;
while(temp != 0)
{
rightDigit = temp % 10;
reverseNumber = (reverseNumber * 10) + rightDigit;
temp = temp/10;
}
if(reverseNumber == inputNumber)
{
printf("%d is Palindrome number\n", inputNumber);
}
Else
{
printf("%d is not a Palindrome number\n", inputNumber);
}
getch();
}
Write a program to check whether a number is Armstrong number or not
Algorithm to check for Armstrong number
Take a number as input from user and store it in an integer variable (Let's call it
inputNumber).
Find the cubic sum of digits of inputNumber, and store it in sum variable.
Compare inputNumber and sum.
If both are equal then input number is Armstrong number otherwise not an
Armstrong number.
70
M&S PUBLICATIONS
#include <stdio.h>
#include <conio.h>
void main()
{
int number, sum = 0, lastDigit, temp;
printf("Enter a number : ");
scanf("%d", &number);
temp = number;
while(temp != 0)
{
lastDigit = temp%10;
sum = sum + (lastDigit*lastDigit*lastDigit);
temp = temp/10;
}
if(sum == number)
{
printf("%d is Armstrong Number \n", number);
}
else
{
printf("%d is not an Armstrong Number \n", number);
}
getch();
}
Write a program in c to print fibonacci series till Nth term
#include <stdio.h>
#include <conio.h>
void main()
{
int terms, lastNumber=1,secondLast=0,currentNumber=0,counter;
printf("Enter number of terms in Fibonacci series: ");
scanf("%d", &terms);
for(counter = 0; counter < terms; counter++){
if(counter < 2)
{
currentNumber = counter;
}
else
{
currentNumber = lastNumber + secondLast;
secondLast = lastNumber;
lastNumber = currentNumber;
}
printf("%d ", currentNumber);
getch();
}
71
M&S PUBLICATIONS
Unit-III
Chapter-VII
Functions in C
A function is a group of statements that together perform a specific task. Every C program has at
least one function, which is main ().
The function is a self-contained block of statements which performs a coherent task of a same
kind. C program does not execute the functions directly. It is required to invoke or call that
functions. When a function is called in a program then program control goes to the function body.
Then, it executes the statements which are involved in a function body. It is possible to call
function whenever we want to process that functions statements.
Why use function?
Function are used for divide a large code into module, due to this we can easily debug and
maintain the code. For example if we write a calculator programs at that time we can write every
logic in a separate function (For addition sum(), for subtraction sub()). Any function can be called
many times.
Advantage of Function
Code Re-usability
Develop an application in module format.
Easily to debug the program.
Code optimization: No need to write lot of code.
A function declaration is the process of tells the compiler about a function name. The actual body
of the function can be defined separately.
return_type function_name(parameter);
Defining a function.
Defining of function is nothing but give body of function that means write logic inside function
body.
72
M&S PUBLICATIONS
return_type function_name(parameter)
{
function body;
}
<return_type><function_name>([<argu_list>]);
{
<function_body>;
}
Return type: A function may return a value. The return_type is the data type of the value
the function returns.Return type parameters and returns statement are optional.
Function name: Function name is the name of function it is decided by programmer or
you.
Parameters: This is a value which is pass in function at the time of calling of function A
parameter is like a placeholder. It is optional.
Function body: Function body is the collection of statements.
Calling a function.
When we call any function control goes to function body and execute entire code. For call any
function just write name of function and if any parameter is required then pass parameter.
function_name(); or variable=function_name(argument);
Program
#include <stdio.h>
#include <conio.h>
void add()
{
int a, b, c;
clrscr();
printf("\n Enter Any 2 Numbers : ");
scanf("%d %d",&a,&b);
c = a + b;
printf("\n Addition is : %d",c);
}
void main()
{
void add();
add();
getch();
}
Function Arguments in C
On the basis of arguments there are two types of function are available in C language, they are
with argument & without argument
If a function take any arguments, it must declare variables that accept the values as a arguments.
These variables are called the formal parameters of the function. There are two ways to pass value
or data to function in C language which is given below;
call by value
call by reference
Call by value
In call by value, original value can not be changed or modified. In call by value, when you passed
value to the function it is locally stored by the function parameter in stack memory location. If you
change the value of function parameter, it is changed for the current function only but it not
change the value of variable inside the caller method such as main ().
73
M&S PUBLICATIONS
Program
#include<stdio.h>
#include<conio.h>
void swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void main()
{
int a=100, b=200;
clrscr();
swap(a, b); // passing value to function
printf("\nValue of a: %d",a);
printf("\nValue of b: %d",b);
getch();
}
Call by reference
In call by reference, original value is changed or modified because we pass reference (address).
Here, address of the value is passed in the function, so actual and formal arguments shares the
same address space. Hence, any value changed inside the function, is reflected inside as well as
outside the function.
Program
#include<stdio.h>
#include<conio.h>
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int a=100, b=200;
clrscr();
swap(&a, &b); // passing value to function
printf("\nValue of a: %d",a);
printf("\nValue of b: %d",b);
getch();
}
Difference between call by value and call by reference
74
M&S PUBLICATIONS
Changes made to the parameter inside the Changes made to the parameter affect the
function have no effect on the argument. argument. Because address is used to access
the actual argument.
Actual and formal arguments will be created in Actual and formal arguments will be created in
different memory location same memory location
Recursive Function in C
When Function is call within same function is called Recursion. The function which call same
function is called recursive function. In other word when a function call itself then that function
is called Recursive function. Recursive function are very useful to solve many mathematical
problems like to calculate factorial of a number, generating Fibonacci series, etc.
Advantage of Recursion
#include<stdio.h>
#include<conio.h>
void main()
{
int fact(int);
int i,f,num;
clrscr();
printf("Enter any number: ");
scanf("%d",&num);
f=fact(num);
printf("Factorial: %d",f);
getch();
}
75
M&S PUBLICATIONS
int fact(int n)
{
if(a<0)
return(-1);
if(a==0)
return(1);
else
{
return(n*fact(n-1));
}
}
#include<stdio.h>
#include<conio.h>
void main()
{
int table(int,int);
int n,i; // local variable
clrscr();
printf("Enter any num : ");
scanf("%d",&n);
for(i=1;i< =10;i++)
{
printf(" %d*%d= %d\n",n,i,table(n,i));
}
getch();
}
int table(n,i)
{
int t;
if(i==1)
{
return(n);
}
else
{
t=(table(n,i-1)+n);
return(t);
}
}
Storage Classes in C Programming
A Storage class defines the scope, life-time and where to store a variable in C program. There are
four storage classes defined in C programming language
Static Variable:- A local static variable is visible only inside their own function but unlike local
variables, they retain their values between function calls. We can declare static variable by
adding statickeyword before data type in variable declaration statement.
static data_type variable_name;
Program
#include <stdio.h>
int printVal()
{
static int staticVariable = 0;
76
M&S PUBLICATIONS
int localVariable = 0;
staticVariable++;
localVariable++;
printf("StaticVariable = %d, LocalVariable = %d\n", staticVariable, localVariable);
}
int main()
{
printVal();
printVal();
printVal();
printVal();
return 0;
}
Automatic variable: -A variable which is declared inside a function or block is automatic
variable by default. We can declare automatic variables using auto keyword, but it is rarely used
because by default every variable is automatic variable.
Program
#include <stdio.h>
int main()
{
int a = 5;
auto int b = 10;
printf("Sum = %d", a+b);
return 0;
}
Register Variable: -Declaring a variable with register keyword is a hint to the compiler to store
this variable in a register of the computer's CPU instead of storing it in memory. Storing any
variable in CPU register, will reduce the time of performing any operation on register variable. We
can declare register variables using register keyword.
Program
#include <stdio.h>
int main()
{
register int counter;
int sum=0;
for(counter = 1; counter <= 500; counter++)
{
sum+= counter;
}
printf("Sum = %d", sum);
return 0;
}
External Variable: -External variables in C are variables which can be used across multiple files.
We you can declare an external variable by preceding a variable name with extern specifier.
The extern specifier only tells the compiler about the name and data type of variable without
allocating any storage for it. However, if you initialize that variable, then it also allocates storage
for the extern variable.
Variables declared extern are initialized to zero by default.
The scope of the extern variable is global.
The value of the external variable exists till program termination.
77
M&S PUBLICATIONS
math.h library functions
“math.h” header file supports all the mathematical related functions in C language. All C inbuilt
functions which are declared in math.h header file are given below.
Function Description
This function returns the nearest integer which is less than or equal to the argument
floor ( )
passed to this function.
This function returns the absolute value of an integer. The absolute value of a
abs ( )
number is always positive. Only integer values are supported in C.
This function returns the nearest integer value of the float/double/long
double argument passed to this function. If decimal value is from “.1 to .5”, it returns
round ( )
integer value less than the argument. If decimal value is from “.6 to .9”, it returns
the integer value greater than the argument.
This function returns nearest integer value which is greater than or equal to the
ceil ( )
argument passed to this function.
sin ( ) This function is used to calculate sine value.
cos ( ) This function is used to calculate cosine.
exp ( ) This function is used to calculate the exponential “e” to the x th power.
tan ( ) This function is used to calculate tangent.
log ( ) This function is used to calculate natural logarithm.
sqrt ( ) This function is used to find square root of the argument passed to this function.
pow ( ) This is used to find the power of the given number.
This function truncates the decimal value from floating point value and returns
trunk ()
integer value.
C – floor() function
floor( ) function in C returns the nearest integer value which is less than or equal to the floating
point argument passed to this function. ”math.h” header file supports floor( ) function in C
language. Syntax for floor( ) function in C is given below.
double floor ( double x );
Program
#include <stdio.h>
#include <math.h>
int main()
{
float i=5.1, j=5.9, k=-5.4, l=-6.9;
printf("floor of %f is %f\n", i, floor(i));
printf("floor of %f is %f\n", j, floor(j));
printf("floor of %f is %f\n", k, floor(k));
printf("floor of %f is %f\n", l, floor(l));
return 0;
}
C – abs() function
abs( ) function in C returns the absolute value of an integer. The absolute value of a number is
always positive. Only integer values are supported in C.
Program
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m = abs(200); // m is assigned to 200
78
M&S PUBLICATIONS
int n = abs(-400); // n is assigned to -400
printf("Absolute value of m = %d\n", m);
printf("Absolute value of n = %d \n",n);
return 0;
}
C – round() function
round( ) function in C returns the nearest integer value of the float/double/long double argument
passed to this function. If decimal value is from ”.1 to .5″, it returns integer value less than the
argument. If decimal value is from “.6 to .9″, it returns the integer value greater than the argument.
double round (double a); float roundf (float a);
Program
#include <stdio.h>
#include <math.h>
int main()
{
float i=5.4, j=5.6;
printf("round of %f is %f\n", i, round(i));
printf("round of %f is %f\n", j, round(j));
return 0;
}
C – ceil() function
ceil( ) function in C returns nearest integer value which is greater than or equal to the argument
passed to this function.
double ceil (double x);
Program
#include <stdio.h>
#include <math.h>
int main()
{
float i=5.4, j=5.6;
printf("ceil of %f is %f\n", i, ceil(i));
printf("ceil of %f is %f\n", j, ceil(j));
return 0;
}
C – sin() cos() tan() exp() log() function
sin( ), cos( ) and tan( ) functions in C are used to calculate sine, cosine and tangent values.
exp( ) function is used to calculate the exponential “e” to the xth power. Log ( ) function is
used to calculates natural logarithm function is used to calculates base 10 logarithm.
”math.h” header file supports all these functions in C language.
Program
#include <stdio.h>
#include <math.h>
int main()
{
float i = 0.314;
float j = 0.25;
float k = 6.25;
float sin_value = sin(i);
79
M&S PUBLICATIONS
float cos_value = cos(i);
float tan_value = tan(i);
float log_value = log(k);
float exp_value = exp(k);
printf("The value of sin(%f) : %f \n", i, sin_value);
printf("The value of cos(%f) : %f \n", i, cos_value);
printf("The value of tan(%f) : %f \n", i, tan_value);
printf("The value of log(%f) : %f \n", k, log_value);
printf("The value of exp(%f) : %f \n",k, exp_value);
return 0;
}
C – sqrt() function
sqrt( ) function in C is used to find the square root of the given number.
double sqrt (double x);
Program
#include <stdio.h>
#include <math.h>
int main()
{
printf ("sqrt of 16 = %f\n", sqrt (16) );
printf ("sqrt of 2 = %f\n", sqrt (2) );
return 0;
}
C – pow() function: - pow( ) function in C is used to find the power of the given number.
double pow (double base, double exponent);
Program
#include <stdio.h>
#include <math.h>
int main()
{
printf ("2 power 4 = %f\n", pow (2.0, 4.0) );
printf ("5 power 3 = %f\n", pow (5, 3) );
return 0;
}
C – trunc() function
trunc( ) function in C truncates the decimal value from floating point value and returns integer
value.
double trunc (double a);
float truncf (float a);
long double truncl (long double a);
Program
#include <stdio.h>
#include <math.h>
int main()
{
printf ("truncated value of 16.99 = %f\n", trunc (16.99) );
printf ("truncated value of 20.1 = %f\n", trunc (20.1) );
return 0;
}
80
M&S PUBLICATIONS
Passing Arrays as Function Arguments in C
In C programming, an array element or whole array can be passed to a function like any other
basic data type. We can pass an array of any dimension to a function as argument. Passing an
array to a function uses pass by reference, which means any change in array data inside will
reflect globally.
We can pass one element of an array to a function like passing any other basic data type variable.
81
M&S PUBLICATIONS
void printArrayThree(int array[], int size)
{
int i;
for(i=0; i<size; i++)
{
printf("%d ", array[i]);
}
printf("\n");
}
int main()
{
int array[5]={1, 2, 3, 4, 5};
printArrayOne(array, 5);
printArrayTwo(array, 5);
printArrayThree(array, 5);
getch();
return 0;
}
82
M&S PUBLICATIONS
Chapter-VIII
Pointers in C Programming
A pointer in C programming language is a variable which is used to store the address of another
variable. It is one of the most powerful features of the C programming language. Pointers are used
everywhere in the C language. Once you master the use of pointers, you will use them everywhere
to make the code more efficient and faster.
Some operations in C, can be performed efficiently using pointers like dynamic memory allocation,
dynamic data structures like linked list and trees, pass arguments to a function as Call by Reference,
access array elements etc. To become an expert C programmer, it is necessary to have deep
understanding of pointers.
What Are Pointers
A variable in C is the name given to a memory location, where a program can store data. A program
can store and manipulate the value stored using variable's identifier. When we declare a variable
in C, compiler reserve space in memory to hold the value assigned to this variable.
We can access the value of this variable either by variable identifier or by directly accessing
the memory location using pointers. Every memory location is given a unique address, once you
know the address of a memory location (variable), you'll then be able to go to that address and
retrieve the data stored in it. To get the address of any variable, we can use & (Address of) operator
and to retrieve the value stored at a memory location we can use *(Value of Operator).
Advantages of Pointers
We can dynamically allocate or deallocate space in memory at run time by using pointers.
Using pointers we can return multiple values from a function.
We can pass arrays to a function as call by Reference.
Pointers are used to efficiently access array elements, as array elements are stored in
adjacent memory locations. If we have a pointer pointing to a particular element of array,
then we can get the address of next element by simply incrementing the pointer.
Pointers in C are used to efficiently implement dynamic Data Structures like Queues,
Stacks, Linked Lists, Tress etc.
The use of pointers results into faster execution of program.
Pointer Operators
While handling a data through pointers, we need to know the address of a variable and second is
given a memory address or pointer we want to access data stored at that location. Address of(&)
and Value of(*) operators are used to perform above mentioned pointer operations respectively.
Address of Operator(&)
The & is a unary operator in C which returns the memory address of the passed operand. This is
also known as address of operator. A pointer contains the memory address of some object.
Value of Operator(*)
The * is a unary operator which returns the value of object pointer by a pointer variable. It is
known as value of operator. It is also used for declaring pointer variable.
Example
int A = 100;
int *ptr = &A;
In the first statement, we first declare an integer variable and initialize it with value 100. In second
statement, we are declaring a pointer to a variable of type int and initializing it with address of A.
83
M&S PUBLICATIONS
Pointer Declaration
A pointer is a derived data type that is created from fundamental data types. We use (*) for
defining pointer variables. Here is the syntax of declaring a pointer variable.
<data_type> *<identifier>;
Program
#include <stdio.h>
#include <conio.h>
void main ()
{
int count = 10;
int *ptr = &count;
printf("Value of count variable is %d\n", count);
printf("Address of count variable: %x\n", ptr);
printf("Value retrieved through pointer : %d\n", *ptr);
getch();
}
NULL Pointers in C
NULL pointer in C is a pointer which is pointing to nothing. It is used to initialize a pointer at the
time of declaration if we don't have any explicit value to initialize. It is a good practice to initialize
a pointer with NULL to ensure that it is not pointer to a random memory location. The NULL is a
macro constant with a value of zero defined in various C header files like stdio.h, stdlib.h, alloc.h
etc.
#define NULL 0
Note: A pointer initialized with NULL is known as NULL pointer.
int *ptr = NULL;
Program
#include <stdio.h>
#include <conio.h>
void main()
{
int *ptr = NULL;
printf("The value of ptr is %x\n", ptr);
if(ptr == NULL)
{
printf("ptr is NULL Pointer\n");
}
if(!ptr)
{
printf("ptr is NULL Pointer\n");
}
getch();
}
Size of a pointer variable is system dependent. A memory address is considered as integer value.
Size of a pointer is fixed, it doesn't depend on the data type it is pointing to. We can use size of
operator to get the size of a pointer.
84
M&S PUBLICATIONS
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int count = 10;
float sum = 20.5;
int *null_ptr = NULL;
int *int_ptr = &count;
float *float_ptr = ∑
printf("Size of NULL Pointer : %d Bytes\n", sizeof(null_ptr));
printf("Size of Integer Variable : %d Bytes\n", sizeof(count));
printf("Size of Integer Pointer : %d Bytes\n", sizeof(int_ptr));
printf("Size of Float Variable : %d Bytes\n", sizeof(sum));
printf("Size of Float Pointer : %d Bytes\n", sizeof(float_ptr));
getch();
}
M&S PUBLICATIONS
char *(*ptr)[4] = &arr;
for(i=0;i<4;i++)
printf("Address of String %d : %u\n",i+1,(*ptr)[i]);
return 0;
}
Program
#include<stdio.h>
int main()
{
int i;
char *arr[4] = {"C","C++","Java","VBA"};
char *(*ptr)[4] = &arr;
for(i=0;i<4;i++)
printf("String %d : %s\n",i+1,(*ptr)[i]);
return 0;
}
C Programming Pointer to a Pointer
A pointer to a pointer is a pointer variable which is used to store the address of another variable.
A pointer can store the address of another pointer variable also like any other data type pointer. A
pointer to a pointer means, first pointer will contains the address of second pointer and second
pointer can will contain the add of actual value stored in memory. We use double * operator to
define a pointer to a pointer.
<data_type> **<identifier>;
Example
The exact size of array is unknown untill the compile time,i.e., time when
a compier compiles code written in a programming language into a
executable form. The size of array you have declared initially can be
sometimes insufficient and sometimes more than required. Dynamic
memory allocation allows a program to obtain more memory space, while
running or to release space when no space is required.
86
M&S PUBLICATIONS
Although, C language inherently does not has any technique to allocated memory dynamically,
there are 4 library functions under "stdlib.h" for dynamic memory allocation.
malloc() : The name malloc stands for "memory allocation". The function malloc() reserves a block
of memory of specified size and return a pointer of type void which can be casted into pointer of
any form.
ptr=(cast-type*)malloc(byte-size)
Program
#include <stdio.h>
#include <stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
getch();
}
calloc()
The name calloc stands for "contiguous allocation". The only difference between malloc() and
calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks
of memory each of same size and sets all bytes to zero.
ptr=(cast-type*)calloc(n,element-size);
Program
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
87
M&S PUBLICATIONS
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
free()
Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The
programmer must use free() explicitly to release space.
free(ptr);
realloc()
If the previously allocated memory is insufficient or more than sufficient. Then, you can change
memory size previously allocated using realloc()
ptr=realloc(ptr,newsize);
Program
#include <stdio.h>
#include <stdlib.h>
void main()
{
int *ptr,i,n1,n2;
printf("Enter size of array: ");
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i<n1;++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");
scanf("%d",&n2);
ptr=realloc(ptr,n2);
for(i=0;i<n2;++i)
printf("%u\t",ptr+i);
getch();
}
88
M&S PUBLICATIONS
Unit-IV
Chapter-IX
Structures & Unions in C
Structures
Structures in C are used to encapsulate, or group together different data into one object. C
structure is nothing but collection of different related data types. We are combining different
related data types in one group so that we can use and manage those variables easily.
A structure is a collection of variables under a single name. These variables can be of different
types, and each has a name which is used to select it from the structure. A structure is a
convenient way of grouping several pieces of related information together.
A structure can be defined as a new named data type, thus extending the number of available
types. It can use other structures, arrays, pointers or function as some of its members, though
this can get complicated unless you are careful. The variables you declare inside the structure are
called data members.
Syntax
struct structure_name
{
data type member1;
data type member2;
…
};
So structure declaration begins with struct keyword and with a space we need to provide a
structure name.
Declaration of Structure Variable
We can declare variable of structure once we defined the format of structure. There are two ways
of declaring a structure variable:
struct employee
Using struct keyword after structure definition. {
Declaring variables at the time of defining structure. char name[100];
int age;
Declare Variables using struct Keyword float salary;
char department[50];
The syntax of defining a structure variable is similar to the variable } employee_one;
declaration syntax of any basic data type in C. it uses struct keyword
followed by structure name as the data type.
struct structure_name variable_name;
Note: All member variables of a structure are stored in contiguous memory locations.
Initialization of Structure Variable
Like any other variable in C, we can initialize a structure variable at the time of declaration. We
can specify initial values as a comma separated list of constants enclosed between curly braces.
struct employee
{
char name[100];
int age;
float salary;
char department[50];
} employee_one = {"Jack", 30, 1234.5, "Sales"};
We can also initialize structure variable after structure declaration.
struct employee employee_one = {"Jack", 30, 1234.5, "Sales"};
89
M&S PUBLICATIONS
It is not compulsory to initialize all the member variables of a structure. Following statement
initializes only name member of structure employee and remaining members gets initialized with
zero (for integer and float) and NULL (for pointers and char).
Accessing Members of Structure in C
We cannot access members of a structure directly in any expression by specifying their name
alone. There are two ways to access structure members
Using Member Access Operator(.) or Dot Operator
structure_variable.member_name
Using Member Structure Pointer Operator or Arrow Operator (->): Structure pointer
operator or Arrow operator is used to access members of structure using pointer variable.
When we have pointer to a structure variable, then we can access member variable by using
pointer variable followed by an arrow operator and then the name of the member variable.
structure_pointer->member_name;
Program
#include<stdio.h>
struct student
{
char name[20];
int rollno;
float marks;
};
void main()
{
struct student s1 = {"abc", 1, 450};
struct student s2;
printf("Enter student Name, Rollno, Marks:\n");
scanf("%s%i%f", &s2.name, &s2.rollno, &s2.marks);
printf("\nStudent Name\tRollno\tMarks\n");
printf("%s\t%i\t%f", s1.name, s1.rollno, s1.marks);
printf("\n");
printf("%s\t%i\t%f",s2.name,s2.rollno,s2.marks);
getch();
}
Program
#include <stdio.h>
#include <conio.h>
struct employee
{
char name[100];
int age;
float salary;
char department[50];
};
void main()
{
struct employee employee_one, *ptr;
printf("Enter Name, Age, Salary and Department of Employee\n");
scanf("%s %d %f %s", &employee_one.name, &employee_one.age, &employee_one.salary,
&employee_one.department);
printf("Employee Details\n");
printf(" Name : %s\n Age : %d\n Salary = %f\n Dept : %s\n",employee_one.name,
employee_one.age, employee_one.salary,employee_one.department);
ptr = &employee_one;
90
M&S PUBLICATIONS
printf("\nEmployee Details\n");
printf(" Name : %s\n Age : %d\n Salary = %f\n Dept : %s\n",
ptr->name, ptr->age, ptr->salary, ptr->department);
getch();
}
Array of Structure in C Programming
A structure in C programming language is used to store set of parameters about an object/entity.
We sometime want to store multiple such structure variables for hundreds or objects then Array
of Structure is used.
Both structure variables and in-built data type gets same treatment in C programming language.
C language allows us to create an array of structure variable like we create array of integers or
floating point value. The syntax of declaring an array of structure, accessing individual array
elements and array indexing is same as any in-built data type array.
Declaration of Structure Array in C
In above declaration, we are declaring an array of 1000 employees where struct Employee
each employee structure contains name, age and salary members. Array {
employees[0] stores the information of 1st employee, employees[1] stores char name[50];
the information of 2nd employee and so on. int age;
float salary;
Accessing Structure Fields in Array }employees[1000];
We can access individual members of a structure
variable as struct Employee employees[1000];
array_name[index].member_name
Program
#include <stdio.h>
#include <conio.h>
struct employee
{
char name[100];
int age;
float salary;
};
void main()
{
struct employee employees[10];
int counter, index, count, totalSalary;
printf("Enter Number of Employees\n");
scanf("%d", &count);
for(counter=0; counter<count; counter++)
{
printf("Enter Name, Age and Salary of Employee\n");
scanf("%s %d %f", &employees[counter].name, &employees[counter].age,
&employees [counter].salary);
}
for(totalSalary=0, index=0; index<count; index++)
{
totalSalary += employees[index].salary;
}
printf("Average Salary of an Employee is %f\n", (float)totalSalary/count);
getch();
}
91
M&S PUBLICATIONS
Unions in C
Union in C programming language is similar to structures. Union is a user defined data structure
which is used to store different data type in same memory location. You can define a union with
many members, but at any given instance of time only one member can contain value. For union
variable, the storage space allocated is equal to the storage space needed by the largest data
member of the union.
Declaration of Union in C
Keyword union is used to define a union. The syntax to define union is similar to defining a
structure in C. The union declaration defines a custom data type, that can store multiple member
variables of different data types in same memory location.
Syntax
union union_name
{
data type member1;
data type member2;
…
};
Accessing Union Members
union union_name
To access any member of a union, we use the member access {
operator (.). The member access operator is coded as a period Body of the UNION;
between the union variable name and the union member that we wish };
to access. You would use the keyword union to define variables
of union type. Union_name.variable=name;
Advantage of Union over Structure: -
Unions efficiently utilize the same memory location for multi-purpose. It occupies less
memory because the storage space needed by the union is size of the largest data member.
Disadvantage of Union over Structure: -Unions cannot store multiple value at a time.
Program
#include <stdio.h>
#include <string.h>
#include <conio.h>
union Employee
{
char name[32];
int age;
float salary;
};
void main()
{
union Employee employee;
strcpy(employee.name, "Jack");
printf("Name = %s Address = %p\n", employee.name,&employee.name);
employee.age = 30;
printf("Age = %d Address = %p\n", employee.age,&employee.age);
employee.salary = 1234.5;
printf("Salary = %f Address = %p\n", employee.salary,&employee.salary);
printf("\nName = %s\n", employee.name);
printf("Age = %d\n", employee.age);
printf("Salary = %f\n", employee.salary);
getch();
}
92
M&S PUBLICATIONS
Difference between union and structure
Though unions are similar to structure in so many ways, the difference between them is crucial
to understand.
Structure Union
The keyword struct is used to define a The keyword union is used to define a union.
structure
When a variable is associated with a structure, When a variable is associated with a union,
the compiler allocates the memory for each the compiler allocates the memory by
member. The size of structure is greater than considering the size of the largest memory. So,
or equal to the sum of sizes of its members. The size of union is equal to the size of largest
smaller members may end with unused slack member.
bytes.
Each member within a structure is assigned Memory allocated is shared by individual
unique storage area of location. members of union.
The address of each member will be in The address is same for all the members of a
ascending order This indicates that memory for union. This indicates that every member begins
each member will start at different offset at the same offset value.
values.
Altering the value of a member will not affect Altering the value of any of the member will alter
other members of the structure. other member values.
Individual member can be accessed at a time Only one member can be accessed at a time.
Several members of a structure can initialize at Only the first member of a union can be
once. initialized.
Program
#include <stdio.h>
union job
{
char name[32];
float salary;
int worker_no;
}u;
struct job1
{
char name[32];
float salary;
int worker_no;
}s;
void main()
{
printf("size of union = %d",sizeof(u));
printf("\nsize of structure = %d", sizeof(s));
getch();
}
93
M&S PUBLICATIONS
Enumerated Data Types
An enumeration is used for defining named constant values. An enumerated type is declared using
the enum keyword.
Syntax
enum enum_name
{
enumeration list
}
The enum_name specifies the enumeration type name.
The enumeration list is a comma-separated list of identifiers.
Each of the symbols in the enumeration list stands for an integer value, one greater than the
symbol that precedes it. The enumerated data types are useful in numerous programming
situations where we refer to the individual items by specific names rather than integer numbers.
Example
enum month {JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,DEC};
enum month rmonth;
The use of an enumeration constant (enum) has many advantages over using the traditional
symbolic constant style of #define. These advantages include a lower maintenance requirement,
improved program readability, and better debugging capability.
enumerated constants are generated automatically by the compiler. Conversely, symbolic
constants must be manually assigned values by the programmer.
The enumeration constant method is that your programs are more readable and thus can
be understood better by others who might have to update your program later.
Some symbolic debuggers can print the value of an enumeration constant.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int roll1,roll2;
enum standard {FIRST,SECOND,THIRD,FOURTH};
enum standard s1,s2;
clrscr();
printf("\n Enter the roll numbers for two students");
scanf("%d%d",&roll1,&roll2);
s1=FIRST;
s2=FOURTH; /*assigning the standards*/
printf("\nThe Roll Number %d is in %d st Standard",roll1,s1+1);
printf("\nThe Roll Number %d is in %d th Standard",roll1,s2+1);
getch();
}
94
M&S PUBLICATIONS
Chapter-X
File Handling in C
A file is a collection of bytes stored on a secondary storage device, which is generally a disk of some
kind. The collection of bytes may be interpreted, C programming language provides access on high
level functions as well as low level (OS level) calls to handle file on your storage devices. For
example, as characters, words, lines, paragraphs and pages from a textual document; fields and
records belonging to a database; or pixels from a graphical image. The meaning attached to a
particular file is determined entirely by the data structures and operations used by a program to
process the file.
Why files are needed?
When the program is terminated, the entire data is lost in C programming. If you want to keep
large volume of data, it is time consuming to enter the entire data. But, if file is created, these
information can be accessed using few commands. There are large numbers of functions to handle
file I/O in C language.
File Operations
1. Creating a new file
2. Opening an existing file
3. Reading from and writing information to a file
4. Closing a file
Essentially there are two kinds of files that programmers deal with. High level file I/O functions
can be categorized as:
1. Text file
2. Binary file
These two classes of files will be discussed in the following sections.
ASCII Text files
A text file can be a stream of characters that a computer can process sequentially. It is not only
processed sequentially but only in forward direction. Similarly, since text files only process
characters, they can only read or write data one character at a time.
Binary files
A binary file has no difference to a text file. It is a collection of bytes. In C Programming Language
a byte and a character are equivalent. Hence a binary file is also referred to as a character stream,
but there are two essential differences.
No special processing of the data occurs and each byte of data is transferred to or from the
disk unprocessed.
C Programming Language places no constructs on the file, and it may be read from, or
written to, in any manner chosen by the programmer.
Creating a file and output some data
In order to create files we have to learn about File I/O i.e. how to write data into a file and how to
read data from a file. Function Name Operation
The type FILE is used for a file fopen() Creates a new file. Opens an existing file.
variable and is defined in the fclose Closes a file which has been opened for use
stdio.h file. It is used to define a file getc() Reads a character from a file
pointer for use in file operations. putc() Writes a character to a file
Before we can write to a file, we fprintf() Writes a set of data values to a file
must open it. What this really fscanf() Reads a set of data values from a file
means is that we must tell the
system that we want to write to a file and what the file name is. We do this with the fopen() function
illustrated in the first line of the program. The following are the different methods used for the
creating a file and output some of the data from the file.
95
M&S PUBLICATIONS
fopen() :- The fopen () function opens a file whose name is pointed to by ‘filename’ and
returns the stream that is associated with it. The type of operation that will be allowed on
the file are defined by the vale of mode.
Syntax
FILE * fopen (const char *filename, const char *mode);
File
Meaning
Type
“r” Open an existing file for reading only
Open a new file for writing only. If a file with the specified file-name currently
“w”
exists, it will be destroyed and a new file created in its place.
Open an existing file for appending (i.e., for adding new information at the end
“a” of the file). If a file with the specified file-name currently does not exist, a new
file will be created.
“r+” Open an existing file for both reading and writing.
Open a new file for both reading and writing. If a file with the specified file-name
“w+”
currently exists, it will be destroyed and a new file created in its place.
Open an existing file for both reading and appending. If a file with the specified
“a+”
file-name currently does not exist, a new file will be created.
fclose() :- The fclose function closes the file associated with stream and flushes its buffer
(i.e., it writes any data still remaining in the disk buffer to the file). After a call to fclose(),
stream is no longer connected with the file, and any automatically allocated buffers are
deallocated. If fclose() is successful, zero is returned; otherwise EOF is returned.
Syntax
fclose (FILE *stream);
fputc(): -The fputc() function writes the character to the specified stream at the current file
position and then advance the file position indicator.
Syntax
fputc(int ch,FILE *stream);
fgetc():- The fgetc() function returns the next character from the specified input stream and
increments the file position indicator. The character is read as an unsigned char that is
converted to an integer. If the end-of-file is reached, fgetc() returns EOF. If fgetc() encounters
an error, EOF is also returned.
Syntax
fgetc(FILE *stream);
fputs():- The fputs() function writes the content of the string pointed to the specified stream.
The null terminator is not written. The fputs() function returns non negative on success and
EOF on failure.
Syntax
char * fputs(const char *str , FILE *stream);
fgets():- The fgets() function reads up to character from stream and store them into a
character array pointed. Characters are read until either a newline or an EOF is received or
until the specified limit is reached. After the character has been read, a null is stored in the
array immediately after the last character is read. A newline character will be retained and
will be a part of the array pointed.
Syntax
char * fgets(char *str,int num, FILE *stream);
96
M&S PUBLICATIONS
fscanf():- The fscanf function works exactly like the scanf function except that it reads the
information from the stream specified by stream instead of standard input device.
Syntax
fscanf (FILE *stream, const char *format,…..);
fprintf():- The fprintf() function outputs the values of the arguments that makes up the
argument list as specified in the format string to the stream pointed to by stream. The
operations of the format control string and command are identical to those in printf().
Syntax
fprintf (FILE *stream, const char *format,…..);
putc():- The putc() function writes the character to the specified stream at the current file
position and then advance the file position indicator. The value returned by the putc() is the
value of the character written . If an error occurs, EOF is returned. The putc() and fputc()
are identical.
Syntax
putc(int ch, FILE *stream);
getc():- The getc() function returns the next character from the specified input stream and
increment file position indicator. If the end-of-file is reached, getc() returns EOF. If getc()
encounters an error, EOF is also returned. The function getc() and fgetc() are identical.
Syntax
getc(FILE *stream);
Program to create a file and write some data the file
#include <stdio.h>
#include <stdio.h>
main( )
{
FILE *fp;
char stuff[25];
int index;
fp = fopen("TENLINES.TXT","w"); /* open for writing */
strcpy(stuff,"This is an example line.");
for (index = 1; index <= 10; index++)
fprintf(fp,"%s Line number %d\n", stuff, index);
fclose(fp); /* close the file before ending program */
}
#include <stdio.h>
void main()
{
FILE *fopen(), *fp;
int c;
fp = fopen("prog.c","r");
c = getc(fp) ;
while (c!= EOF)
{
putchar(c);
c = getc(fp);
}
fclose(fp);
}
97
M&S PUBLICATIONS
Program for writing the text into a file
#include <stdio.h>
int main()
{
FILE *fp;
FILE = fopen("file.txt","w");
/*Create a file and add text*/
fprintf(fp,"%s","This is just an example :)"); /*writes data to the file*/
fclose(fp); /*done!*/
return 0;
}
#include <stdio.h>
int main()
{
FILE *fp
FILE = fopen("file.txt","a");
fprintf(fp,"%s","This is just an example :)"); /*append some text*/
fclose(fp);
return 0;
}
#include <stdio.h>
main( )
{
FILE *fp;
char c;
funny = fopen("TENLINES.TXT", "r");
if (fp == NULL)
printf("File doesn't exist\n");
else
{
do
{
c = getc(fp); /* get one character from the file
*/putchar(c); /* display it on the monitor */
} while (c != EOF); /* repeat until EOF (end of file)*/
}
fclose(fp);
}
What are Binary Files?
Binary Files Contain Information Coded Mostly in Binary Format.
Binary Files are difficult to read for human.
Binary Files can be processed by certain applications or processors.
Only Binary File Processors can understood Complex Formatting Information Stored in
Binary Format.
Humans can read binary files only after processing.
All Executable Files are Binary Files.
Binary file is stored in Binary Format (in 0/1). This Binary file is difficult to read for humans. So
generally Binary file is given as input to the Binary file Processor. Processor will convert binary file
into equivalent readable file.
98
M&S PUBLICATIONS
Some Examples of the Binary files
Executable Files
Database files
This is about using random access files in C. Apart from the simplest of applications, most
programs have to read or write files. Maybe it's just for reading a config file, or a text parser or
something more sophisticated.
There are two fundamental types of file: text and binary. Of these two, binary are generally the
simpler to deal with. The first four operations listed are for both text and random access files. The
last two just for random access.
fopen - open a file- specify how its opened (read/write) and type (binary/text)
fclose - close an opened file
fread - read from a file
fwrite - write to a file
fseek/fsetpos - move a file pointer to somewhere in a file.
ftell/fgetpos - tell you where the file pointer is located
Random access means we can move to any part of a file and read or write data from it without
having to read through the entire file. Back thirty years ago, much data was stored on large reels
of computer tape. The only way to get to a point on the tape was by reading all the way through
the tape. Then disks came along and now we can read any part of a file directly.
Programming with Binary Files
A binary file is a file of any length that holds bytes with values in the range 0 to 0xff. (0 to 255).
These bytes have no other meaning unlike in a text file. In modern terms we call binary files a
stream of bytes and more modern languages tend to work with streams rather than files.
99
M&S PUBLICATIONS
The important part is the data stream rather than where it came from! In C you can think about
the data either in terms of files or streams. Or if it helps, think of a file/stream as a very long
array! With random access you can read or write to any part of this array. With sequential you
have to loop through it from the start like a big tape.
Program
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
const char *filename="test.txt";
const char *mytext="Once upon a time there were three bears.";
int byteswritten=0;
FILE *ft= fopen(filename, "wb");
if(ft)
{
fwrite(mytext,sizeof(char),strlen(mytext), ft);
fclose( ft );
}
printf("len of mytext = %i ",strlen(mytext));
return 0;
}
Program
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
int size = 0;
fp = fopen("MyFile.txt", "r");
if (fp == NULL)
{
printf("\nFile unable to open ");
}
else
{
printf("\nFile opened ");
}
fseek(fp, 0, 2); /* file pointer at the end of file */
size = ftell(fp); /* take a position of file pointer un size variable */
printf("The size of given file is : %d\n", size);
fclose(fp);
getch();
}
100