Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
458 views

C Programming Lecture Notes 1

The document provides an overview of computers and their history. It discusses how Charles Babbage first developed the concept of a computer in 1812 and how subsequent generations made computers smaller, faster, and more powerful. It describes how computers store and analyze information based on programs written in languages like BASIC, COBOL, FORTRAN, C, C++, Java and Visual Basic. The document outlines how computers have revolutionized areas like business, medicine, transportation and more by performing calculations faster and storing large amounts of data. It acknowledges both the benefits of computers in connecting people globally and streamlining tasks, as well as some negative impacts like the rise of cybercrime.

Uploaded by

anilperfect
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
458 views

C Programming Lecture Notes 1

The document provides an overview of computers and their history. It discusses how Charles Babbage first developed the concept of a computer in 1812 and how subsequent generations made computers smaller, faster, and more powerful. It describes how computers store and analyze information based on programs written in languages like BASIC, COBOL, FORTRAN, C, C++, Java and Visual Basic. The document outlines how computers have revolutionized areas like business, medicine, transportation and more by performing calculations faster and storing large amounts of data. It acknowledges both the benefits of computers in connecting people globally and streamlining tasks, as well as some negative impacts like the rise of cybercrime.

Uploaded by

anilperfect
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 105

lOMoARcPSD|4381973

C Programming - Lecture notes 1

Electronic and Communication Engineering (Osmania University)

StuDocu is not sponsored or endorsed by any college or university


Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)
lOMoARcPSD|4381973

G.Venkata Subba Reddy.


M.Sc(Comp.Science)

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

Silent Features
1. Complete Syllabus Covered According to the latest CBCS

Syllabus.

2. Subject deals with Simple and Easy Understanding Language.

3. Includes Internal Assignment.

4. Student & Lecturer Friendly.

5. All the Practical’s are covered according to the Syllabus.

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

Computer languages are best learned by


“Writing
&
Debugging Programs.”

Computer Fundamentals and Programming in C is designed to serve for the


undergraduate students of computer science, computer applications, and information
technology. This book provide a thorough overview of all the fundamental concepts
related to computer science and programming. It lays down the foundation for all the
advanced courses that a student is expected to learn in the following semesters.

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.

A program should be as simple as possible. A programmer should avoid clever tricks.


This book stresses simple, practical rules. This handbook is written for people with no
previous programming experience or programmers who already know C and want to
improve their style and reliability. You should have access to a computer and know how
to use the basic functions.

Author….

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

A computer can execute over a million instructions per second


without committing and mistake. It can carry our calculations
in just a few minutes that would require days if carried out
manually. It helps us in solving many difficult problems of
multiple calculations. Computer has a huge memory. It can hold large amount of data.

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.

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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 major advantage of using computers is given below.


1. Computers makes it possible to receive, supply and process large volumes of data at very
high speed.
2. Computer reduces the cost of all data related operations including, input, output, storage,
processing, and transmission.
3. Computer greatly improves the speed of data input, output, processing, and transmission.
4. Computer ensures consistent and error free processing of data.
5. The data input, output, and processing speed of computers has enabled development of
many applications requiring speedy continuous monitoring of a process or situation and
responding to it very quickly in real time.
Disadvantages 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.

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Each generation of computers is characterized by major technological development that


fundamentally changed the way computers operate, resulting in increasingly smaller, cheaper and
powerful, efficient and reliable devices. Read about each generation and the developments that led
to the current devices that we use today.

First Generation - 1940-1956: Vacuum Tubes

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.

They were very expensive to operate and in addition to using a great


deal of electricity, generated a lot of heat, which was often the cause of malfunctions. First

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

Prior to the invention of transistors, digital circuits


were composed of vacuum tubes, which had many
disadvantages. They were much larger, required more
energy, dissipated more heat, and were more prone to failures. It's safe to say that without the
invention of transistors, computing as we know it today would not be possible. The examples of
second generation computers are IBM 7094 series, IBM 1400 series and CDC 164 etc.

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

Semiconductor is a material that is neither a good conductor


of electricity (like copper) nor a good insulator (like rubber).
The most common semiconductor materials are silicon and
germanium. These materials are then doped to create an excess or lack of electrons.

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

Three basic characteristics differentiate microprocessors


 Instruction Set: The set of instructions that the microprocessor can execute.
 Bandwidth: The number of bits processed in a single instruction.
 Clock Speed: Given in megahertz (MHz), the clock speed determines how many instructions
per second the processor can execute.
Abbreviation of central processing unit, and pronounced as separate letters. The CPU is the brains
of the computer. Sometimes referred to simply as the processor or central processor, the CPU is
where most calculations take place. In terms of computing power, the CPU is the most important
element of a computer system.

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 .

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Currently, no computers exhibit full artificial intelligence


