0% found this document useful (0 votes)
19 views

Module 1 Notes

Uploaded by

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

Module 1 Notes

Uploaded by

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

MODULE-1: INTRODUCTION TO COMPUTER

COMPUTER
• A computer is an electronic device that accepts the data, process the data and gives
the required output.
• It can store and process information.
CHARACTERISTICS OF THE COMPUTER

The characteristics of the computer system are as follows −

Speed
• A computer works with much higher speed and accuracy compared to humans while
performing mathematical calculations.
• Computers can process millions (1,000,000) of instructions per second. The time
taken by computers for their operations is microseconds and nanoseconds.
Accuracy
• Computers perform calculations with 100% accuracy.
• Errors may occur due to data inconsistency or inaccuracy.

Diligence
• A computer can perform millions of tasks or calculations with the same consistency
and accuracy.
• A computer is free from tiredness, lack of concentration, fatigue, etc.

Versatility
• Versatility refers to the capability of a computer to perform different kinds of works
with same accuracy and efficiency.

1
Reliability
• A computer is reliable as it gives consistent result for similar set of data i.e., if we
give same set of input any number of times, we will get the same result.
Automation
• Computer performs all the tasks automatically i.e. it performs tasks without manual
intervention.

Memory
• A computer has built-in memory called primary memory where it stores data.
• Secondary storage are removable devices such as CDs, pen drives, etc., which are also
used to store data.

• First Generation (1940-56) - vacuum tubes


• Second Generation (1956-63) - Transistors
• Third Generation (1964-71) - integrated circuit
• Fourth Generation (1971-89) - microprocessor
• Fifth Generation (1990 till date) - artificial intelligence

First Generation Computers (1940-1956)


• Vacuum tubes (a sealed glass tube containing a near-vacuum which allows the free
passage of electric current.) for circuitry and magnetic drums for memory.
• First generation computers relied on machine language.
• The UNIVAC (Universal Automatic Computer) and ENIAC (Electronic Numerical
Integrator and Computer) computers are examples of first-generation computing
devices.
• Input was based on punched cards and paper tape. Output came out on print-outs.

2
Second Generation Computers (1956-1963)
• Transistors replaced vacuum tubes
• Moved from binary machine language to symbolic.
• High-level programming languages were also being developed at this time, such as
early versions of COBOL and FORTRAN.
• These were also the first computers that stored their instructions in their memory.

Third Generation Computers (1964-1971)


• Development of the integrated circuit
• Transistors were miniaturized and placed on siliconchips, called semiconductors.
• Instead of punched cards and printouts, users interacted with third generation
computers through keyboards and monitors and interfaced with an operating system.
• Allowed the device to run different applications at one time.

3
• The programming languages like COBOL and FORTRAN were standardised by
ANSI(American National Standard Institute) and was called as ANSI COBOL and
ANSI FORTRAN
• Cray-1: 160 million instructions per seconds and 8 Mbytes of memory

Fourth Generation Computers(1971-present)


• The microprocessor - thousands of integrated circuits were built onto a single silicon
chip.
• The Intel 4004 chip, developed in 1971, located all the components of the computer
from the central processing unit and memory to input/output controls—on a single chip.
• Fourth generation computers also saw the development of GUIs, the mouse and
handheld devices.
• The year 1981 saw the first ever computer (IBM) specifically designed for home use
and 1984 saw the MacIntosh introduced by Apple
• 1981 - IBM PC
• 1984 - Macintosh introduced by Apple
• Semiconductor memories were used
• Hard disk become smaller and cheaper
• Networks that led to the development of the Internet.
• It also supported several applications like wordprocessing packages, spreadsheet
packages and graphics packages

4
Fifth Generation Computers (present and beyond)
• Artificial intelligence
• Are still in development, though there are some applications, such as voice
recognition.
• The use of parallel processing and superconductors is helping to make artificial
intelligence a reality.
• The goal of fifth-generation computing is to develop devices that respond to natural
language input and are capable of learning and self-organization.
• The hottest area of AI is neural networks. Neural networks are used in fields such as
voice recognition system.
• The language are Prolog and LISP

5
CLASSIFICATION OF COMPUTERS BASED ON ORGANIZATIONAL USAGE
Computers can be broadly classified into four categories based on their speed, amount of data
that they can hold, and price. These categories are as follows:
• Supercomputers
• Mainframe computers
• Minicomputers
• Microcomputers

