BPOPS103/203 Module 1 Notes
BPOPS103/203 Module 1 Notes
Introduction to C
Definition of Computer:
A computer, in simple terms, can be defined as an electronic device that is designed to accept data, perform
the required mathematical and logical operations at high speed, and output the result
OR
Computer is an electronic device which takes input from the user in the form of data and instructions and the
data is processed according to instruction given by the user and gives result as output.
A computer performs the following tasks:
a) Input: Sending the data and command to the computer is known as input.
b) Processing: Work done by the computer with the help of hardware and software to produce results is
known as processing.
c) Output: The result displayed by the computer is known as output.
d) Storage: A place to save result inside or outside the computer is known as storage.
Speed: Computers can perform millions of operations per second .The speed of computers is usually given in
nanoseconds and picoseconds, where 1 nanosecond = 1 × 10-9 seconds and 1 picosecond = 1 × 10 -12 seconds.
Accuracy: A computer is a very fast, reliable, and robust electronic device. It always gives accurate results,
provided the correct data and set of instructions are input to it.
Memory: Computer can stored large amount of data and programs in the secondary storage space like (CD,
Floppy, DVD, Hard Disk and pen drives). When data and programs have to be used, they are copied from the
secondary memory into the internal memory, often known as random access memory (RAM).
Stored Program Concept: Sir John von Neumann in late 1940s introduced the stroed program concept.
The following are the key characteristic features of this concept:
• Before any data is processed, instructions are read into memory.
• Instructions are stored in the computer‟s memory for execution.
• Instructions are stored in binary form (using binary numbers - 0s and 1s).
• Processing starts with the first instruction in the program, which is copied into a control unit circuit.
The control unit executes the instructions.
• Instructions written by the users are performed sequentially until there is a break in the current flow.
• Input/ Output and processing operations are performed simultaneously. While data is being read/
written, the central processing unit (CPU) executes another program in the memory that is ready for
execution.
Following are the types of Stored Program Computers based on Von Neumann architecture
1. Shared memory for instructions and data
• Shared Memory for instructions and data: In this type of machine instructions and data are selected
one at a time. Data and instructions are transferred to and from memory through a shared data bus.
Since there is a single bus to carry data and instructions, process execution becomes slower.
• Separate Memory for instructions and data: In this type of machine Instructions are selected serially
from the instruction memory and executed in the processor. When an instruction needs data, it is
selected from the data memory. Since there are separate memories, execution becomes faster.
Computer Generations:
Five Generations of Modern Computer:
The five generations of modern computers can be classified as follows:
Generation Period Based on Other features
First 1941-1956 Vacuum Tubes Magnetic drums for memory
Second 1956-1963 Transistors Magnetic cores, disks, punched cards and
printouts
Third 1964-1971 Integrated Circuits (ICs) Keyboard, monitor and operating system
Fourth 1972- 2010 Microprocessors Networking
Fifth 2010-Present ULSI Nano Technology Mainly unclear
Advantages:
• They were faster than second-generation computers and could perform one million
transactions per second.
• They were smaller, cheaper and more reliable than their predecessors.
• These computers had faster and larger primary memory and secondary storage.
• Third-generation computers were widely used for scientific as well as business applications.
• During this generation of computers, standardization of existing high-level languages and
invention of new high-level languages happened.
• Third-generation computers could run time sharing operating systems, which allowed
interactive use of a computer by one or more users simultaneously, thereby improving the
productivity of the users.
Disadvantages:
• These computers were difficult to maintain.
• They got heated very quickly.
Advantages:
• These computers were smaller, cheaper, faster and more reliable than their predecessors.
• They consumed less electricity and generated less heat.
• They had faster and larger primary memory and secondary storage.
• They could be used as general-purpose computers.
• GUIs enabled people to learn to work with computers very easily. Hence, the use of
computers both in offices and at homes became widespread.
• Networks allowed sharing of resources, thereby enabling efficient utilization of computer
hardware and software.
Disadvantage:
• They were not intelligent systems.
Workstations Network
Supercomputers:
➢ Among the four categories, the supercomputer is the fastest, most powerful and most expensive
computer.
➢ Supercomputers were first developed in the 1980s to process large amounts of data and to solve
complex scientific problems.
➢ Super computers use multiple CPUs for parallel processing technology and can perform more than
one trillion calculations in a second.
➢ A single supercomputer can support thousands of users at the same time. Such computers are mainly
used for weather forecasting, nuclear energy research, aircraft design, automotive design, online
banking, controlling industrial units etc. They are also used to solve complex scientific problems.
➢ Supercomputers have enormous storage, with huge amounts of power and generate a lot of heat.
➢ Because of their exorbitant cost, they are mainly used by government agencies.
➢ Some examples of supercomputers are CRAY-1, CRAY-2, Control Data CYBER 205, and ETAA-10.
Mainframe Computers:
➢ Mainframe computers are large-scale computes (but smaller than supercomputers)
➢ These are very expensive and need a very large clean room with air conditioning, thereby making
them very costly to deploy.
➢ As with supercomputers, mainframes can also support multiple processors. They are multi-user
machines that can support hundreds or thousands of users using the features of time sharing supported
by systems like Linux. For example, the IBM S/390 mainframe can support 50,000 users at the same
time.
➢ Users interact with this system using terminal and keyboard, which is akin to the way we use PCs.
➢ Mainframes can concurrently run multiple programs even with a single CPU.
➢ The processor speed in a mainframe is measured in MIP (Million Instructions per Second).
➢ Mainframes are generally used to handle data and applications related to the organization as whole.
Microcomputers:
➢ Microcomputers, commonly known as PCs, are very small and cheap.
➢ The first microcomputer was designed by IBM in 1981 and was name IBM-PC. Later on, many
computer hardware companies copied this design and termed their microcomputers as PC-compatible,
which refers to any PC that is based on the original IBM PC design.
➢ Another type of popular PC is designed by Apple. PCs designed by IBM and other PC-compatible
computers have a different architecture from that of Apple computers. Moreover, PCs and PC-
compatible computers commonly use the Windows operating system, while Apple computers use the
Macintosh operating system (MacOS). However, IBM and IBM-compatible PC are more popular
than their Apple counterparts.
➢ This computer is a single-user machine powered by a single microprocessor. Today‟s PCs are very
powerful machines having gigabytes or terabytes of memory or two of disk storage.
➢ They are used both in the standalone mode (at home) and in a network (office).
Desktop PCs:
A desktop PC is the most popular model of PCs. The system unit of the desktop PC can be placed flat
on a desk or table. It is widely used in homes and offices.
Laptops:
Laptops are small microcomputers that can easily fit inside a briefcase. They are very handy and can
easily be carried from one place to another. They may also be placed on the user‟s lap (thus the name).
Hence, laptops are very useful, especially when going on long journeys. Laptops operate on a special battery
and do not always have to be plugged in like desktop computers.
Tablet PCs:
• A tablet PC is a computing device that is smaller than a laptop, but bigger than a smartphone.
• Features such as user-friendly interface, portability, and touch screen have made them very popular
in the last few years.
• These days, a wide range of high-performance tablets are available in the market. While all of them
look similar from outside, they may differ in features such as operating system, speed of data
Workstations:
• Workstations are single-user computers that have the same features as PCs, but their processing
speed matches that of a minicomputer or mainframe computer.
• Workstation computers have advanced processors, more RAM and storage capacity than PCs.
Therefore, they are more expensive and powerful than a normal desktop computer.
• Although workstation computers are widely used as powerful single-user computers by scientists,
engineers, architects, and graphic designers, they can also be used as servers in a networked
environment.
Network Computers:
• Network computers have less processing power, memory, and storage than a desktop computer.
These are specially designed to be used as terminals in a networked environment. For example,
Applications of Computers:
Computers are used in various fields:
• Word processing: This software enables users to read and write the documents and insert the
images, tables and graphs for illustrating the concepts.
• Internet: The Internet is a network of networks that connects computers all over the world. It
gives the user access to an enormous amount of information, much more than available in any
library.
• Digital video or audio composition: Computers make audio or video composition and editing
very simple. This has drastically reduced the cost of equipment to compose music or make a film.
• Desktop Publishing: Desktop publishing software enables us to create page layouts for entire
books.
• E-Business: e-Business or electronic business is the process of conducting business via the
Internet. This may include buying and selling of goods and services using computers and the
Internet.
• Health Care: In Health care system computers are used to store the records, surgical procedures
and for Better diagnosis and treatment.
• Geographic's and Information System and Remote Sensing: A geographic information
system (GIS) is a computer- based tool for mapping and analyzing earth‟s features. It integrates
database operations and statistical analysis to be used with maps. GIS manages location- based
information and provides tools for display and analysis of statistics such as population count,
types of vegetation, and economic development opportunities. Remote sensing is the science of
taking measurements of the earth using sensors on airplanes or satellites. These sensors collect
data in the form of images, which are then analyzed to derive useful information.
• Multimedia and Animation : Using animation software, we can reproduce real- world
phenomena such as fire, smoke, fluids, movement of chemicals through the air and ground, and
the respiratory system to name a few.
The following figure shows the interaction between the different units of a computer system:
Input: This is the process of entering data and instructions (also known as programs) into the computer
system. The data and instructions can be entered by using different input devices such as keyboard, mouse,
scanner, and trackball. Note that computers understand binary language, which consists of only two symbols
(0 and 1), so it is the responsibility of the input devices to convert the input data into binary codes.
Storage: Storage is the process of saving data and instructions permanently in the computer so that they can
be used for processing. The computer storage space not only stores the data and programs that operate on that
data but also stores the intermediate results and the final results of processing.
A computer has two types of storage areas:
Motherboard:
The motherboard, also known as the mainboard or the parent board is the primary component of a computer.
It is used to connect all the components of the computer. The motherboard is a printed circuit that has
connectors for expansion cards, memory modules, the processor, etc.
I/O connectors: The motherboard has a number of input–output sockets on its rear panel, some of which
include:
• A serial port to connect some old peripherals
• A parallel port to connect old printers
• USB ports to connect more recent peripherals such as mouse and pen drive.
• RJ45 connector (also known as LAN or Ethernet port) to connect the computer to a network. It corresponds
to a network card integrated into the motherboard.
• Video graphics array (VGA) connector to connect a monitor. This connector interfaces with the built-in
graphics card.
• Audio plugs that include the line in, line out, and microphone to connect sound speakers, hi-fi system, or
microphone. This connector interfaces with the built-in sound card.
Input Devices
Keyboard: A keyboard looks like a typewriter. The keyboard that we use is also known as QWERT
keyboard. Various keys present on the keyboard are:
1. Typewriter keys: Includes letters, numbers and punctuation symbols
2. Function Keys: Includes keys labeled F1 to F12 located at the top end of the keyboard. The
functions they perform depend on the software that they use.
3. Cursor control keys: Appears as left , right, down, Up arrows keys which allows you to move the
cursor to the left, right , down and up in the screen.
Notes Prepared by Sayeesh, Dept. of CSE, YIT
4. Numeric keys: Appears just below the function keys along with special characters printed on the
topside. Also the right hand side of the keyboard contains the numeric key pad. When NUM-LOCK key
is ON, the key „7‟ prints 7. When it is OFF, key „7‟ acts like Home key.
5. Page Up and Page Down keys: Allows you to move to the preceding and next pages of the document,
respectively.
6. Home and End keys: Allows you to move cursor to the top and end of the document line or window
respectively.
7. Caps Lock key: Allows you to type text in upper case.
8. Shift key: Allows you to type text in uppercase. Holding the shift down and pressing a letter key
creates an upper case letter. However if caps lock is ON, then this effect is reversed.
9. Ctrl and Alt keys: Select a text, press ctrl + c does copy action. This is example for ctrl + alt
10. Enter Key: Allows you to start processing the data.
11. Tab key: It lets you indent paragraphs and helps you to move from one option to another in a menu.
12. Esc (Escape) Key: Allows you to cancel or ignore the entry or command that you have just entered in
an application.
13. Delete and Backspace keys: Delete key erases a space or character that is placed to the right side of
the blinking cursor. Backspace key erases the character to the left side of the blinking cursor.
The Scanner: The scanner is a device that can transfer types or handwritten texts, graphs, diagrams and
paragraphs to the computer. Scanner can be used to store photographs and important documents in the
original form.
Bar code reader: Many retail and grocery stores use some form of bar code reader to determine the item
being sold and to retrieve the item price from the computer. The bar code reader reads the Universal Product
Code. Federal Express, a courier delivery company uses a unique bar code to identify and track each
package.
Mark Sense Character Recognition system: In this a OMR (Optical mark reader) which contains bubble
canton form is filled with correct responses in #2 lead pencil. #2 pencil works best because of the number of
magnetic particles in the lead of the pencil. The OMR senses the magnetized marks, enabling the reader to
determine which responses are marked.
Optical Character recognition: This system can even scan types documents, pictures, graphics or even
handwriting into the computer.
Voice recognition devices: Voice recognition devices are capable of recognizing human voice and used to
execute command. The speech from the user with some keyword is well enough to execute the command.
With development in the field of computer, voice recognition system can be used for security purpose. Voice
recognition system can be digitized to work only when it listens to voice of authorized user or owner of the
system.
Microphone: A microphone is an input device used to record voices and transform the recorded voice into
digital data so that the user can play back or edit the digitized data as required. To convert the voice into
digital data, you need additional hardware known as sound card.
Visual Input Device: Video can be recorded and can be converted into digital data with the help of
computers. Example: digital camera. Digital camera has viewfinder, a lens to focus the image
light sensitive device and a method to store and remove images. Digital photography uses a combination of
advanced image sensor technology and memory storage which allows image to capture in digital format. The
captured images are instantly available to print with no need for a development process.
LCD Monitor: An LCD monitor is one of the most widely used flat panel monitors. It is more popular as a
display device compared to a CRT because of its economic power consumption, thinness, and high
resolution. Due to this, it is widely used in digital television, laptops, computers and digital cameras. LCD
monitors take up less desk space and are lighter than CRT monitors.
Nowadays, LCD monitors use the Thin Film Transistor (TFT) technology to display image on the monitor
screen.
TFT is a part of LCD. The main difference between LCD and TFT monitors is that TFT monitor uses a tiny
transistor for each pixel on the display. This allows electrical current illuminating the display to be turned on
and off quickly, which makes the display brighter and the movements smoother. These transistors are used in
the TFT panel.
Hardcopy Devices:
Printer: A device that prints images, numbers, alphabets and graphs on a sheet of paper is known as printer.
After creating a document on a computer you can send it to a printer for printing its hard copy which is
generally called printout. The speed of the printer is rated by either number of pages per minute or characters
per minute.
Different Types of printers
1. Daisy wheel printer
2. Dot matrix printer
3. Line printer
4. Inkjet printer
5. Laser printer
Understanding Impact and Non-Impact Printer: Impact printers are those printers in which a physical
contact is established between the print head, the cartridge and the media paper.
In non-impact printer, no physical connection is established between the print head and cartridge. Examples
are inkjet and laser printer.
Dot Matrix Printer: The dot matrix printer uses metal pins in its print head to create text and graphics in the
form of dots. An ink soaked ribbon is placed between the paper and the print head
The print head strikes against the ribbon with considerable force and the impact causes an impression of the
text on the paper. Dot matrix printers are ideal for printing multipart documents such as invoices and receipts.
The number of metal pins in the print head of the dot matrix determines the quality of the printout. The
Inkjet Printer: The inkjet printer is more efficient than matrix printer. It has several tiny nozzles that spray
ink onto the paper. Each nozzle is thinner than hair. The print head of the inkjet printer is known print
cartridge. The print cartridge contains nozzle and ink. That‟s why when no more ink is left; entire cartridge
needs to be replaced. An inkjet cartridge has 50 or more nozzles.
Laser printer: The laser printer uses a beam of laser for printing. Laser printer works on the principal of
electro-photography used in a photocopy machine. During the printing process, a laser printer converts the
entire text or image into a raster image which is then processed by raster image processor. This processor
scans the entire page, line by line and stores a bitmap of the page in the memory. The drum inside the laser
printer is then charged negatively and the bitmap is then written on the photosensitive drum by a laser beam.
The toner particles are charged positively. The toner particles will not stick on those regions of the drum
which are not discharged by the laser. The toner contains a plastic powder that is attract to the parts of the
drum where the laser beam hits. Finally, plastic powder is fused at 200 degree Celsius to bind the toner
particles with the paper producing the final printouts.
Plotters: A plotter similar to a printer produces hard copy output. Plotters, which produce high quality color
graphics, are usually categorized based on whether they use pens or electrostatic charges to create images.
Continuous curve plotters are used to draw maps from stored data. Plotters are ideal for engineering, drafting
and many other applications that require intricate graphics.
Programming Paradigms:
Monolithic Programming: If, we write an entire program in a single function that is in main function then,
you call it as a monolithic type of programming. But, it is not a good style of writing entire logic in a single
function.
Disadvantages:
The disadvantages of monolithic programming include −
• Program seems to be very large and complex.
• Debugging, testing and maintenance of a program are very difficult.
Requirements Analysis: In this phase, users‟ expectations are gathered to know why the program/software
has to be built. Then all the gathered requirements are analysed to pen down the scope or the objective of the
overall software product. The last activity in this phase includes documenting every identified requirement of
the users in order to avoid any doubts or uncertainty regarding the functionality of the programs. The
functionality, capability, performance, availability of hardware and software components are all analysed in
this phase.
Design: The requirements documented in the previous phase acts as an input to the design phase. In the
design phase, a plan of actions is made before the actual development process could start. This plan will be
Testing: In this phase, all the modules are tested together to ensure that the overall system works well as a
whole product. Although individual pieces of codes are already tested by the programmers in the
implementation phase, there is always a chance for bugs to creep in the program when the individual
modules are integrated to form the overall program structure. In this phase, the software is tested using a
large number of varied inputs also known as test data to ensure that the software is working as expected by
the users‟ requirements that were identified in the requirements analysis phase
Software Deployment, Training, and Support: After the code is tested and the software or the program has
been approved by the users, it is then installed or deployed in the production environment. Software Training
and Support is a crucial phase which is often ignored by most of the developers. Program designers and
developers spend a lot of time to create software but if nobody in an organization knows how to use it or fix
up certain problems, then no one would like to use it. Moreover, people are often resistant to change and
avoid venturing into an unfamiliar area, so as a part of the deployment phase, it has become very crucial to
have training classes for the users of the software.
Maintenance: Maintenance and enhancements are ongoing activities which are done to cope with newly
discovered problems or new requirements. Such activities may take a long time to complete as the
requirement may call for addition of new code that does not fit the original design or an extra piece of code
required to fix an unforeseen problem. As a general rule, if the cost of the maintenance phase exceeds 25% of
the prior-phases cost then it clearly indicates that the overall quality of at least one prior phase is poor. In
such cases, it is better to re-build the software (or some modules) before maintenance cost is out of control
Decision: Decision statements are used when the outcome of the process depends on some condition. For
example, if x=y, then print “EQUAL”. Hence, the general form of the if construct can be given as if
condition then process An algorithm to check the equality of two numbers is given below:
Step 1: START
Step 2: Input two numbers as A and B
Step 3: IF A=B Then
PRINT "EQUAL"
ELSE
PRINT "NOT EQUAL"
Step 4: END
Repetition: Repetition, which involves executing one or more steps for a number of times, can be
implemented using constructs such as while, do-while, and for loops. These loops execute one or more steps
until some condition is true. The following algorithm prints the first 10 natural numbers.
Step 1: START
Step 2: Initialization SET I = 0, N = 10
Step 3: Repeat Step while I<=N
PRINT I
I=I+1
Step 4: END
Flowcharts: A flowchart is a graphical or symbolic representation of a process. It is basically used to design
and document virtually complex processes to help the viewers to visualize the logic of the process, so that
they can gain a better understanding of the process and find flaws bottlenecks, and other less obvious features
within it. When designing a flowchart, each step in the process is depicted by a different symbol and is
associated with a short description. The symbols in the flowchart are linked together with arrows to show the
flow of logic in the process.
Types of Errors:
While writing programs, very often we get errors in our program. These errors if not removed will either give
erroneous output or will not let the compiler to compile the program. These errors are broadly classified
under four groups:
• Run-time errors
• Compile-time errors
• Linker errors
• Logical errors
Run-time Errors: As the name suggests, run-time errors occur when the program is being run executed.
Such errors occur when the program performs some illegal operations like
• Dividing a number by zero
• Opening a file that already exists
• Lack of free memory space
• Finding square or logarithm of negative numbers
Run-time errors may terminate program execution, so the code must be written in such a way that it handles
all sorts of unexpected errors rather terminating it unexpectedly. This ability to continue operation of a
program despite of run-time errors is called robustness.
Compile-time Errors: Again as the name implies, compile errors occur at the time of compilation of the
program. Such errors can be further classified as follows:
Syntax Errors: Syntax error is generated when rules of C programming language are violated. For example,
if we write int a: then a syntax error will occur since the correct statement should be int a;
Semantic Error: Semantic errors are those errors which may comply with rules of the programming
language but are not meaningful to the compiler. For example, if we write, a * b = c; it does not seem correct.
Rather, if written like c = a * b would have been more meaningful.
Logical Errors: Logical errors are errors in the program code that result in unexpected and undesirable
output which is obviously not correct. Such errors are not detected by the compiler, and programmers must
Notes Prepared by Sayeesh, Dept. of CSE, YIT
check their code line by line or use a debugger to locate and rectify the errors. Logical errors occur due to
incorrect statements. For example, if you meant to perform c = a + b; and by mistake you typed c = a * b;
then though this statement is syntactically correct, it is logically wrong.
Linker Errors: These errors occur when the linker is not able to find the function definition for a given
prototype. For example, if we write sqrt function but do not include math.h then a linker error will be shown.
Similarly, even if we have defined a function display_data() but while calling if we mistakenly write
displaydata() then again a linker error will be generated
Since it was developed along with the UNIX operating system, it is strongly associated with
UNIX. This operating system, which was also developed at Bell Laboratories of AT &T, was
coded almost entirely in C.
Documentation Section
Link Section
Definition Section
Declaration Part
Executable Part
}
Subprogram section
Function 1
• The Documentation Section consists of a set of comment lines giving the name of the
program, the name author and other details which the programmer would like to use later.
• The Link Section provides instructions to the compiler to link functions from the system
library.
NOTE: All the sections, except the main function section may be absent when they are not
required.
Example: Write a program to print area and circumference of a circle for the given radius
value.
void main( )
{
float r, A, C; Declaration Part
printf(“Enter the radius value”);
scanf(“%f”,&r);
A=3.142*r*r;
C=2*3.142*r; main function Section
printf(“Area of the circle is %f\n”,A);
printf(“Circumference of the circle is %f”,C); Executable Part
}
void main( )
{
float r, A, C; Declaration Part
printf(“Enter the radius value”);
scanf(“%f”,&r);
A=3.142*r*r;
C=2*3.142*r; main function Section
printf(“Area of the circle is %f\n”,A);
printf(“Circumference of the circle is %f”,C); Executable Part
}
void main( )
{
float r, A, C; Declaration Part
printf(“Enter the radius value”);
scanf(“%f”,&r);
A=PI*r*r;
C=2*PI*r; main function Section
printf(“Area of the circle is %f\n”,A);
printf(“Circumference of the circle is %f”,C); Executable Part
}
Tokens in C
Keywords:
Keywords are preserved words that have special meaning in C language. The meaning of C
language keywords has already been described to the C compiler. These meaning cannot be
changed. Thus, keywords cannot be used as variable names because that would try to change the
existing meaning of the keyword, which is not allowed. These serve as basic building blocks for
program statements. All keywords must be written in lowercase. There are total 32 keywords in
ANSI C.
ANSI C Keywords
do if static while
The following table gives illegal identifiers and explains why they are illegal.
Identifier Reasons for invalidity
For It is a keyword
Variables:
A variable is a data name that may be used to store a data value. Unlike the constants that remain
unchanged during the execution of a program, a variable may take different values at different times
during execution.
A variable is a name of the memory location. It is used to store data. Its value can be changed, and it
can be reused many times.
A variable name can be chosen by the programmer in a meaningful way so as to reflect its
function or nature in the program. Some examples are given below.
Average Height
Total Counter_1
Rules for writing Variables:
1. A variable can only have alphanumeric characters (a-z, A-Z, 0-9) and underscore ( _ )
2. The first character of a variable can only contain alphabet (a-z, A-Z) or underscore ( _ ).
3. Variables are also case sensitive in C. For example, name and Name are two
differentvariables in C.
4. Keywords are not allowed to be used as variables.
Numeric variables
Numeric variables can be used to store either integer values or floating point values. While an
integer value is a whole number without decimal point, a floating point value can have a decimal
point
Character variables
Character variables are single character enclosed with single quotes. It can either be ’A’ or ‘a’ or
special characters ‘&’. Here 2 is considered as integer and ‘2’ is considered as character not
integers.
Declaration of variables:
A variable declaration provides assurance to the compiler that there exists a variable with the given type
and name so that the compiler can proceed for further compilation without requiring the complete
detail about the variable. A variable definition has its meaning at the time of compilation only, the
compiler needs actual variable definition at the time of linking the program.
Identifiers which are used as variable names should be prefixed as integer or float by the following
declaration should appear at the beginning of a program before the variable names are used.
The data_type is always a reserved word. The data_type available for variable names storing numbers are
int for integers and float for floating point numbers.
Valid examples are given below:
int n, height ,count ,digit;
float rate, average , y_coordinate,p1;
When a variable name is declared then a memory location is identified and given this name.
The following declarations of variables are invalid:
float, a ,b ,c ; (comma after float is not valid) int :x;
(: is not valid)
real x, y;(real is not the correct type_name)
The fundamental or primary data types are integer (int), character (char), floating point (float), and
double-precision floating point (double). Many of them also has extended data types such as long,
double, short, unsigned and signed. The ranges of basic four types are given below:
char, int, float and double are all keywords and therefore their use is reserved.
They may not be used as names of variables. Char stands for “character” and int stands for “integer”.
The keywords short int, long int and unsigned int may be and usually are, shortened to just short, long,
and unsigned, respectively. Also, double and long float are equivalent, but double is the keyword
usually used.
Character Set
The characters that can be used to form words, numbers and expressions depend upon the
computer on which the program is run. The characters in C are grouped into the following categories.
1. Letters
2. Digits
3. Special characters
4. White Spaces
Letters Digits
Special characters
White Spaces
Blank Space
Horizontal tab
Carriage return New
line
Form feed
Constant:
Constants are data values that cannot be changed during the execution of a program. Constants are
also called as literals.
Constant
An octal integer constant consists of any combination of digits from the set 0 through 7 with a leading
0.
Some examples are: 037
0
0435
0567
A sequence of digits preceded by 0x is considered as hexadecimal integer. They may also include
alphabets A through F or a through f. The letters A through F represent the numbers 10 through
15. The examples for hexadecimal integers are:
0x2 0x9F
0xbcd 0x
Floating-point constants:
Integer numbers are inadequate to represent quantities that vary continuously, such as
distances, heights, temperatures, prices and so on. These quantities are represented by numbers
containing fractional parts like 23.78. Such numbers are called floating-point constants or real
constants. Examples for floating-point constants are given below.
213.00
0 .95
-0.71
+0.5
A real number may also be expressed in exponential (or specific notation). For example the value
213.45 may be written as 2.1345e2 in exponential notation. e2 means multiply by 102. The general form
is
mantissa e exponent
Character Constants:
A character constant contains a single character enclosed within a pair of single quote
marks. Examples of character constants are:
„5‟ „X‟ „;‟ „ „
Remember that a character constant „X‟ is not equivalent to the single character string constant (“X”).
A single character string constant does not have an equivalent integer value as a single character
constant. These type of constants are used in programs to build meaningful programs.
Defining Constants
There are two simple ways in C to define constants −
• Using #define preprocessor.
• Using const keyword.
The #define Preprocessor
Given below is the form to use #define preprocessor to define a constant −
Single Line Comment (Line Comment): The second format, the line comment, uses two slashes (//) to
identify a comment. This format does not require an end of comment token; the end of the line
automatically ends the comment. Programmers generally use this format for short comments. The line
comment token can start anywhere on the line.
Example: // This is a line comment.
Multiple Line Comment (Block Comment): A block comment is used when the comment will span
several lines. We call this comment format block comment. It uses opening and closing comment
tokens. Each comment token is made of two characters that, taken together, form the token; there can
be no space between them. The opening token is /* and the closing token is */. Everything between the
opening and closing comment tokens is ignored by the compiler. The tokens can start in any column,
and they do not have to be on the same line. The only requirement is that the opening token must
precede the closing token.
Example: /* This is a block comment that
covers two lines */
Input and Output Statements in C:
In C, data is input to and output from a stream. A stream is a source of or destination for data. It isassociated
with a physical device, such as a terminal, or with a file stored in auxiliary memory.
Reading data, processing it and writing the processed data known as information or a result of a program
are the essential functions of a program. The C is a functional language. It provides a number of macros and
functions to enable the programmer to effectively carry out these inputs andoutput operations. The data is
entered by the user through the standard input device (i.e. keyboard)and processed data is displayed on the
standard output device (i.e. monitor).
I/O functions are grouped into two categories:
• Unformatted I/O functions.
• Formatted I/O functions.
The formatted I/O functions allow programmers to specify the type of data and the way in which it
should be read in or written out. On the other hand, unformatted I/O functions do not specify the type of
data and the way is should be read or written. scanf ( ) and printf( ) are formattedI/O functions.
The following table lists the formatted and unformatted I/O functions:
Function Formatted Unformatted
Input scanf( ) getchar( ), gets( )
Output printf( ) putchar( ), puts( )
scanf(format-string, &var1,&var2,………&varn);
Where format-string gives information to the computer on the type of data to be stored in the list of
variables var1,var2……varn and in how many columns they will be found
For example:
scanf(“%d %f %e”, &a , &b, &c);
Specifies that an integer is to be stored in a, float is to be stored in b and a float written usingthe
exponent format in c. The appropriate sample data line is:
485 498.762 6.845e-12
Formatted Output Function:
printf function:
The general format of an output function is
printf(format-string, var1,var2…..varn);
Where format-string gives information on how many variables to expect, what type ofarguments they
are, how many columns are to be reserved for displaying them and any character string to be printed.
The printf() function may sometimes display only a message andnot any variable value. In the following
example:
printf(“Answers are given below”); The
format-string is:
Answers are given below
And there are no variables. This statement displays the format-string on the video display andthere are
no variables. After displaying, the cursor on the screen will remain at the end of thestring. If we want it
to move to the next line to display information on the next line, we shouldhave the format-string:
printf(“Answers are given below\n”);
In this string the symbol \n commands that the cursor should advance to the beginning of the next line.
In the following example:
printf(“Answer x= %d \n”, x);
%d specifies how the value of x is to be displayed. It indicates the x is to be displayed as a decimal
integer. The variable x is of type int. %d is called the conversion specification and d the conversion
character. In the example:
printf(“a= %d, b=%f\n”, a, b);
the variable a is of type int and b of type float or double. % d specifies that a is to be displayed as an
integer and %f specifies that, b is to be displayed as a decimal fraction. In this example
%d and %f are conversion specifications and d, f are conversion characters.
Notes prepared by Sayeesh, Dept. of CSE YIT
Formatted input and output using format specifiers:
The function scanf is the input analog of printf, providing many of the same conversionfacilities
in the opposite direction.
Conversion characters are shown in the table below:
CHARACTER DESCRIPTION
Review Questions
1. Define computer. Explain the stored program concepts and its types. (6 Marks)
2. List out and explain the characteristics of computer (8 Marks)
3. Explain the different generations of computer. (10 Marks)
4. Discuss the different types of computers (10 Marks)
5. Explain the different types of microcomputers. (8 Marks)
6. List out and explain the different types of input and output devices. (10 Marks)
7. Distinguish between dumb terminals and intelligent terminals in mainframe computer. (4 Marks)
8. Explain the basic organization of computer with neat a block diagram. (10 Marks)
9. Discuss the various components inside a computer. (6 Marks)
10. What is motherboard? Explain the characteristics of motherboard. (8 Marks)
11. Differentiate primary memory and secondary memory. (4 Marks)
12. List out and explain the applications of computer (8 Marks)
13. List out and explain the different types of programming paradigm, (8 Marks)
14. Discuss the different phases of software development with the help of diagram. (10 Marks)
15. What is algorithm? Explain the control structures used in algorithm with examples. (8 Marks)
16. What is a pseudocode? Explain with example. (5 Marks)
17. Write an algorithm and draw a flowchart to compute area and circumference of the circle for the given
radius value. (6 Marks)
18. Write an algorithm and draw a flowchart to find area of the triangle for the given three sides. (6 Marks)
19. What is flowchart? List out and explain the purpose of different symbols used in flowchart. (6 Marks)
20. Write an algorithm and draw a flowchart to compute simple interest for the given principal amount, rate of
interest and number of years. (6 Marks)
21. What is compiler? Explain the function of compiler. (4 Marks)
22. List out and explain the different types of errors with examples. (8 Marks)
23. What is testing? Explain the different types of testing. (6 Marks)
24. What is debugging? Explain the different approaches applied for debugging a code. (6 Marks)
25. List out and explain the different types of files used in C program. (8 Marks)
26. Explain the basic structure of C program with an example. (8 Marks)
27. Give the character set of C. (4 Marks)
a. Sum100
b. sum+3
c. int
d. ab_cd
e. X Y
f. 2product
g. m-n
31. What are constants? How they differ from variables? (4 Marks)
32. List the various types of constants with examples. (4 Marks)
33. Explain the various data types supported by C. (5 Marks)
34. What is variable? How to declare variable in C program? Explain with examples. (6 marks)
35. Explain input and output statements used in C program with examples. (6 Marks)
36. Write a C program to find area of the triangle for the given base and height. (5 Marks)
37. Write a C program to find area of the triangle for the given three sides. (5 Marks)
38. Write a C program to compute simple interest. (5 Marks)
39. Write a C program to find area and circumference of the circle for the given radius value (5 Marks)
40. Write a C program to swap two given numbers without using third variable (5 Marks)