(that is, are able to simulate human behavior). The
greatest advances have occurred in the field of games
playing. The best computer chess programs are now
capable of beating humans. In May 1997, an IBM super-
computer called Deep Blue defeated world chess
champion Gary Kasparov in a chess match.

There are also voice recognition systems that can convert


spoken sounds into written words, but they do not
understand what they are writing; they simply take dictation. Even these systems are quite limited
you must speak slowly and distinctly.

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Notebook computers as the name implies is approximately the size of an 8.5-


11 inch notebook and can easily fit inside a briefcase. Since most people
including yourself would set this device on your lap and use it conveniently in
eateries, cafes, at the work place, in education institutions and so on, hence
the name laptop.

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.

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

This is the process of entering data and programs in to


the computer system. You should know that computer is an electronic machine like any other
machine which takes as inputs raw data and performs some processing giving out processed data.
Therefore, the input unit takes data from us to the computer in an organized manner for
processing.

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.

Arithmetic Logical Unit (ALU) Logical Unit

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.

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

M&S PUBLICATIONS
Joy stick

A joystick is an input device commonly used to control video games.


Joysticks consist of a base and a stick that can be moved in any direction.
The stick can be moved slowly or quickly and in different amounts. Some
joysticks have sticks that can also be rotated to the left or right. Because
of the flexible movements a joystick allows, it can provide much greater
control than the keys on a keyboard.

Joysticks typically include several buttons as well. Most joysticks have at


least one button on the top of the stick and another button in the front of
the stick for the trigger.

Scanner

A scanner is an input device that scans documents such as photographs and


pages of text. When a document is scanned, it is converted into a digital format.
This creates an electronic version of the document that can be viewed and
edited on a computer.
Most scanners flatbed devices, which means they have a flat scanning surface.
This is ideal for photographs, magazines, and various documents. Most flatbed scanners have a
cover that lifts up so that books and other bulky objects can also be scanned.

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 is an input device which is used to draw lines or figures on a computer


screen. It’s touched to the CRT screen where it can detect raster on the screen
as it passes.

Bar Code Reader

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.

Voice Input Systems

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

"Monitor" can also be used as a verb. A network administrator may


monitor network traffic, which means he watches the traffic to make sure the bandwidth usage is
within a certain limit and checks to see what external sources may be attempting to access the
network. Software programs may monitor the system's CPU performance as well as RAM and hard
disk usage.

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.

The printing speed of a printer is usually expressed in pages per minute


(ppm). Printer resolution is often expressed in dpi (dots per inch). The larger
the number, the higher the resolution.

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

Computer users focus on the CPU speed as a measurement of the overall


capabilities and performance of a system. The fact is that there are other
factors besides the processor's speed that must be taken into consideration.
The CPU is the component that is often referred to as the intelligence behind
the computer. It interprets instructions and performs computations and
operations. A CPU is attached on the motherboard of every computer.

"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.

Components inside the CPU

 Registers (Processing Memory)


 Control Unit (CU)
 Arithmetic and Logical Unit (ALU)
Registers

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

Storage can be classified into two types


 Internal storage or Primary Storage
 External/removable storage or Secondary Storage

Primary Storage Devices


Memory Units
Primary storage, also known as main storage or
1 Bit = Binary Digit
memory, memory is the main area in a computer in
8 Bits = 1 Byte
which data is stored for quick access by the
1024 Bytes = 1 KB (Kilo Byte)
computer's processor. Today's smaller computers,
1024 KB = 1 MB (Mega Byte)
especially personal computers primary storage is the
1024 MB = 1 GB (Giga Byte)
storage device that is directly connected to the CPU
1024 GB = 1 TB (Terra Byte)
and store data temporarily during execution. Primary
1024 TB = 1 PB (Peta Byte)
storage device are volatile in nature. Primary Storage
1024 PB = 1 EB (Exa Byte)
Devices are as follows
1024 EB = 1 ZB (Zetta Byte)
1024 ZB = 1 YB (Yotta Byte)  RAM
1024 YB = 1 (Bronto Byte)  ROM
 CACHE MEMORY
1024 Bronto byte = 1 (Geop Byte)

Random Access Memory (RAM)

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

Read Only Memory (ROM)

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.

ROM is memory containing hardwired instructions that the computer uses


when it boots up, before the system software loads. In PCs, the instructions
are read from a small program in the ROM, called the BIOS (Basic Input/Output System). ROM is
classified into different types
 Pure Rom
 Prom (Programmable Read Only Memory)
 EPRom(Erasable Programmable Read Only Memory)
 EEPRom (Electronically Erasable Programmable Read Only Memory)