6
7
Supercomputers use parallel processing technology and can perform more than one trillion
calculations in a second.

Users can access mainframes by either using terminals or via PCs. There are basically two
types of terminals.
Dumb Terminals Dumb terminals consist of only a monitor and a keyboard (or mouse). They
do not have their own CPU and memory and use the mainframe system’s CPU and storage
devices.
Intelligent Terminals In contrast to dumb terminals, intelligent terminals have their own
processor and thus can perform some processing operations. However, just like the dumb
terminals, they do not have their own storage space. Usually, PCs can be used as intelligent
terminals to facilitate data access and other services from the mainframe system

They are called minicomputers because they were the smallest computer of their times. Also
known as midrange computers, the capabilities of minicomputers fall between mainframe and
PCs

8
Microcomputers Microcomputers, commonly known as PCs, are very small and cheap. The
fi rst microcomputer was designed by IBM in 1981 and was named IBM-PC. Another type of
popular PC is designed by Apple. PCs commonly use the Windows operating system, while
Apple computers use the Macintosh operating system (MacOS). PCs can be classified into the
following categories:

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

9
Commonly known as handheld computers, Palmtop computers, or Mini-Notebook computers.
• Personal digital assistants (PDA)
– lightweight mobile devices
– offer a collection of application software for word processing, spreadsheets,
games, etc.
– take notes, organize telephone numbers, and store addresses.
– Many PDAs are web-enabled
– The primary input device of a PDA is the stylus
– Some PDAs also support voice input.
• Cellular phones These days, cellular phones are web-enabled telephones that have
features of both analog and digital devices. Such phones are also known as smart phones
because, in addition to basic phone capabilities, they also facilitate the users to access
the Internet and send e-mails and faxes.

10
• H/PC Pro devices
– The size and features of the H/PC Pro device is more than PDAs but less than
that of typical notebook PCs.
– includes a full-sized keyboard, RAM with very low storage capacity, and a
slow-speed processor
– do not have a secondary storage disk.

APPLICATIONS OF COMPUTER

The various application areas of computer are described below:


Education:
Computer is a very effective tool which can be used for teaching and learning, result
processing, student data processing, question preparation, handouts and note preparation, etc
and also online education.
Industries:
Industrial research, budgeting, process control, all are computer based. The robotics are also
computer based. Nowadays robots are used in complicated industrial process which is
dangerous for human.
Entertainments:
Different types of entertainment fields such as multimedia, film making with animation,
graphics, audio and visual design are done with the help of computer.
Hospital:
The research in health is done with the help of computer. It is applied to medicine, surgery
and research.
Data processing:
All the types of data processing like as word, data, salary, income tax, database processing
etc. are processed through computer.
Science and Engineering:
For every branch of engineering, computer is considered as a strong tool like civil, electrical
and computer to aeronautic, ceramics, chemical and leather technology.
Offices:
Computers are used in small offices as well as large offices. It is used for preparing reports,
storing/deleting reports, updating reports etc. Most of the offices use word processing package,
spreadsheet package, graphics package, presentation package, database package etc.
Advertisement:
Computers are used in the different fields of advertisement such as business advertisement,
film advertisement, education advertisement etc.
Communications:
E-mail, e-fax, internet etc. are computer based communications. The computer and Internet
integration is the backbone of recent communication.
Library:
Computer software is used for management of library. It is used for keeping the records of
book, updating book records, and records of books issued or submitted.
Weather Forecasting:

11
Computer programs are used for weather forecasting. The past and the present data help to
predict the climate.
Hotel management:
Computers are used for front desk management, preparing trial balance sheet, documentation
etc. in hotel management.

BITS BYTES WORD

A bit is a BInary digiT. A bit (short for binary digit) is the smallest unit of data in a computer.
A bit has a single binary value, either 0 or 1. In most computer systems, there are eight bits in
a byte. A group of N bits can be arranged in 2N different patterns. So a byte can hold 28 = 256
different patterns. Half a byte (four bits) is called a nibble. In some systems, the term octet is
used for an eight-bit unit instead of byte. In many systems, four eight-bit bytes or octets form
a 32-bit word.

12
BLOCK DIAGRAM OF COMPUTER

