Module 1 - C Programming
Module 1 - C Programming
A computer, in simple terms, can be defined as an electronic device which accepts data, performs the required
mathematical and logical operations at high speed, and outputs the result.
BRIEF HISTORY OF C
The C programming language is a structure oriented programming language, developed at Bell Laboratories
in 1972 by Dennis Ritchie.
• C programming language features were derived from an earlier language called “B” (Basic Combined
Programming Language – BCPL)
• C language was invented for implementing UNIX operating system
• In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming
Language” and is commonly known as K&R C.
• In 1983, the American National Standards Institute (ANSI) established a committee to provide a
modern, comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI C”,
was completed late 1988.
• Many of C’s ideas & principles were derived from the earlier language B, thereby naming this new
language “C”.
INTRODUCTION TO COMPUTERS
Any programming language is implemented on a computer. Right form its inception, to the present
day, all computer system (irrespective of their shape & size) perform the following 5 basic
operations. It converts the raw input data into information, which is useful to the users.
➢ Inputting: It is the process of entering data & instructions to the computer system.
➢ Storing: The data & instructions are stored for either initial or additional processing,
as & when required.
➢ Processing: It requires performing arithmetic or logical operation on the saved data
to convert it into useful information.
➢ Outputting: It is the process of producing the output data to the end user.
➢ Controlling: The above operations have to be directed in a particular sequence to be
completed.
➢ Storage Unit: The data & instruction that are entered have to be stored in the computer.
Similarly, the end results & the intermediate results also have to be stored somewhere
before being passed to the output unit. The storage unit provides solution to all these
issues. This storage unit is designed to save the initial data, the intermediate result &
the final result. This storage unit has 2 units: Primary storage & Secondary storage.
Primary Storage: The primary storage, also called as the main memory, holds the data
when the computer is currently on. As soon as the system is switched off or restarted,
the information held in primary storage disappears (i.e. it is volatile in nature).
Moreover, the primary storage normally has a limited storage capacity, because it is
very expensive as it is made up of semiconductor devices.
Secondary Storage: The secondary storage, also called as the auxiliary storage,
handles the storage limitation & the volatile nature of the primary memory. It can
retain information even when the system is off. It is basically used for holding the
program instructions & data on which the computer is not working on currently, but
needs to process them later.
➢ Central Processing Unit: Together the Control Unit & the Arithmetic Logic Unit are
called as the Central Processing Unit (CPU). The CPU is the brain of the
computer. Like in humans, the major decisions are taken by the brain itself & other
body parts function as directed by the brain. Similarly in a computer system, all the
major calculations & comparisons are made inside the CPU. The CPU is responsible
for activating & controlling the operation of other units of the computer system.
Arithmetic Logic Unit: The actual execution of the instructions (arithmetic or logical
operations) takes place over here. The data & instructions stored in the primary
storage are transferred as & when required. No processing is done in the primary
storage. Intermediate results that are generated in ALU are temporarily transferred
back to the primary storage, until needed later. Hence, data may move from the
primary storage to ALU & back again to storage, many times, before the processing
is done.
Control Unit: This unit controls the operations of all parts of the computer but does
not carry out any actual data processing.It is responsible for the transfer of data and
instructions among other units of the computer.It manages and coordinates all the
units of the system.It also communicates with Input/Output devices for transfer of
data or results from the storage units.
➢ Output Unit: The job of an output unit is just the opposite of an input unit.
It accepts the results produced by the computer in coded form. It converts
these coded results to human readable form. Finally, it displays the
converted results to the outside world with the help of output devices ( Eg
:monitors, printers, projectors etc..).
Application Software- Application software is a set of programs designed to solve a particular problem for
users. It allows the end user to do something besides simply running the hardware. E.g.: Web Browser,
Gaming Software
CHARACTERISTICS OF COMPUTERS
• Speed: Computers can perform millions of operations per second. The speed of computers
is usually given in nanoseconds (ns) and picoseconds (ps), where 1 ns = 1×10-9 sec and 1
ps = 1×10-12 sec.
• Versatile: Computers can perform multiple tasks of different nature at the same time.
• Memory: Computers have internal or primary memory (storage space) as well as external
or secondary memory to store data and programs.
• Accuracy: A computer always gives accurate results, provided the correct data and
instructions are input to it. If the input data is wrong, then the output will also be erroneous.
This is called garbage-in, garbage-out (GIGO).
• Automation: Computers perform a task without any user intervention.
• Diligence: Unlike humans, computers never get tired of a repetitive task.
• No IQ: Computers do not have any decision-making abilities of their own. They need
guidance to perform various tasks.
• Economical: Computers are considered as short-term investments for achieving long-term
gains. They save time, money, and energy.
GENERATIONS OF COMPUTERS
The word ‘Generation’, when applied to computing, refers to the different advancements in
computer technology. The focus of every new generation has been on miniaturization, speed,
power, and efficient computer memory.
Advantage
Fastest calculating devices of their time
Disadvantages
Generated a lot of heat
Consumed a lot of electricity
Bulky in size
Prone to frequent hardware
Required constant maintenance because of the low mean time between failures
Limited commercial use
Very expensive
Disadvantage
Transistors had to be assembled manually, which made commercial production of computers
difficult and expensive
Advantages
Faster and could perform one million transactions per second
Smaller, cheaper, and more reliable
Faster and larger primary memory and secondary storage
Widely used for scientific as well as business applications
Supported time sharing operating systems
Disadvantages
Difficult to maintain
Got heated very quickly
Advantages
Smaller, cheaper, faster, and more reliable
Consumed less electricity and generated less heat
Faster and larger primary memory and secondary storage
Could be used as general-purpose computers
GUIs enabled people to learn to work with computers very easily
Lead to widespread use of computers in offices and at homes
Networks allowed sharing of resources
Disadvantage
Not intelligent systems
• Gaming: Computers are programmed to play games such as chess and checkers. More recent
examples of such gaming systems include PlayStation by Sony.
• Expert systems: Computers are programmed to take decisions in real-world situations.
• Natural languages: Computers are programmed to understand and respond to natural human
languages.
• Neural networks: Systems are programmed to simulate intelligence by reproducing the physical
connections that take place in animal brains.
• Robotics: Computers are programmed to look, listen, and react to other sensory stimuli.
CLASSIFICATION OF COMPUTERS
Supercomputers
• Fastest, most powerful, and most expensive computer
• Used to process large amounts of data and to solve complex scientific problems
• Can support thousands of users at the same time
• Mainly used for weather forecasting, nuclear energy research, aircraft design, automotive
design, online banking, etc.
• Some examples of supercomputers are CRAY-1, CRAY-2, Control Data CYBER 205, and
ETA A-10
Mainframe Computers
• Large-scale computers, but smaller than Supercomputers
• Very expensive
• Need a very large clean room with air conditioning
• Used as servers on the World Wide Web
• Some examples are IBM S/390, Control Data CYBER 176, and Amdahl 580
Minicomputers
• Smaller, cheaper, and slower than Mainframes
• Can be used as servers in a networked environment
• Widely used in business, education, hospitals, government
• Some examples are AS/400 computers (IBM Corporation), Data General Corporation, and
Prime Computer
Microcomputers
Desktop PCs
• Most popular model
• Widely used in homes and offices
Laptops
• Very handy and easily portable
• Storage capacity is almost equivalent to that of a desktop computer
• For input, laptops have a built-in keyboard and a touchpad
• More expensive than desktop computers Microcomputers
Workstations
• Single-user computers
• Same features as PCs but with higher processing speed
• Have advanced processors, more RAM and storage capacity
• Can be used as servers in a networked environment
Network Computers
• Designed to be used as terminals in a networked environment
• Have less processing power, memory, and storage
• Those used to access Internet or Intranet are often known as Internet PCs or Internet boxes
• Some used in homes do not even have a monitor. They may be connected to a TV. They
are called WebTV
Handheld Computers
• Single-user computers
• Can fit in one hand
• Have small-sized screens and keyboards
• Some examples of handheld computers are
Personal Digital Assistants (PDA)
Cellular Phones
H/PC Pro Devices
COMPUTER LANGUAGES
Languages are a means of communication. Normally people interact with each other through a
language. On the same pattern, communication with computers is carried out through a language.
This language is understood both by the user and the machine. Just as every language like English,
Hindi has its own grammatical rules; every computer language is also bounded by rules known as
syntax of that language. The user is bound by that syntax while communicating with the computer
system.
o BASIC (Beginners All Purpose Symbolic Instruction Code): It is widely used, easy to learn
general purpose language. Mainly used in microcomputers in earlier days.
o C: Structured Programming Language used for all purpose such as scientific application,
commercial application, developing games etc.
o C++: Popular object oriented programming language, used for general purpose.
Storage: The process of saving data and instructions permanently in the computer so that they can
be used for processing. A computer has two types of storage areas:
Primary storage (main memory) is the storage area that is directly accessible by the CPU
at very high speeds
Secondary storage (secondary or auxiliary memory) supplements the limited storage
capacity of the primary memory
• Processing: The process of performing operations on the data as per the instructions specified
by the user (program)
• Output: The process of giving the result of data processing to the outside world (external to the
computer system)
• Control Unit: It is the central nervous system of the computer system that manages and controls
all the other components
Input Devices: An input device is used to feed data and instructions to the computer.
KEYBOARD
• Main input device for computers
• Most keyboards have between 80 and 110 keys, which include the following:
Typing keys
Numeric keys
Function keys
Control keys
Advantage
Easy to use and low-priced
Disadvantages
Cannot be used to draw figures
Moving the cursor to another position is very slow
MOUSE
• A pointing device that helps users to select items on screen by controlling the movement of
pointer
• Can be used to perform the following operations:
Point Click
Drag Scroll
Advantages
Low-priced
Easy to use and can be used to quickly place the cursor
Disadvantages
Needs extra desk space to be placed and moved easily
The ball must be cleaned to remove dust from it
TRACKBALL
• A pointing device to control the position of the cursor on the screen
• Usually used in notebook computers, where it is placed on the keyboard
Advantages
Provides better resolution
Occupies less space
Easier to use as compared to a mouse as its use involves less hand-and-arm movements
Disadvantage
The trackball chamber is often covered with dust, so it must be cleaned regularly
TOUCHPAD
• A small, flat, rectangular stationary pointing device with a sensitive surface of 1.5’’–2’’
• Users have to slide their fingertips across the surface of the pad to point to a specific object on
the screen
• The surface translates the motion and position of the user’s fingers to a relative position on the
screen
Advantages
Occupies less space
Easy to use
Built in the keyboard so no need to carry an extra device
HANDHELD DEVICES
• Joystick: A cursor control device widely used in computer games and CAD/CAM
applications
• Stylus: A pen-shaped device to enter information or write on the touch screen of a handheld
device
• Touch screen: A display screen that can identify the occurrence and position of a touch
inside the display region. The user can touch the screen by using either a finger or a stylus
Barcode Reader
• Works by directing a beam of light across the barcode and measuring the amount of light reflected
back
Advantages
Low-priced, portable, and easy to use
Disadvantages
Must be handled with care
Can interpret information using a limited series of thin and wide bars. To interpret other
unique identifiers, the bar display area must be widened
Image Scanner
Captures images, printed text, photographs, etc., and converts them into digital images for editing
and display on computers
Advantages
Any document can be scanned and stored in a computer for further processing
Scanned and stored document will never deteriorate in quality with time
Disadvantages
Scanned documents are bigger in size as compared to other equivalent text files
Scanned documents are uneditable
OUTPUT DEVICES
Electromechanical devices that accept digital data from the computer and convert them into human
understandable form
Monitors
•Used to display video and graphics information generated by the computer through the video card
• Similar to television screens but they display information at a much higher quality
• Come in three variants:
Cathode ray tube (CRT) monitor
Liquid crystal display (LCD) monitor
Plasma monitor
CRT Monitor
Specialized vacuum tubes in which images are produced when an electron beam strikes a
phosphorescent surface
Advantages
Provide good quality images
Low-priced
Disadvantages
Occupy a large space on the desk
Bigger in size and weight and therefore not easily portable
Power consumption is higher than in other monitors
LCD Monitor
• Thin, flat, electronic visual displays that use the light modulating properties of liquid crystals
• Replacing CRT displays at a fast pace
Advantages
Very compact and lightweight
Consume less power
Little or no flicker of images
Cause less eye fatigue
Disadvantages
More expensive than CRTs
Images are not very clear when tried to view from an angle
Plasma Monitor
Thin and flat monitors widely used in televisions
Advantages
• The technology used in plasma monitors allows producing a very wide screen
• Very bright images can be formed
• Not heavy and are thus easily portable
Disadvantages
• Very expensive
• High power consumption
• Since the images are phosphor-based, at times, they may suffer from flicker visions
Projectors
• A device that takes an image from a digital source and projects it onto a screen or another surface
• Can be broadly classified into two categories:
LCD projectors use their own light to display the image on the screen/wall. The room
must be first darkened, else the image formed will be blurred.
Digital light processing (DLP) projectors use a number of mirrors to reflect light. When
using a DLP projector, the room may or may not be darkened because it displays a clear
image in both situations.
Printers
A device that takes text and graphics information obtained from a computer and prints it on a paper
Impact printers
• Print characters by striking an inked ribbon against the paper
Advantages
Enable users to produce carbon copies
Low-priced
Disadvantages
Slow
Poor print quality, especially in the case of graphics
Can be extremely noisy
Can print only using the standard font
Band Printers
• Printing mechanism uses a metal loop or band to produce typed characters
• The set of characters is permanently embossed on the band, and this set cannot be changed unless
the band is replaced
Line Printers
• High-speed printers in which one typed line is printed at a time
• Used in data centers and industrial environments
Non-Impact Printers
• Much quieter as their printing heads do not strike the paper
• Offer better print quality, faster printing, and the ability to create prints that contain sophisticated
graphics
• Use either solid or liquid cartridge-based ink, which is either sprayed, dripped, or electrostatically
drawn onto the page
Advantages
Produce prints of good quality
Noiseless, fast
Can print text in different fonts
Disadvantage
Expensive as ink cartridges used by them are costly
Inkjet Printers
• The print head has several tiny nozzles, also called jets. As the paper moves past the print head,
the nozzles spray ink onto it, forming characters and images
• Cartridges have to be changed frequently
Laser Printers
• Work at very high speeds and produce high-quality text and graphics
• A laser beam ‘draws’ the document on a drum which is coated with a photo-conductive material
• After the drum is charged , it is rolled in a toner (a dry powder type of ink)
• The toner sticks to the charged image on the drum and transferred onto a piece of paper
Plotters
• Used to print vector graphics with high-print quality
• Widely used to draw maps, in scientific applications, and in CAD, CAM, and CAE
Drum plotters
• Used to draw graphics on paper that is wrapped around a drum
• Usually used with mainframe and minicomputer systems
Flatbed plotters
• The paper is spread on the flat rectangular surface of the plotter, and the pen is moved over it
• Less expensive, and are used in many small computing systems Plotters
STRUCTURE OF A C PROGRAM
The structure of a C program is a protocol (rules) to the programmer, which he has to follow while
writing a C program. The general basic structure of C program is shown in the figure below.
Based on this structure, we can sketch a C program.
Example:
/* This program accepts a number & displays it to the user*/
#include <stdio.h>
void main(void)
{ int number;
printf( "Please enter a number: " ); scanf( "%d", &number );
printf( "You entered %d", number );
return 0;}
Stepwise explanation:
#include
The part of the compiler which actually gets your program from the source file is called
the preprocessor.
#include <stdio.h>
#include is a pre-processor directive. It is not really part of our program, but instead it is an
instruction to the compiler to make it do something. It tells the C compiler to include the
contents of a file (in this case the system file called stdio.h).
The compiler knows it is a system file, and therefore must be looked for in a special place,
by the fact that the filename is enclosed in <> characters
<stdio.h>
stdio.h is the name of the standard library definition file for all STanDard Input and Output
functions.
Your program will almost certainly want to send information to the screen and read things
from the keyboard, and stdio.h is the name of the file in which the functions that we want to
use are defined.
The function we want to use is called printf. The actual code of printf will be tied in later
by the linker.
The ".h" portion of the filename is the language extension, which denotes an include file.
void
This literally means that this means nothing. In this case, it is referring to the function
whose name follows.
Void tells to C compiler that a given entity has no meaning, and produces no error.
main
In this particular example, the only function in the program is called main.
A C program is typically made up of large number of functions. Each of these is given a
name by the programmer and they refer to each other as the program runs.
C regards the name main as a special case and will run this function first i.e. the program
execution starts from main.
(void)
This is a pair of brackets enclosing the keyword void.
It tells the compiler that the function main has no parameters.
A parameter to a function gives the function something to work on.
{ (Brace)
This is a brace (or curly bracket). As the name implies, braces come in packs of two - for
every open brace there must be a matching close one.
Braces allow us to group pieces of program together, often called a block.
A block can contain the declaration of variable used within it, followed by a sequence of
program statements.
In this case the braces enclose the working parts of the function main.
; (semicolon)
The semicolon marks the end of the list of variable names, and also the end of that
declaration statement.
All statements in C programs are separated by ";" (semicolon) characters.
The ";" character is actually very important. It tells the compiler where a given statement
ends.
If the compiler does not find one of these characters where it expects to see one, then it
will produce an error.
scanf
In other programming languages, the printing and reading functions are a part of the
language.
In C this is not the case; instead they are defined as standard functions which are part of
the language specification, but are not a part of the language itself.
The standard input/output library contains a number of functions for formatted data
transfer; the two we are going to use are scanf (scan formatted) and printf (print formatted).
printf
The printf function is the opposite of scanf.
It takes text and values from within the program and sends it out onto the screen.
Just like scanf, it is common to all versions of C and just like scanf, it is described in the
system file stdio.h.
The first parameter to a printf is the format string, which contains text, value descriptions
and formatting instructions.
ELEMENTS OF C
Every language has some basic elements & grammatical rules. Before starting with rogramming,
we should be acquainted with the basic elements that build the language.
Character Set
Communicating with a computer involves speaking the language the computer understands. In C,
various characters have been given to communicate.
Keywords
Keywords are the words whose meaning has already been explained to the C compiler. The
keywords cannot be used as variable names because if we do so we are trying to assign a new
meaning to the keyword, which is not allowed by the computer. There are only 32 keywords
available in C. Below figure gives a list of these keywords for your ready reference.
Identifier
In the programming language C, an identifier is a combination of alphanumeric characters, the
first being a letter of the alphabet or an underline, and the remaining being any letter of the
alphabet, any numeric digit, or the underline.
Data Type
In the C programming language, data types refer to a domain of allowed values & the operations
that can be performed on those values. The type of a variable determines how much space it
occupies in storage and how the bit pattern stored is interpreted. There are 4 fundamental data
types in C, which are- char, int, float &, double. Char is used to store any single character; int is
used to store any integer value, float is used to store any single precision floating point number &
double is used to store any double precision floating point number. We can use 2 qualifiers with
these basic types to get more types.
VARIABLES
Variables are names that are used to store values. It can take different values but one at a time. A
data type is associated with each variable & it decides what values the variable can take. When
you decide your program needs another variable, you simply declare (or define) a new variable
and C makes sure you get it. You declare all C variables at the top of whatever blocks of code
need them. Variable declaration requires that you inform C of the variable's name and data type.
Syntax – datatype variablename;
Eg:
int page_no; char grade; float salary; long y;
Declaring Variables:
There are two places where you can declare a variable:
• After the opening brace of a block of code (usually at the top of a function)
• Before a function name (such as before main() in the program) Consider various
examples:
Suppose you had to keep track of a person's first, middle, and last initials. Because an initial is
obviously a character, it would be prudent to declare three character variables to hold the three
initials. In C, you could do that with the following statement:
1. main()
2. main()
Initialization of Variables
When a variable is declared, it contains undefined value commonly known as garbage value. If
we want we can assign some initial value to the variables during the declaration itself. This is
called initialization of the variable.
char grade=’A’;
float salary= 20000.50;
INPUT-OUTPUT IN C
When we are saying Input that means we feed some data into program. This can be given in the
form of file or from command line. C programming language provides a set of built-in functions
to read given input and feed it to the program as per requirement.
When we are saying Output that means to display some data on screen, printer or in any file. C
programming language provides a set of built-in functions to output the data on the computer
screen.
Functions printf() and scanf() are the most commonly used to display out and take input
respectively. Let us consider an example:
Output:
C Programming
Explanation:
printf("Number=%d",c); return 0;
}
Output
Number=5
Inside quotation of printf() there, is a conversion format string "%d" (for integer). If this
conversion format string matches with remaining argument, i.e, c in this case, value of c is
displayed.
The scanf() function is used to take input from user. In this program, the user is asked an input
and value is stored in variable c. Note the '&' sign before c. &c denotes the address of c and
value is stored in that address.
Output
Conversion format string "%f" is used for floats to take input and to display floating value of a
variable.
Output
Enter character: g You entered g.
ASCII code
When character is typed in the above program, the character itself is not recorded a numeric
value (ASCII value) is stored. And when we displayed that value by using "%c", that character is
displayed.
return 0;
}
Output:
Enter character:
g 103
When, 'g' is entered, ASCII value 103 is stored instead of g.
You can display character if you know ASCII code only. This is shown by following example.
Output
Character of ASCII value 69: E
The ASCII value of 'A' is 65, 'B' is 66 and so on to 'Z' is 90. Similarly ASCII value of 'a' is 97, 'b'
is 98 and so on to 'z' is 122.