Cache Memory

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

The first floppy disks were created in 1969, the same


year the Internet had its origin. These disks were 8 inches in diameter
and were read-only, like a CD-ROM, meaning no data could be written
17

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Types of Operating System

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

Types of System Software


Different types of system software are as follows:
 Utility Programs: - A utility program is a type of system software that is used to perform a
specific task. It is normally used to solve the common problems of software and hardware.
Antivirus and file compressor are two examples of utility programs.
 Device Drivers: - A device driver is a program that is used to operate and control a device
attached to computer. Device drivers are provided by manufactures of devices. The devices
cannot function properly without device drivers.
Application Software
Application software, on the other hand, is used to accomplish specific tasks other than just
running the computer system. Application software may consist of a single program, such as an
image viewer; a small collection of programs (often called a software package) that work closely
together to accomplish a task, such as a spreadsheet or text processing system; a larger collection
(often called a software suite) of related but independent programs and packages that have a
common user interface or shared data format, such as Microsoft Office, which consists of closely
integrated word processor, spreadsheet, database, etc.; or a software system, such as a database
management system, which is a collection of fundamental programs that may provide some service
to a variety of other independent applications.
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 (often called Integrated Development Environments) that include
editors, debuggers, and other tools for multiple languages.
Operating Systems for Computers List

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

Linux Apple Macintosh


 Unix  Apple DOS
 Red Hat Linux  GS/OS
 Mandrake Linux  Mac System Software 01-09
 Ubuntu  Mac OSX

20

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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?

A programming language is a computer language engineered to create a standard form of


commands. These commands can be interpreted into a code understood by a machine. Programs
are created through programming languages to control the behavior and output of a machine
through accurate algorithms, similar to the human communication process. A programming
language is also known as a programming system, computer language or computer system.
A programming language is typically divided into two elements: syntax and semantics. There is
pretty much always a specification document to define both elements. Programming language logic
differs by developer. From a high level, good code can be evaluated with factors such as:

 Robustness: Focuses on program continuation capability, regardless of errors or


incorrect data
 Reliability: Focuses on correct design and algorithm implementation
 Efficiency: Focuses on memory, hardware or other properties used to optimize
programs
 Readability: Proper documentation and indentation availability, which provides
insight to other program developers or designers
21

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

 Second Generation Language or Assembly Language: As We know that the Program


which is Written into the Machine Language are very difficult to understand for the user So
that there is the Development of the new Programming Language which is also known as
the second Generation Language Which is also known as the Assembly Language and in
the Assembly Language there are Many Mnemonics those are also Called as the Reserve
Words those are easy to understand to the users and those have Some Specific Meaning.
In the Assembly Language the Programs are written into the Form of some Words those are
Machine Oriented Mans which has the Specific Meaning and the Words those are easily
understand by the Machine Language. But the Words are not Machine Language Oriented
Means the Words are Just the English Language Forms so that they are not easily
understand by the Machine and we must have to convert the Words of the Assembly
Language into the Machine Language and For Converting the Assembly Language into the
Machine Language we must uses the Assembler. This Converts the Whole Program which
is written into the Assembly Language into the Machine Language.
 Third Generation Language or Some High Level Languages: Due to the Development of
the Assembly Language and the Mnemonics there is also the new development of Some
High Level Languages those are used for making the Programs. There are Many High Level
Programming Languages has developed at that Tim which contains the Java, c, C++, LOGO
etc.
All the High Level Programming Languages are User Friendly means the Syntax of theses
Languages is Quite Simple because they Contains all the Words those are in the Form of
English Language but the Main Problem is that they are not Machine Oriented Means the
Program which is written into the High Level Languages is not understand by the Computer
So that the Program Must be Converted into the Machine Language and the Program which
is Written into the Human Language will cause the Computer in Slow of Processing.

22

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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?

Programming logic is a fundamental construct that's applied to computer science in a variety of


comprehensive ways. Programming logic involves logical
operations on hard data that works according to logical
principles and quantifiable results.
The term programming logic has its roots in the
advancement of computer science. Programming logic
started only with 'hard and fast logic’ compiled into
sophisticated algorithms and expressed in programming
languages. Basic computers developed ways to deal with
numbers and logical states, applying specific operators
that lead to precise results.
The important distinction here is that programming logic, and logic in general, is fundamentally
set against other kinds of programming that are not built on hard logic or quantifiable states and
results.
Programming logic in general rests on a foundation of computational logic that is shared by both
humans and machines, which is what we explore as we continue to interact with new technologies.
With that in mind, one could develop more specific definitions of a programming logic having to
do with the basis of a piece of code.
Differences between High Level Languages and Low Level Languages