Central Processing Unit (CPU)

Central Processing Unit (CPU) consists of the following features −

• CPU is considered as the brain of the computer.

13
• CPU performs all types of data processing operations.

• It stores data, intermediate results, and instructions (program).

• It controls the operation of all parts of the computer.

CPU itself has following three components.


• Control Unit

• ALU(Arithmetic Logic Unit)

• Memory or Storage Unit

It manages and coordinates all the units of the computer.


• It communicates with Input/Output devices for transfer of data or results from
storage.
• It does not process or store data.

ALU (Arithmetic Logic Unit)


Function of arithmetic section is to perform arithmetic operations like addition, subtraction,
multiplication, and division. Function of logic section is to perform logic operations such as
comparing, selecting, matching, and merging of data.

Input Device:
• equipment/hardware which helps us enter data into a computer is called an input
device.
• For example keyboard, mouse, etc.

Output Device:
• equipment/hardware which gives out the result of the entered input, once it is processed
(i.e. converts data from machine language to a human-understandable language), is
called an output device.
• For example printer, monitor, etc.

Memory or Storage Unit


• This unit can store instructions, data, and intermediate results. This unit supplies
information to other units of the computer when needed. It is also known as internal

14
storage unit or the main memory or the primary storage or Random Access Memory
(RAM).

PRIMARY MEMORY AND SECONDARY MEMORY

ROM: ROM stands for Read Only Memory. The memory from which we can only read but
cannot write on it. This type of memory is non-volatile. The information is stored permanently
in such memories during manufacture. A ROM stores such instructions that are required to start
a computer. This operation is referred to as bootstrap. Types of ROM:

15
• PROM (Programmable Read Only Memory)
• EPROM (Erasable and Programmable Read Only Memory)
• EEPROM (Electrically Erasable and Programmable Read Only Memory)

Secondary Storage Device

Alternatively referred to as external memory, secondary memory, and auxiliary storage,


a secondary storage device is a non-volatile device that holds data until it is deleted or
overwritten. Secondary storage is cheaper than primary
storage.

16
17
INPUT AND OUTPUT DEVICES

18
19
20
21
Speakers
• "Most computers allow you to hook up external speakers"
• Speakers are popular output devices
• They receive audio input from the computer's sound card and produce audio output in
the form of sound waves.
• Allows to increase the volume
• Speakers usually come in pairs

22
COMPUTER NETWORK
A computer network is a group of computer systems and other computing hardware devices that are
linked together through communication channels to facilitate communication and resource-sharing
among a wide range of users.
Networks are used to:

• Facilitate communication via email, video conferencing, instant messaging, etc.


• Enable multiple users to share a single hardware device like a printer or scanner
• Enable file sharing across the network
• Allow for the sharing of software or operating programs on remote systems
• Make information easier to access and maintain among network users

Types
Local area network (LANs) connect computers and peripheral devices in a limited physical
area, such as a business office, laboratory, or college campus, by means of links (wires,
Ethernet cables, fibre optics, Wi-Fi) that transmit data rapidly. A typical LAN consistsof two
or more personal computers, printers, and high-capacity disk-storage devices called file
servers, which enable each computer on the network to access a common set of files.
A metropolitan area network (MAN) is a computer network that interconnects users with
computer resources in a geographic area or region larger than that covered by even a large
local area network (LAN) but smaller than the area covered by a wide area network
(WAN). The term MAN is applied to the interconnection of networks in a city into a single
larger network which may then also offer efficient connection to a wide area network.It is
also used to mean the interconnection of several local area networks in a metropolitan area
through the use of point-to-point connections between them.
Wide area network (WANs) connect computers and smaller networks to larger networks over
greater geographic areas, including different continents. They may link the computers bymeans
of cables, optical fibres, or satellites, but their users commonly access the networks viaa modem
(a device that allows computers to communicate over telephone lines). The largest WAN is
the Internet, a collection of networks and gateways linking billions of computer users on every
continent.

23
Hardware & Software
Hardware
• Physical devices of computer system
• Equipment that processes the data
• Controlled by software
• Physical devices
– Keyboard
– Mouse
– Monitor
– Other devices
Software

• Software is a set of instructions, data or programs .


• In contrast, the term 'hardware' refers to the physical components that you can see
and touch, such as the computer hard drive, mouse, and keyboard.
• There are two main types of software: systems software and application software.

Difference between Hardware and Software

Difference between System Software and Application Software

S.No. System Software Application Software

24
System software is used for operating Application software is used by user to
1. computer hardware. perform specific task.

System softwares are installed on the


computer when operating system is Application softwares are installed
2. installed. according to user’s requirements.

In general, the user does not interact with


system software because it works in the In general, the user interacts with
3. background. application sofwares.

System software can run independently. Application software can’t run


It provides platform for running independently. They can’t run without
4. application softwares. the presence of system software.

Some examples of system softwares are Some examples of application softwares


compiler, assembler, debugger, driver, are word processor, web browser, media
5. etc. player, etc.

Language Processor
• Compiler –
reads the program written in high level language and translates it into machine
language

• Assembler –
translate the program written in Assembly language into machine code.

• Debugger
• allows testing and debugging programs
• used to remove bugs from code

25
Operating System
• A collection of programs that handle technical tasks
– Manage resources
– Provide user interface
– Run applications
• Examples:
– Windows 7
– Mac OS X
• Also called the software environment or platform

Functions of an Operating System


• Manages computer resources
– Coordinate memory, processing, storage, printers and monitors
– Monitor system performance
– Schedule tasks
– Provide security
– Start-up the computer

26
• Provides user interface
– Graphical user interface (GUI)
• Runs applications
– Multitasking
– Foreground and background applications

CHARACTERISTICS OF AN ALGORITHM
• Finiteness: An algorithm should have finite number of steps and it should end after a
finite time.
• Input: An algorithm may have many inputs or no inputs at all.
• Output: It should result at least one output.
• Definiteness: Each step must be clear, well-defined and precise. There should be no
any ambiguity.
• Effectiveness: Each step must be simple and should take a finite amount of time.

Program Design Tools: Algorithms, Flowcharts, Pseudocodes


Algorithm
An algorithm is a step by step procedure to solve a given problem in finite number of steps by
→ accepting a set of inputs and
→ producing the desired output for the given problem
• Example: Write an algorithm to add 2 numbers
Step 1: Start
Step 2: Declare variables num1, num2 & sum.
Step 3: Read values of num1 and num2.
Step 4: Add num1 & num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
Pseudocode as a problem solving tool
Pseudocode is used to translate problem description written in English language to C
language
Most programming problems are too long and complex to be translated directly. It is difficult
to go directly from English language description of the program to the ‘C’ program.
A typical problem may take one or two pages. Most of the programmers find it difficult to
translate directly from English to ‘C’.(or any computer language)

27
As a problem solving tool at least one intermediate step between English and C is used. This
is called as Pseudo code.
Pseudo code cannot be compiled & executed like a regular program
Definition
Pseudo code is an outline of the basic structure or logic of the program. Pseudo code consists
of statements which are a combination of English and C. Pseudocode
is a method of describing the algorithm using a combination of
→ natural language (English like words) and
→ programming language
For Example:
Problem 1: Display a list of numbers from 4 to 9. Next to each number, display its square
start with the first number
Compute its square
Display num and square number
Repeat the same for numbers from 5 to 9
Problem 2: Input two numbers and display their sum.
1) read num1, num2
2) find sum = num1 + num2
3) display sum
Problem 3: Input the marks and display message “passed” or “failed” based on the marks.
1) read marks
2) if student's marks is greater than or equal to 35
print "passed"
else
print "failed"
endif
ALGORITHMS
1. Algorithm to find sum of two integer numbers
INPUT: Two integer numbers
OUTPUT: Sum
1. Start
2. Read the value of first number as, n1.
3. Read the value of second number as, n2.

28
4. Initialize the value of sum as, s = 0.
5. Calculate sum as, s = n1 + n2.
6. Write out the sum as,s.
7. Stop

2. Algorithm to find average of three numbers


INPUT: Three integer numbers
OUTPUT: Avg
1. Start
2. Read the value of three numbers as, (x, y, z)
3. Calculate sum as, sum = x + y +z
4. Calculate average as, avg = sum / 3
5. Write out the average as, avg
6. Stop

3. Algorithm to find area of circle