High-level Language Low-level languages


High-level languages are easy to learn Low-level languages are difficult to learn
High0level languages are near to human Low-level languages are far from human
languages. languages.
Programs in high-level languages are slow Programs in low-level languages are fast in
in execution. execution.
Programs in high-level languages are easy Programs in low-level languages are
to modify. difficult to modify.
High-level languages do not provide much Low-level languages provide facility to write
facility at hardware level. programs at hardware level.
Knowledge of hardware is not required to Deep knowledge of hardware is required to
write programs. write programs.
These languages are normally used to write These languages are normally used to write
application programs. hardware programs.

23

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

M&S PUBLICATIONS
in system functions or access hardware resources like compiled programs can. Therefore, most
software applications are compiled rather than interpreted.

Difference between Interpreter and Compiler


We generally write a computer program using a high-level language. A high-level language is one
which is understandable by us humans. It contains words and phrases from the English (or other)
language. But a computer does not understand high-level language. It only understands program
written in 0's and 1's in binary, called the machine code. A program written in high-level language
is called a source code. We need to convert the source code into machine code and this is
accomplished my compilers and interpreters. Hence, a compiler or an interpreter is a program that
converts program written in high-level language into machine code understood by the computer.

The difference between an interpreter and a compiler is given below

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

Qualities of a good algorithm

 Inputs and outputs should be defined precisely.


 Each steps in algorithm should be clear and unambiguous.
 Algorithm should be most effective among many different ways to solve a problem.
 An algorithm shouldn't have computer code. Instead, the algorithm should be written in
such a way that, it can be used in similar programming languages.
Write an algorithm to add two numbers entered by user.

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

Different ways of stating Algorithms

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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).

When to Use a Flowchart

To develop understanding of how To study a process for


a process is done improvement.
When better communication
To communicate to others how a is needed between people
process is done. involved with the same
process.
To document a process. When planning a project

31

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

M&S PUBLICATIONS
Flowchart Basic Procedure

Materials needed: sticky notes or cards, a large piece of flipchart paper or newsprint, marking
pens.

1. Define the process to be diagrammed.


Write its title at the top of the work surface.
2. Discuss and decide on the boundaries of
your process: Where or when does the process
start? Where or when does it end? Discuss and
decide on the level of detail to be included in the
diagram.
3. Brainstorm the activities that take place.
Write each on a card or sticky note. Sequence is
not important at this point, although thinking
in sequence may help people remember all the
steps.
4. Arrange the activities in proper sequence.
5. When all activities are included and everyone agrees that the sequence is correct, draw
arrows to show the flow of the process.
6. Review the flowchart with others involved in the process (workers, supervisors, and
suppliers, customers) to see if they agree that the process is drawn accurately.
Structured Programming (Modular Programming)

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 (sometimes known as modular programming) is a subset of procedural


programming that enforces a logical structure on the program being written to make it more
efficient and easier to understand and modify. Certain languages such as Ada, Pascal, and dBASE
are designed with features that encourage or enforce a logical program structure.

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

Assembly Level 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.

High Level Language

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

Advantages of High Level Language

Following are the advantages of a high level language

 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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

Saving a Program in Turbo C

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.

Making an Executable File in Turbo C

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).

Compiling and linking in the Turbo C IDE


In the Turbo C IDE, compiling and linking can be performed together in one step. There are two
ways to do this: you can select Make EXE from the compile menu, or you can press the [F9] key.
Correcting Errors in Turbo C
If the compiler recognizes some error, it will let you know through the Compiler window. You’ll see
that the number of errors is not listed as 0, and the word “Error” appears instead of the word
“Success” at the bottom of the window. The errors are to be removed by returning to the edit
window. Usually these errors are a result of a typing mistake. The compiler will not only tell you
what you did wrong, they’ll point you to the exact place in your code where you made the mistake.
Executing a Programs in Turbo C

If the program is compiled and linked without errors,


the program is executed by selecting Run from the Run
Menu or by pressing the [Ctrl+F9] key combination.

Exiting Turbo C IDE


An Edit window may be closed in a number of different ways. You can click on the small square
in the upper left corner, you can select close from the window menu, or you can press the Alt+F3
combination. To exit from the IDE, select Exit from the File Menu or press Alt+X Combination.

34

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

 UNIX developed c. 1969 -- DEC PDP-7 Assembly Language


 BCPL -- a user friendly OS providing powerful development tools developed from BCPL.