INPUT: radius
OUTPUT: area
1. Start
2. Read the radius of circle as, r
3. Initialize pi as, pi = 3.142.
4. Initialize area of circle as, a = 0.
5. Compute the area of circle as, a = pi * r * r
6. Write out the area of circle as, a
7. Stop

4. Algorithm to find smallest of two numbers


INPUT: Two integer numbers
OUTPUT: small number either x or y
1. Start
2. Read the value of first number as, x
3. Read the value of second number as, y
4. Compare the numbers

29
5. If x < y go to step 7
6. Display y is smallest number and go to step 8
7. Display x is smallest number
8. Stop

FLOWCHART:
• Flowchart is the graphical/diagramatic representation of the algorithm.
• The pictures are more understandable than the text.
• We generally say that, one picture is worth more than 10,000 words.
• Flowchart use the predefined symbols.

EXAMPLES:
1. Draw a flowchart to find sum of two numbers

2. Draw a flowchart to find smallest of two numbers

30
1. Pseudo-code to add two numbers
Begin
input a, b
sum = a + b
print sum
End
2. Pseudo-code to compute pay
Begin
input hours
input rate
pay = hours * rate
print pay
End
3. Pseudo-code to compute average of three numbers
Begin
input x
input y
input z
sum = x + y + z
avg = sum / 3
print avg
End
4. Pseudo-code for calculating area of rectangle
Begin
input length
input width

31
Area=length*width
print Area
End

TYPES OF ERRORS

There are 2 types of error in C:


1. Syntax Errors
2. Logical Errors
1. Syntax Errors
These are also referred to as compile-time errors. These errors have occurred when the rule
of C writing techniques or syntaxes has been broken.
2. Runtime Errors
This type of error occurs while the program is running. Because this is not a compilation
error, the compilation will be completed successfully.

INTRODUCTION TO C

Note:
C is a general-purpose programming language. It is closely associated with the UNIX system
where it was developed, since both the system and most of the programs that run on it are
written in C.
C is structured and procedural programming language.
It was introduced in 1972 by Dennis Ritchie at the Bell Telephone Laboratories and was first
used with the UNIX operating system.
C allows to work with bits, bytes and addresses, which are the basic elements used for
computer's functioning.
C also provides portability to a program, which means that we can easily run a c program in
DOS as well as Windows Operating System.
C provides a variety of data types. The fundamental types are character, integers and floating
point numbers of several sizes.
History:

32
Prior to C, BCPL (Basic Combined Programming Language) language was used, which was
introduced by Ken Thompson.
The C language derives many features from the BCPL language.
Later on, in 1983, a committee was introduced to create the ANSI (American National
Standards Institute) standard to define the standards for the C language.
Finally, the ANSI standard was developed in early 1990s. This standard was also adopted by
ISO ( International Standard Organization) to develop the ANSI/ISO standard. By the end of
the 1999, the C standard was referred as C99.

Features Of C Language:
Is a structured programming language
Provides various operators – arithmetic, increment, decrement and relational
helps to develop efficient programs and system software
Can be compiled and executed on any computer
Allows manipulation of internal processor registers
Provides various data types – char, int, float and double
Allows the use of pointers for memory, array, structures and functions
Provides high level constructs and allows the programmer to make use of function calls

33
BASIC CONCEPT OF C PROGRAM (OR ) STRUCTURE OF C PROGRAM ( OR )
FORMAT OF C PROGRAM ( OR ) GENERAL OUTLINE OF C PROGRAM
The structure of a C program is shown below:

1. Documentation section: The documentation section consists of a set of comment lines


giving the name of the program, the author and other details, which the programmer
would like to use later.

Ex: //Program to print message

2. Link section: The link section provides instruction to the compiler to link or include
the required in-built functions from the system library such as using the #include
directive.

Ex: #include<stdio.h>

3. Definition section: The definition section defines all symbolic constants using
the #define directive.

Ex: #define PI 3.14

4. Global declaration section: There are some variables that are used in more than one
function; these variables are called global variables and are declared in this global

34
declaration section which is outside the definition of any function This section also
declares all the user-defined functions.

Ex: int x;

5. main () function section: A C program must have one main function section in its
structure. This section contains two parts; declaration part and executable part.
However, the content of these two parts can be mixed.
1. Declaration part: The declaration part declares all the variables used in the
executable part. Ex: int y;
2. Executable part: There is at least one statement in the executable part. These
two parts must appear between the opening and closing braces of the main
function. The program execution begins at the opening brace and ends at the
closing brace. The closing brace of the main function is the logical end of the
program. All statements in the declaration and executable part end with a
semicolon.

Ex: printf(“hello”);

6. Subprogram section: If the program is a multi-function program then the subprogram


section contains definition of all the user-defined functions which were declared earlier
in the Definition Section. User-defined functions are generally placed immediately after
the main () function, although they may appear in any order.

Ex: add( ) { }

All section, except the main () function section and link section may be absent when they are
not required.

//Program to print hello on the screen


#include <stdio.h>
#include <conio.h>
void main()
{
printf("Hello World");
}
Output:
Hello

FILES USED IN A C PROGRAM

A C program uses four types of files as follows:

35
Source Code File
• This file includes the source code of the program.
• The extension for these kind of files are '.c'. It defines the main and many more functions
written in C.
• main() is the starting point of the program.

Header Files
• They have an extension '.h'.
• They contain the C function declarations and macro definitions that are shared
between various source files.
• The header files are added at the start of the source code so that they can be used by
more than one function of the same file.
• C provides some standard header files which are available easily.

Common standard header files are:


i) string.h – used for handling string functions.
ii) stdlib.h – used for some miscellaneous functions.
iii) stdio.h – used for giving standardized input and output.
iv) math.h – used for mathematical functions.
v) alloc.h – used for dynamic memory allocation.
vi) conio.h – used for clearing the screen.

Object files
• They are the files that are generated by the compiler as the source code file is processed.
• These files generally contain the binary code of the function definitions.
• The object file is used by the linker for producing an executable file. It has a '.o'
extension.

Executable file
• This file is generated by the linker.

36
• Various object files are linked by the linker for producing a binary file which will be
executed directly.
• They have an '.exe' extension.

EXECUTING A C PROGRAM

37
CHARACTER SET
Character-set refers to the set of alphabets, letters and some special characters that are valid
in C language.
For example, the characters in C are:
→ Letters A-X, a-z, both upper and lower
→ Digits 0-9
→ Symbols such as + - * / %
→ White space

TOKENS

• A token is a smallest element of a C program.


• One or more characters are grouped in sequence to form meaningful words. These
meaningful words are called tokens.
• The tokens are broadly classified as follows
→ Keywords ex: if, for, while
→ Identifiers ex: sum, length
→ Constants ex: 10, 10.5, 'a', "bitm"
→ Operators ex: + - * /
→ Special symbols ex: [ ] ( ){ } > < ; : ‘ “ . % ~ + - * / # = - _ etc

Keywords
• Keywords are tokens which are used for their intended purpose only.

38
• Each keyword has fixed meaning (ie already defined by the compiler) and that cannot
be changed by user. Hence, they are also called reserved-words.
Rules for using keywords
• Keywords cannot be used as a variable or function.
• All keywords should be written in lower letters.
Some keywords are as listed below
auto, break, case ,char, const, continue ,default, do, double ,else ,float, for ,if, int,
long,register, return ,short ,signed, sizeof, struct,switch ,typedef, unsigned, void, while etc
Identifier
As the name indicates, identifier is used to identify various entities of program such as
variables, constants, functions etc.
Rules for identifiers:
• First character must be an alphabet.
• Must consist of only letters, digits or underscore.
• Cannot use keyword.
• Must not contain white space.
For ex:
area, length, breadth
Constants
Constants refer to fixed values that do not change during the execution of program.
Integer Constants:
• An integer constant refer to a sequence of digits.
• There are 3 types of integers namely: Decimal integer, octal integer and hexadecimal
integer.
o Decimal integer consist of a set of digits 0 through 9,precceded by an optional
– or + sign. Examples: -250, 11, +12, -45, -56789 etc.
o An octal integer constant consist of any combination of digits from the set 0
through 7. with a leading 0 • Eg: 037,0, 0456.
o A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer.
They may include alphabets A through F or f. Letter A through F represents
numbesr 10 to 15. For example, decimal 31 can be written as 037 in octal and
0x1f or 0x1F in hex.
• long constant is written a terminal l or L. e.g: 123456789L.