Assembler tedious long and error prone.
 A new language ``B'' a second attempt. c. 1970.
 A totally new language ``C'' a successor to ``B''. in 1972
 By 1973 UNIX OS almost totally written in ``C''.
Why Use 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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

M&S PUBLICATIONS
C Fundamentals
C-Program Structure

A C program basically has the following form


 Preprocessor Commands
 Functions
 Variables
 Statements & Expressions
 Comments
The following program is written in the C programming language.

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.

Statements & Expressions

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.

Note the followings

 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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

C program executes in following 4 (four steps).

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.

Compiling the program

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.

Linking a program to library Header Purpose


The object code of a program is linked with libraries assert.h Defines the assert() macro
that are needed for execution of a program. The ctype.h Character handling
linker is used to link the program with libraries. It errno.h Error reporting
creates a file with '*.exe' extension in compilation Defines implementation-
step. float.h
dependent floating-point limits
Code files are not the only files commonly seen in limits.h dependent limits
programs. The other type of file is called a header locale.h Localization
file, sometimes known as an include file. Header math.h math library
files almost always have a .h extension. The purpose setjmp.h Nonlocal jumps
of a header file is to hold declarations for other files
signal.h Signal handling
to use.
stdarg.h Variable argument lists
Execution of program stddef.h Constants
The final executable file is then run by Ctrl+F9 or by stdio.h I/O system
any other software to produce the out put.

37

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

Auto Break Case Char Const


Default Do goto if sign
Double Else Enum extern float
Int Long Register Return Short
Struct Switch typedef union unsigned
Volatile While continue Sizeof For
Static Void
Identifiers

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Rules for defining variables pointer NULL

 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.

Data Types in C- Programming


C language provides various data types for
holding different kinds of values. There are
several integral data types, a character data
type, floating point data types for holding real
numbers and more.
A programming language is proposed to help
programmer to process certain kinds of data
and to provide useful output. The task of data
processing is accomplished by executing
series of commands called program. A
program usually contains different types of
data types (integer, float, character etc.) and
need to store the values being used in the program. C language is rich of data types. C has different
data types for different types of data and can be broadly classified as:
 Primary data types
 Secondary data types

39

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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 type has no values therefore we


cannot declare it as variable as we did in case
of integer and float.

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

 In programming, an expression is any legal combination of symbols that represents


a value.
 C Programming provides its own rules of Expression, whether it is legal expression
or illegal expression. For example, in the C language x+5 is a legal expression.
 Every expression consists of at least one operand and can have one or more
operators.
 Operands are values and Operators are symbols that represent particular actions.
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression;
Variable is any valid C variable name. When the statement is encountered, the expression is
evaluated first and then replaces the previous value of the variable on the left hand side. All
variables used in the expression must be assigned values before evaluation is attempted.
Example
x=a*b–c
y=b/c*a
z = a – b / c + d;
Program
#include<stdio.h>
#include<conio.h>
void main()
{
float a, b, c x, y, z;
a = 9;
b = 12;
c = 3;
x = a – b / 3 + c * 2 – 1;
y = a – b / (3 + c) * (2 – 1);
z = a – ( b / (3 + c) * 2) – 1;
printf (“x = %fn”,x);
printf (“y = %fn”,y);
printf (“z = %fn”,z);
getch();
}
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.
Operator precedence & associativity
C Programming supports wide range of operators. While Solving the Expression we must follow
some rules
Operator precedence & associativity table
Operator precedence & associativity are listed in the following table and this table is summarized
in decreasing Order of priority i.e topmost operator has highest priority and bottommost operator
has Lowest Priority.

46

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

M&S PUBLICATIONS

Operator Description Associativity

() Parentheses (function call) left-to-right


[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ – Postfix increment/decrement

++ – Prefix increment/decrement right-to-left


+– Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation

* / % Multiplication/division/modulus left-to-right

+ – Addition/subtraction left-to-right

<< >> Bitwise shift left, Bitwise shift right left-to-right

< <= Relational less than/less than or equal to left-to-right


> >= Relational greater than/greater than or equal to

== != Relational is equal to/is not equal to left-to-right

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

&& Logical AND left-to-right

|| Logical OR left-to-right

?: Ternary conditional right-to-left

= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment

, Comma (separate expressions) left-to-right

Summary of operator precedence


1. Comma Operator Has Lowest Precedence.
2. Unary Operators are Operators having Highest Precedence.
3. Sizeof is Operator not Function.
4. Operators sharing Common Block in the Above Table have Equal Priority or Precedence.
5. While Solving Expression, Equal Priority Operators are handled on the basis of FIFO i.e
Operator Coming First is handled first.

47

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

There are two types of type casting in c language.


 Implicit Conversion: -Implicit conversions do not required any operator for converted.
They are automatically performed when a value is copied to a compatible type in program.
 Explicit Conversion: -In c language, Many conversions, especially those that imply
a different interpretation of the value, require an explicit conversion. We have
already seen two notations for explicit type conversion. They are not automatically
performed when a value is copied to a compatible type in program.
(type_name) expression
Program

#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

The usual arithmetic conversions are implicitly performed to cast their


values to a common type. The compiler first performs integer promotion,
if the operands still have different types, then they are converted to the
type that appears highest.

48

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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();
}