39
• Unsigned constants are written with a terminal u or U, and the suffix ul or UL indicates
unsigned long.
• Octal and hexadecimal constants may also be followed by L to make them long and
U to make them unsigned: 0XFUL is an unsigned long constant with value 15 decimal.
Real Constants:
• To represent quantities that vary continuously real constants are used.
Examples: -22.55, 45.56, -3456.99, 55.00, 6666.66 etc.
• The suffixes f or F indicate float constant; l or L indicate a long double. If suffix is not
specified, it is considered as double constant by default
• A real number may be expressed in exponential notation.
SYNTAX: mantissa e exponent.
Mantissa can be either real number expressed in decimal notation or an integer.
Exponent is an integer number with an optional + or – sign.
The letter ‘e’ separating the mantissa and the exponent, it can be written either lower
case or upper case.
SYNTAX: 0.65e4,12e-2.
Single Character Constants:
• A single character constant contains a single character enclose in a pair of single
quote marks.
Eg: ‘5’,’x’.
• Character constants have integer values known as ASCII values. Statement:
printf (“%d”, ’a’); would print number 97, the ASCII value of letter ‘a’.
String Constants:
• A string constant is a sequence of characters enclosed in double quotes.
• Characters may be letters, numbers, special characters and blank spaces.
Eg: “hello” , “1987”, “?...!”.
Back Slash Character Constants:
C supports some special back slash character constants that are used in output functions.
These characters combinations are known as escape sequences.

40
VARIABLE
• A variable is an identifier whose value can be changed during execution of the program. In
other words, a variable is a name given to a memory-location where the data can be stored.
• Using the variable-name, the data can be
→ stored in a memory-location and
→ accessed or manipulated
Rules for defining a variable
1) The first character in the variable should be a letter or an underscore
2) The first character can be followed by letters or digits or underscore
3) No extra symbols are allowed (other than letters, digits and underscore)
4) Length of a variable can be up to a maximum of 31 characters.
5) Keywords should not be used as variable-names. Uppercase and lowercase letters are
different
Valid variables:
a, principle_amount, sum_of_digits
Invalid variables:
3fact //violates rule 1
sum= sum-of-digits 62$ //violates rule 3
for int if //violates rule 5

DATA TYPES AND SIZES


• Data type defines the type of data to be stored in the memory location;
• C supports 3 classes of datatypes:

41
• Primary datatypes or basic data types are predefined data types in C which has fixed
size memory location to store the data.

Qualifiers
Qualifiers alter the meaning of primary data types to yield a new data type.
Size Qualifiers
• Size qualifiers alter the size of primary data type.
• The keywords long and short are 2 size qualifiers.
• For example:
long int i; //The size of int is 2 bytes but, when long keyword is used, that variable
will be of 4 bytes
short int i; //The size of int is 2 bytes but, when short keyword is used, that variable
will be of 1 byte
Sign Qualifiers
• Whether a variable can hold positive value, negative value or both values is specified
by sign qualifiers.
• Keywords signed and unsigned are used for sign qualifiers.
unsigned int a; //unsigned variable can hold zero & positive values only
signed int b; //signed variable can hold zero , positive and negative values
Constant Qualifiers
• Constant qualifiers can be declared with keyword const.
• An object declared by const cannot be modified.
const int p=5; //the value of p cannot be changed in the program.

42
Character type:
• It allows to store 1 byte character type data
1 byte = 8 bits (ie 28= 0 to 255 values can be stored)
01000001= 65 Ex: A
The ASCII value of A is 65 and it is stored in binary form ie 01000001
• The qualifiers signed & unsigned can be used with char data type.
• We can store only one character in character type variable
Ex: char ch=’a’; valid
char ch=’dd’; invalid

Data type size range of values


char 1 byte -128 to 127
unsigned characters 1 byte 0 to 255
signed characters 1 byte -128 to 127

Integer type:
• it is used to store whole number or integer numbers;
• The size of the integer is machine dependent.
• it supports 4 different types of data. The qualifiers short, long, signed & unsigned can
be used with int data type.
Ex: short int a; or short a;
long int a; or long a; // The word int can be omitted in such declarations.
short is 16 bits, long is 32 bits and int is either 16 bits or 32 bits. short is smaller than
int & int is smaller than long

float type:
• It is single precision floating point number and it is used to store fractional values.

43
• The size of float is 4 bytes.
Ex: float a=11.9;
• We can store only 6 digits after decimal point
Ex: 11.900000

double type:
• It is double precision floating point number and it is used to store fractional values.
• The size of double is 8 bytes.
Ex: float a=11.9154991;
• We can store 10 digits after decimal point
Ex: 11. 9154991891

void
• void is an empty data type.
• Since no value is associated with this data type, it does not occupy any space in the
memory.
• This is normally used in functions to indicate that the function does not return any
value.

DECLARATION OF VARIABLES
• The declaration tells the complier
→ what is the name of the variable used
→ what type of data is held by the variable
• The syntax is shown below:
data_type var_name; where var_name is any valid identifier

44
data_type can be int, float, double or char
data_type v1,v2,v3; v1,v2,v3 are variable-names
• For ex: int a, b, c;
float x, y, z;

INITIALIZATION OF VARIABLE (Assignment statements)


• The variables are not initialized when they are declared. Hence, variables normally
contain garbage values and hence they have to be initialized with valid data.
• There are several ways to assign the values. Simple one is using assignment statement
(operator is =).
num=4;
This assignment statement will store the value 4 in the physical location associated
with the variable num ie variable num is assigned the value 4.
General form of assignment statement
Variable_name=expression;
Evaluate the expression on the right hand side of the assignment operator and put this value
in the variable on the left hand side of the assignment operator.
The right hand side of assignment statement must be valid C expression. This expression may
be a constant or variable or an expression.

DECLARATION AND INITIALIZATION OF VARIABLE


• Syntax is shown below:
data_type var_name=data;
where data_type can be int, float or char
var_name is a name of the variable
= is assignment operator
data is the value to be stored in variable
• For ex: int a=10;
float pi=3.1416;
char c='z';
• The qualifier const can be used with variable. Const keyword will not change the
value of variable.
const int a=5;
const float pi = 3.142;

45
FORMATTED I/O FUNCTIONS
scanf() - Formatted Input Function
• The scanf function does following tasks:
→ Scan a series of input fields one character at a time
→ Format each field according to a corresponding format-specifier passed in
format- string (format means convert).
→ Store the formatted input at an address passed as an argument i.e. address-list
• Syntax is shown below:
scanf("format-string", address-list);
where format-string contains one or more format-specifiers, address-list is a list of
variables. Each variable name must be preceded by &
For ex:
scanf("%d %f %c", &x, &y, &z);

printf() - Formatted Output Function


• The printed or dispayed results after running a program is called output
• The printf function does following tasks:
→ Accept a series of arguments
→ Apply a format-specifier to each argument contained in the format-string
→ Output the formatted data to the screen
Forms of a printf statement
Two simple forms are

46
1. One that has just a literal string(a sequence of character within the quotations mark)
General form of printf with just a literal string is,

For ex: Write a program to print hi and hello


#include<stdio.h>
void main()
{
printf (“Hi, hello”);
}

2. One that has values of one or more expressions to be printed.


General form of a printf with expressions to be printed are,

Ex-
#include<stdio.h>
void main()
{
int x=4,y=5,sum;
sum=x+y;
printf(“ The sum of two numbers is %d”,sum);
}

47
Output:
The sum of two numbers is 9

GUIDELINES FOR printf


1. A printf always contain a control string or format string in quotation marks. The control
string may or may not be followed by some variables or expressions whose value we
want to print.
2. Each value to be printed needs a conversion specification like %d (format specifier) to
hold its place in the control string.
3. This conversion specification describes the exact way the value is to be printed. When the
printf is executed each conversions specifications is replaced by the value of the
corresponding expression, then it is printed according to the rules in the specification.
4. The symbol \n in the control string tells the machine to skip to a new line. This part of the
control string effects the appearance of the output but it is not displayed as a part of it.
Anything else within the control string (a word or a blank space or a punctuation symbol)
will print exactly as it appears.
5. If there are variables or expressions to be printed, commas are to be used to separate them
from the control string and each other.
Ex: printf (“%d %d \n ”, num, sqnum );
The control string for this printf is “%d %d \n “, and the two items to be printed are the
values of the variables num and sqnum. Because these variables hold integer values so the
conversion specification is %d (d stands for decimal or digit). The control string ends in
\n, it is considered as a single character called the newline character

48
49

You might also like