Looping Statements / Iterative Statements

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

M&S PUBLICATIONS
Types of looping statements

The following are the types of Looping Statements.


 While Loop
 Do-While Loop
 For Loop
This is an entry controlled looping statement. It is used to repeat a block of statements until
condition becomes false.
Syntax

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

This is an exit controlled looping statement. Sometimes, there is need to


execute a block of statements first then to check condition. At that time
such type of a loop is used. In this, block of statements are executed first
and then condition is checked.
Syntax

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.

Note: The while statement should be terminated with; (semicolon).

54

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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;

NOTE: Use of goto statement is highly discouraged in any programming


language because it makes difficult to trace the control flow of a program,
making the program hard to understand and hard to modify. Any program that uses a goto can
be rewritten to avoid them.

56

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

The break statement in C programming has the following two usages,

 When a break statement is encountered inside a loop, the loop


is immediately terminated and the program control resumes at the
next statement following the loop.
 It can be used to terminate a case in the switch statement
(covered in the next chapter).
If you are using nested loops, the break statement will stop the execution
of the innermost loop and start executing the next line of code after the
block.
Syntax
break;
Program
#include <stdio.h>
void main ()
{
int a = 10;
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
break;
}
}
getch();
}

57

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Multidimensional array can be declared as.


Syntax
<data type> array_name[size_of_row][size_of_column]
Initializing 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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

M&S PUBLICATIONS
Accessing Elements in Multidimensional Arrays

To access elements in a multidimensional array, all you have to do is provide a combination of


index values for each dimension to reach the desired element, just like a bunch of cells in a
spreadsheet or coordinates in an n dimensional matrix or graph.
Syntax
array_name[dim1_index][dim2_index] ... [dimn-1_index];
Setting values in a multidimensional array is just as simple as in a basic array; you need to add
another index per dimension.
Syntax
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
printf("%c", array_name[i][j]);
}
}
Example
#include <stdio.h>
#include <conio.h>
void main()
{
int a[3][3], i, j;
clrscr();
printf("\n\t Enter matrix of 3*3 : ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
scanf("%d",&a[i][j]); //read 3*3 array
}
}
printf("\n\t Matrix is : \n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("\t %d",a[i][j]); //print 3*3 array
}
printf("\n");
}
getch();
}
String Handling in C
A string is a collection of characters. Strings are always enclosed in double quotes as "string
constant". Strings are used in string handling operations such as,
 Counting the length of a string.
 Comparing two strings.
 Copying one string to another.
 Converting lower case string to upper case.
 Converting upper case string to lower case.
 Joining two strings.
 Reversing string.
60

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

Function Name Description


strlen() Returns the Length of the String
strlwr() Returns Upper case to Lower case Letters
strupr() Returns Lower case to Upper case Letters
strcat() Concatenate two Strings
strrev() Returns the reverse of the string
strcpy() Copies a string from source to destination

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

isalpha() checks whether character is alphabetic

isdigit() checks whether character is digit

isalnum() checks whether character is alphanumeric

isspace() checks whether character is space

islower() checks whether character is lower case

isupper() checks whether character is upper case

isxdigit() checks whether character is hexadecimal

iscntrl() checks whether character is a control character

isprint() checks whether character is a printable character

ispunct() checks whether character is a punctuation

isgraph() checks whether character is a graphical character

tolower() checks whether character is alphabetic & converts to lower case

toupper() checks whether character is alphabetic & converts to upper case

C – isalpha() function: isalpha( ) function in C language checks whether given character is


alphabetic or not.
int isalpha ( 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 alphabetic" ) ;
else
printf ( "\nEntered character is not alphabetic" ) ;
getch();
}
C – isdigit() function:isdigit( ) function in C language checks whether given character is digit or
not.
int isdigit ( int x );

62

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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();
}

C – isalnum() function: isalnum() function in C language checks whether given character is


alphanumeric or not.
int isalnum ( int x );
Program
#include <stdio.h>
void main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isalnum ( ch ) )
printf ( "\nEntered character is alphanumeric" ) ;
else
printf ( "\nEntered character is not alphanumeric" ) ;

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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();
}

C – isxdigit() function: isxdigit( ) function in C language checks whether given character is


hexadecimal or not.
int isxdigit( int x );
Program
#include <stdio.h>
void main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isxdigit ( ch ) )
printf ( "\nEntered character is hexadecimal" ) ;
else
printf ( "\nEntered character is not hexadecimal" ) ;
getch();
}
C – iscntrl() function: iscntrl( ) function in C language checks whether given character is control
character or not.

int iscntrl( int x );

64

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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();
}

C – tolower() function: tolower( ) function in C language checks whether given character is


alphabetic and converts to lowercase.
int tolower( 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 "\"lower character :%c\n",tolower ( ch));
else
printf("Entered character is not an alphabetic");
getch();
}

66

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

 Let inputArray is an integer array having N elements.


 Declare an integer variable 'sum' and initialize it to 0. We will use 'sum' variable to
store sum of elements of array.
 Using for loop, we will traverse inputArray from array from index 0 to N-1.
 For any index i (0<= i <= N-1), add the value of element at index i to sum.
sum = sum + inputArray[i];
 After termination of for loop, sum will contain the sum of all array elements.
#include <stdio.h>
#include <conio.h>
void main()
{
int inputArray[500], elementCount, counter, sum = 0;
printf("Enter Number of Elements in Array\n");
scanf("%d", &elementCount);
printf("Enter %d numbers \n", elementCount);
for(counter = 0; counter < elementCount; counter++)
{
scanf("%d", &inputArray[counter]);
}
for(counter = 0; counter < elementCount; counter++)
{
sum += inputArray[counter];
}
printf("Sum of All Array Elements : %d", sum);
getch();
}

67

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

M&S PUBLICATIONS
Write a program in c for addition of two matrices

Algorithm 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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

 Copy firstString's content into tempString using strcpy.


 Copy secondString's content into firstString using strcpy.
 Copy tempString's content into secondString.
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
char firstString[100], secondString[100], tempString[100];
printf("Enter first String \n");
69

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

fibonacci(N) = Nth term in fibonacci series


fibonacci(N) = fibonacci(N - 1) + fibonacci(N - 2);
whereas, fibonacci(0) = 0 and fibonacci(1) = 1

#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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

There are two type of function in C Language. They are;


 Library function or pre-define function.
 User defined function.
Library function
Library functions are those which are predefined in C compiler. The implementation part of pre-
defined functions is available in library files that are .lib/.obj files. .lib or .obj files are contained
pre-compiled code. printf(), scanf(), clrscr(), pow() etc. are pre-defined functions.

Limitations of Library function


 All predefined function are contained limited task only that is for what purpose function is
designed for same purpose it should be used.
 As a programmer we do not having any controls on predefined function implementation
part is there in machine readable format.
 In implementation whenever a predefined function is not supporting user requirement then
go for user defined function.
User Defined Functions
These functions are created by programmer according to their requirement The functions which
are created by user for program are known as 'User defined functions'.
Function Declarations

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

call by value call by reference


This method copy original value into function This method copy address of arguments into
as a arguments. function as an arguments.
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.

74

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Important points related to function

 The basic purpose of the function is code reuse.


 From any function we can invoke (call) any another functions.
 Always compilation will be take place from top to bottom.
 Always execution process will starts from main () and ends with main () only.
 In implementation when we are calling a function which is define later for avoiding the
compilation error we need to for forward declaration that is prototype is required.
 In function definition first line is called function declaration or function header.
 Always function declaration should be match with function declaratory.
 In implementation whenever a function does not returns any values back to the calling
place then specify the return type.
 Void means nothing that is no return value.
 In implementation whenever a function returns other than void then specify the return type
as return value type that is one type of return value it is returning same type of return
statement should be mentioned.
 Default return type of any function is an int.
 Default parameter type of any function is void.

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

 Function calling related information will be maintained by recursion.


 Stack evaluation will be take place by using recursion.
 In fix prefix, post-fix notation will be evaluated by using recursion.
Disadvantage of Recursion

 It is a very slow process due to stack overlapping.


 Recursive programs can create stack overflow.
 Recursive functions can create as loops.

Find the Factorial of any number using 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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

M&S PUBLICATIONS
int fact(int n)
{
if(a<0)
return(-1);
if(a==0)
return(1);
else
{
return(n*fact(n-1));
}
}

Find the Table of any number using recursion

#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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

Passing Single Element of an Array to Function

We can pass one element of an array to a function like passing any other basic data type variable.

Passing one dimensional array to function

We can pass a one dimensional array to a function by passing the


base address (address of first element of an array) of the array. We can
either pas the name of the array (which is equivalent to base address)
or pass the address of first element of array like &array [0]. Similarly,
we can pass multi-dimensional array also as formal parameters.
Different ways of declaring function which takes an array as input
 Function argument as a pointer to the data type of array.
int testFunction(int *array)
{
/* Function body */
}
 By specifying size of an array in function parameters.
int testFunction(int array[10])
{
/* Function body */
}
 By passing unsized array in function parameters.
int testFunction(int array[])
{
/* Function body */
}
Program
#include <stdio.h>
#include <conio.h>
void printArrayOne(int *array, int size)
{
int i;
for(i=0; i<size; i++)
{
printf("%d ", array[i]);
}
printf("\n");
}
void printArrayTwo(int array[5], int size)
{
int i;
for(i=0; i<size; i++)
{
printf("%d ", array[i]);
}
printf("\n");
}

81

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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();
}

SizeOf() Pointer Variable

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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 = &sum;
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();
}

C Programming Arrays of Pointers

Array of pointers in C can be declared like an array of integers or character. An array of


pointers is a collection of pointer variables stored in continuous memory location. In other works,
it is an array of addresses. Each element of a pointer array is bound to store address of same data
type. Here is the syntax of declaring an array of pointers.
data_type *identifier[size];
Program
#include <stdio.h>
#include <conio.h>
void main()
{
int *ptr_array[6];
int a1=1, a2=2, a3=3 ,a4=4, i;
int int_array[] = {10, 20};
ptr_array[0] = &a1;
ptr_array[1] = &a2;
ptr_array[2] = &a3;
ptr_array[3] = &a4;
ptr_array[4] = &int_array[0];
ptr_array[5] = &int_array[1];
for(i=0; i<6; i++)
{
printf("%d\n", *(ptr_array[i]));
}
getch();
}
C pointer to array of string
A pointer which pointing to an array which content is string, is known as pointer to array of strings.
Program
#include<stdio.h>
int main()
{
int i;
char *arr[4] = {"C","C++","Java","VBA"};
85

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

int count = 10;


int *ptr = &count; /* Pointer to an integer variable */
int **ptrToPtr = &ptr; /* Pointer to a pointer */
Program
#include <stdio.h>
#include <conio.h>
void main () {
int count = 10;
int *ptr = &count;
int **ptrToPtr = &ptr;
printf("Value of count variable = %d\n", count);
printf("Value of count variable retreived uisng ptr %d\n", *ptr);
printf("Value of count variable retreived uisng ptrToPtr = %d\n", **ptrToPtr);
getch();
}

C Dynamic Memory Allocation

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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.

Function Use of Function


malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
Allocates space for an array elements, initializes to zero and then returns a pointer
calloc()
to memory
free() dellocate the previously allocated space
realloc() Change the size of previously allocated space

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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;

Specifying Values for Enumerated Constants


By default, the enumerated constants are assigned consecutive values starting from 0. However,
we can specify the desired integer values for one or more enumerated constants. The subsequent
constants are assigned the next integer values.
enum month {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep,Oct, Nov, Dec};

Advantages of enumerated Data Type

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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 */
}

Program to display the contents of a file on screen

#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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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;
}

Program for appending the text in the file that is created

#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;
}

Program for Display the data from the file

#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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

M&S PUBLICATIONS
Some Examples of the Binary files
 Executable Files
 Database files

Standard Library function for File Handling in C


There are many file handling functions defined in stdio.h header file. Here is the list of frequently
used file handling functions:
Function Description
clearerr() Clears error indicators associated with a given stream.
fclose() Closes the stream and flushes buffers associated with the given stream.
feof() Checks the end-of-file indicator of the given stream.
ferror() Checks the error indicator of the given stream.
fflush() Flushes the content of the given stream.
fgetc() Gets the next character from the given stream.
fgetpos() Gets current position of the given stream.
fgets() Reads a line from given stream and stores it into a character array.
fopen() Opens a file in the given mode.
fprintf() Writes formatted output to a stream.
fputc() Writes a character to the given stream.
fputs() Writes a string to the given stream excluding the null terminating character.
fread() Reads data from the given stream and stores it into an array.
freopen() Reopens a stream with different file or mode.
fscanf() Read formatted data from given stream.
fseek() Changes the position indicator of the given stream.
fsetpos() Sets the position indicator of the given stream.
ftell() Returns the current position of the given stream.
fwrite() Writes data from an array to the given stream.

Programming Random Access File I/O in C

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)


lOMoARcPSD|4381973

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

Downloaded by Pradeep Katuriya (mspradeepparacoat@gmail.com)

You might also like