KEMBAR78
Module 1 Org | PDF | Integer (Computer Science) | Computer Data Storage
0% found this document useful (0 votes)
24 views41 pages

Module 1 Org

Uploaded by

ananyashankar456
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views41 pages

Module 1 Org

Uploaded by

ananyashankar456
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Atria Institute of Technology

MODULE 1

Introduction to digital computers


Computers have become the basic necessity for any organization. They are used for all sorts of
problem solving ranging from simple addition to highly complex calculations like research,
Engineering, Simulations, Weather forecasting etc.

A computer is an electronic device that is used for information processing. It accepts data and
instructions, stores it in its memory, processes and gives the results to the user. The term compute
is derived from Latin word ‘Compute’ which means to calculate. Therefore, the computer is a
calculation machine.

The computers that we see and use in our day to day life are digital computers. They are called
so because they use numbers to represent any piece of information. Digital computers work on
the principle of programmed instructions which give the computers a purpose and instruct what
to do.

Capabilities of a computer

A Computer is capable of processing the following tasks:

1] Huge data storage: A computer can store large amount of data and instructions in its memory.

2] Input and Output: A computer receives data and instructions as input and display output after
execution.

3] Processing: It processes the data entered by the user. Processing means performing the
necessary operations such as arithmetic or logical operations on the data.

Characteristics of computer

The basic characteristics of computer are

1] High Processing speed: A computer is an extremely fast information processing device. It


carries out all sorts of computations within a fraction of a second. It executes millions of
instructions per second.

2] Accuracy: It gives accurate result for correct input data. Here accuracy means the correctness
of processed data. If the input data is erroneous, the output will not be correct.

3] Reliability: It always gives correct results.

4] Versatility: Computers are used in all fields like teaching, training, simulations, media and
1
Atria Institute of Technology

entertainment etc.

5] Diligence: It does not feel tired. It can be used for hours, days or months.

2
Atria Institute of Technology

History of development of computers

1] Abacus: This is the first recorded computer. It was invented in china and used by Greeks,
Romans and Japanese.

2] Napier’s Bones: A mathematician John Napier introduced the concept of logarithms. He used
a set of bones to perform multiplication. Each bone was carved with numbers on it. These
numbers were so carved with numbers on it. These numbers so carved that by keeping them side
by side, the product of numbers could be obtained. Hence the name Napier’s bones.

3] Slide rule: It consists of 2 scales, one of which slides over the other, It was so designed that
whenever one scale slides over the other, The alignment of one on the other gave the result of
basic arithmetic operations.

4] Pascale in: It was made up of counter wheels. This was capable of performing addition,
subtraction, multiplication and division.

5] Rotating wheel calculator: It was designed based on the principle of counter wheels.

6] Jacquard’s loom: A textile manufacturer, invented this machine to automatically control the
weaving loom.

7] Differential Engine: A Professor of mathematics at the Cambridge university, Charles


Babbage, invented the differential engine. It was used to calculate various mathematical
functions.

8] Analytical Engine: Charles Babbage developed the analytical engine. This machine consisted
of five functional units such as input unit, memory unit, arithmetic unit, control unit and output
unit. The architecture of the modern digital computer resembles the analytical engine and hence
Charles Babbage is called the father of computers.

9] Mark I: It was capable of performing a sequence of arithmetic operations. The time needed to
perform multiplication and division was considerably reduced in this machine.

10] ENIAC: It is introduced after revolution in semiconductor technology. It is an acronym for


electronic numerical integrator and calculator. This was able to carry out 5000 additions per
second.

11] EDVAC: John Von Neumann Proposed a new concept of a large internal memory to store
instructions and data. This is known as the stored program concept. The first computer developed
on the principle of stored program concept was EDVAC. It is an acronym for Electronic Discrete
Variable Automatic computer.

12] UNIVAC- I: It is an acronym for universal automatic computer I. It was used for scientific
and commercial applications.

3
Atria Institute of Technology

Generations of computers:

The generations of computers are broadly classified into two types.

1] Non electronic generation: These are also referred to as the zero generation computers. They
were developed before the semiconductor revolution.

2] Electronic generation: Computer developed after 1946 are categorized into five generations.
Since they are mainly built with electronic circuitry, They are called the electronic generation
computers.

• First generation computers: These were built with vacuum tubes. Their speed was
10−3 sec.
• Second generation computers: These were built with diodes and transistors. Their speed
was 10−6 sec.
• Third generation computers: These were built with integrated circuits(IC’s). Their speed
was 10−9 sec.
• Fourth generation computers: These were built with Large scale integration(LSI). Their
speed was 10−9 to 10−12 sec.
• Fifth generation computers: The development of super computers was the key motivation
of the fifth generation computers. These were developed with Super Large scale
Integration(SLSI).

Basic Structure of a computer

A computer is a programmable device which performs the following 4 operations:

1] Accepting data and information from the user.

2] Storing data and information in its memory.

3] Processing data and information

4] Display the result.

4
Atria Institute of Technology

Block diagram of a computer

Input device: This is used to read data and instructions into computer. The different input
devices are keyboard, mouse, joystick, light pen etc. Keyboard is the most commonly used input
device.

System unit: This is responsible for storing and processing of data and instructions. The system
unit consists of CPU and memory devices. The term CPU stands for Central Processing
Unit(CPU). The CPU is main unit of computer system. Which performs all arithmetic and logical
operations. It is considered as brain of computer system. The data and instructions given by the
user are processed in this unit. The CPU consists of Control unit(CU) and Arithmetic and Logic
unit(ALU).

The control unit is an important unit in a computer. It controls and coordinates the activities of all
the units of a computer system. The functions of control unit are

1] Reading data and instructions from memory.

2] Understand the instructions.

3] Controlling transfer of data and instructions to and from memory.

4] Controlling input and output devices.

5] Overall supervision of a computer.

5
Atria Institute of Technology

The arithmetic and logic unit performs all arithmetic operations such as addition, subtraction,
multiplication division and modulus. It also performs logical operations such as AND, OR and
NOT.

Memory devices: Memory devices are used to store data and instructions given by the user. The
computer memory is measured in terms of bits, bytes and words. A bit is a binary digit, It can
store either 0 or 1. A byte is a sequence of 8 bits. A word is a combination of 2 bytes. The
computer memory is classified into:

1] CPU registers

2] Primary memory

3] Secondary memory

4] Cache memory

The CPU registers hold a limited amount of memory during execution. They are inside the CPU.
The main memory is the primary memory, Which holds data and instructions. The main memory
is a temporary memory that holds data and instructions till power supply is there. But the
secondary memory is a permanent memory, which holds data and instructions as long as user
wants. The cache memory is a high speed memory and present in between CPU and memory.
Unlike the main memory and secondary memory, the user cannot access the cache memory.

Output devices: Once the data and instructions are processed, the result can be displayed on
output devices. The monitor is the most commonly used output device. The other output devices
are printer, LCD’s, speakers and disks.

Categorization of computers

The computers can be categorized based on

1] Principle of working

2] Size and capacity

3} Processor and storage

Computers based on principle of working

Based on the principle of working , computers are classified as:

1] Analog computers

2] Digital computers

3] Hybrid computers

6
Atria Institute of Technology

Analog computers takes input which is continuous in nature such as temperature, pressure and
voltage.

Digital computers reads input which is discrete in nature such as graphical data.

Hybrid computers are the combination of both analog and digital computers. The hybrid
computers accept both analog and digital data as input.

Factors Analog computers Digital computers


Input Physical variables Graphical data
Processing Integration Arithmetic and logical
Output Graphical Numeric and graphical
Memory Unit Normally not required Necessary to store data and
instructions
Accuracy Limited More
Application Simulation In solving business and scientific
problems

Due to the advancement in the technology, the size , shape, processing power and price of the
computers are changing every year. Based on these factors, computer are categorized into:

1] Computers for individual users.

2] Computers for organizations.

Computers for individual users: Computers for individual users are used by only person at a
time. There are 6 types of computers in the individual users category. They are

1) Desktop computers
2) Workstations
3) Notebook computers
4) Tablet PC’s
5) Handheld computers
6) Smart phones

Computers for organizations: Computers for organizations can be used by more than 1 person
at a time. Such computers are classified as

1) Network servers
2) Mainframe computers
3) Mini computers
4) Super computers

The parts of a computer system

7
Atria Institute of Technology

There are four parts in a computer system . They are,

1) Hardware: The mechanical components of a computer system are called hardware


components. The example of hardware components are monitor, keyboard, hard disk
mouse etc.
2) Software: Software is a program or a set of programs written to carry out specific task. A
program is a set of instructions that performs certain tasks. Software tells the hardware
what to do. Software components are more expensive compare to hardware.
3) Data: Data is the raw information the computers can process. Data by itself doesn’t make
much sense to the user. It will give a meaning only when it is processed by the computer.
A processed data is called information. Data can be text, numbers, audio, video etc.
4) User: people who use computers are called users. No computer system is 100%
autonomous. They need human being in one or other way. So user is considered as part of
computer system.

Information processing cycle

Information processing cycle is a process that the computer follows in inputting data,
processing, outputting data and storing data. There are four steps in an information processing
cycle. They are

1) Input
2) Processing
3) Output
4) Storage

Input: Input is nothing but the data and instructions given to computer. In this phase , the
computer accepts data and instructions from the user. Input devices are used to accept and pass
the same to processing stage.

Processing: In this stage, the data and instructions given by the user are processed. The system
unit of a computer is responsible for processing. In system unit, both arithmetic and logical
operations are carried out to produce desired results.

Output: Output is nothing but the result. In this stage, the user can display the result. The results
may be in the form of text, number, audio, image etc.

Storage: The data and instructions should be stored for future use. The memory unit is
responsible for storage.

Algorithms and Flowcharts

Steps involved in problem solving

Problem solving by a computer involves following steps:

8
Atria Institute of Technology

1. Problem definition
2. Analysis
3. Design
4. Coding
5. Running the program
6. Debugging
7. Testing
8. Documentation

Problem definition

In this step, the problem solver should understand what is the input need to be given , what is
output we get and what is operation need to be performed.

Analysis: The given problem must be analyzed before it is solved. It involves finding type of
input we need to give and also finding the type of operation we need to perform, that is whether
it is arithmetic or logical operation.

Design: It is to write the blue print of solution. Algorithms ,flowcharts and pseudo code are some
of the design techniques.

Algorithm: An algorithm can be defined as a step by step procedure to solve a particular


problem. It consists of English like statements. Each statements must be precise and well defined
to perform specific operation.

The word algorithm is named by the mathematician name “Abu Jafar Mohammed Ibn Musa Al
Khowarizmi” the last two words of name took different pronunciations over the period such as
‘Alkhowarizm’,’Algorism’ and finally it became “Algorithm”.

Characteristics of an algorithm

Every algorithm have five important characteristics:

1] Input: Algorithm may accept zero or more inputs.

2] Output: It should produce at least one output, output is nothing but the result.

3]Definiteness: There should not be only ambiguity in instructions.

4] Finiteness: If we convert algorithm to program, the execution of program should complete in


fixed time. It should not take infinite time.

5] Effectiveness: The operations defined in algorithm should be simple.

Algorithmic Notations

9
Atria Institute of Technology

While writing algorithms, the following notations need to be followed.

1] Name of the algorithm: Give meaningful name for an algorithm, which specified the problem
to be solved.

2] Step number: Assign number to each instruction of an algorithm.

3] Explanatory comment: It is the description or explanation about an instruction. It should be


written with in square brackets.

4] Termination: It specifies the end of the algorithm. It generally a stop statement and it should
be the last instruction of algorithm.

Example 1: Write an algorithm to compute the area of circle.

Algorithm: Area of circle

Step 1: Read Radius

Step 2: [compute area]

Area= 3.14*r*r

Step 3: [print the area]

Print “area of circle=”, area

Step 4: [End of an algorithm]

Stop

Example 2: Write an algorithm to perform the basic arithmetic operations such as addition,
subtraction, multiplication and division.

Algorithm: Arithmetic operations

Step 1: Read A, B

Step 2: [calculate sum, difference, product and quotient]

Sum= A + B

Difference= A – B

Product= A * B

Quotient= A/B

Step 3: [print the Contents of sum, difference, product and quotient ]

10
Atria Institute of Technology

Print “ sum of A and B=”, sum

Print “difference, of A and B=”, difference,

Print “product of A and B=”, product

Print “quotient of A by B=”, quotient

Step 4: [End of an algorithm]

Stop

Example 3: Write an algorithm to find area of rectangle .

Algorithm: Area o rectangle

Step 1: Read l, b

Step 2: [calculate area of rectangle]

Area= l*b

Step 3: [print contents of area]

Print “ area of rectangle=” , area

Step 4: [End of an algorithm]

Stop

Example 4: Write an algorithm to calculate the simple interest and compound interest for the
amount deposited ( P ) for some years ( T ) for the rate of interest ( R ).

Algorithm: simple interest and compound interest

Step 1: [ read the value of P, R, T]

Read P, R, T

Step 2: [ calculate simple interest]

P∗R∗T
SI=
100

Step 3: [calculate compound interest]


T
R
( )
CI= P * 1 -p
+ 100

Step 4: [ print the contents of SI and CI]


11
Atria Institute of Technology

Print “simple interest=”, SI

Print “compound interest=”, CI

Step 5: [End of an algorithm]

Stop

Example 5: Write an algorithm to find largest of two numbers.

Algorithm: Largest of two numbers

Step 1: Read A, B

Step 2: [compare A and B]

If (A>B) then

Print “ A is the largest”

else

Print “ B is the largest”

Step 3: [End of an algorithm]

Stop

Example 6: Write an algorithm to find largest of 3 numbers.

Algorithm: Largest of three numbers.

Step 1:[ read values of A, B, C]

Read A, B, C

Step 2:[ compare A and B]

if (A>B) go to step 4

Step 3: [ compare B and C]

if (B>C) then

print “ B is largest”

else

print “ C is largest”

12
Atria Institute of Technology

Step 4: [ compare A and C]

if (A>C) then

print “ A is largest”

else

print “ C is largest”

Step 5: [End of an algorithm]

Stop

Example 7: Write an algorithm to compute the sum of first N natural numbers and their mean.

Algorithm: sum and mean of natural numbers

Step 1:[ read values of N]

Read N

Step 2: [set sum equal to zero]

sum=0

Step 3: [ compare the sum of N natural numbers]

For num =1 to N in Step of 1 do

sum= sum+ num

Step 4: [ compare mean]

∑¿
Mean= n
¿
Step 5: [print contents of sum and mean]

Print “sum of N natural numbers=” sum

Print “mean of N natural numbers=” mean

Step 6: [End of an algorithm]

Stop

13
Atria Institute of Technology

Flowcharts

The flowchart can be defined as a diagrammatic representation or graphical representation of an


algorithm. It is referred as blue print of an algorithm. Flow charts make use of geometrical
figures. They are

Geometric figure Name Function

oval Start and stop

Parallelogram Input and output

Rectangle processing

Diamond Decision making

Arrows Connections

Small circle Continuation

Hexagon Looping/ Repitation

Example 1: Draw a flowchart to find the area of triangle when its three sides are given.

14
Atria Institute of Technology

Example 2: Draw a flowchart to find the largest of 3 numbers

Example 3: Draw a flowchart to compute the factorial of a given number.

15
Atria Institute of Technology

Example 4: Draw a flowchart to find the roots of a quadratic equation a x2+ bx+ c=0

Example 5: Draw an algorithm and flowchart to reverse a given number.

Algorithm: Reverse an integer

Step 1:[read the number]

Read N

Step 2: [Initialization]
16
Atria Institute of Technology

Temp =N

Step 3: [Repeat until N greater than zero and compute the reverse]

Reverse = 0

Temp =N

While ( N>=0)

Digit= N mod 10

Reverse= Reverse*10+digit

N=N/10

Step 4:[ print given number and its reverse]

Print “ given number=”, temp

Print “ Reverse of number=”, reverse

Step 5: [End of an algorithm]

Stop

17
Atria Institute of Technology

Pseudo code: A Pseudo code is neither an algorithm nor a program. It consists of English like
statements which performs specific operations. In pseudo code, the program is represented in
terms of words and phrases, but the syntax is not followed.

The Pseudo code is

• Easy to read
• Easy to understand
• Easy to modify

Example: Write a pseudo code to perform basic arithmetic operations

Read a , b

Sum = a + b

Diff= a – b

Product= a * b

Quotient= a/ b

Print sum, diff, product, quotient

End

Coding: The process of writing program called coding. The computer does not process
algorithm or a flow chart, but executes the program. A program is a set of instructions to solve a
problem by computer.

Running the program : The program will be executed in the CPU. This phase of problem
solving involves 3 steps.

• Store data and instructions


• Understand the instructions
• Perform computations

The user writes program and store it in memory. All the instructions stored in the memory, are
read one by one by the CPU, understand it. Then it will perform specified operations. The result
of operations is stored in memory again. And also the result is displayed in output devices.

Debugging: Bug is nothing but error or mistake. The process of detecting and correcting errors
in the program is called debugging. The term debug was introduced after detecting a bug in
Mark-I, by Admiral Gracehopper. She removed the bug from the machine and wrote in a The
Mark - I was debugged today”.

Generally programmer do 3 types of errors, they are

18
Atria Institute of Technology

• Syntax error
• Logical error
• Run time error

Syntax error: This type of errors will occur when we don’t follow syntax while writing
programs. On encountering these errors the compiler displays an error message specifying the
line number where the error has occurred. It is easy to debug these errors. For example, the
syntax of initializing a variable in c is

Variable = expression;

If we miss semicolon in the above statement, then there will be an error.

Logical errors: Logical errors occur during coding process. When the programmer writes a
program, he must take care of correct operations to be performed. Even though logical errors are
there in a program, the program will get executed, but it will give unexpected results. It is very
difficult to debug such as errors, because compiler doesn’t display them. We can eliminate such
errors through execution of program by giving inputs.

Runtime errors: These errors when we execute instructions which have ambiguity. These errors
may occur due to errors in program like divide by zero or due to device errors, keypunch errors,
incorrect data input etc. The computer will print these error messages.

Testing: The process of executing the program to test the correctness of outputs is called testing.
The program is tested by executing with different sets of data. We can find logical errors using
the process.

Documentation: While writing programs, it is a good programming practice to write a brief


explanation on the program. This explanation is called comment. It explain how the program
works and how to interact with it. Thus, it helps the other programmers to understand the
program.

There are 2 types of documentation. They are,

• Internal documentation
• External documentation

Internal documentation: This documentation is a comment statement within a program. It


describes the function of the program. These statements are not converted to machine language.

There are 2 types of comments.

• Single line comments: These will start with //


• Multiline comments( block comments): These comments should be written with in /*
comment line */

19
Atria Institute of Technology

External documentation: This documentation is an executable statement in a program. It


may be a message to the user to give inputs. These can be written using output statements. It
makes the program more attractive and interactive. Some examples are,

printf(“enter values of a and b”);

printf(“do you want to continue”);

20
Atria Institute of Technology

Introduction to Programming
Importance of C

C became very popular compared to other programming languages introduced before C like
BASIC, COBOL, FORTRAN etc. The increasing popularity of C is due to its desirable
qualitiesThey are

1) C has rich set of built in functions and operators which can be used to write any complex
program.
2) Programs written in C are efficient and fast C is many times faster than BASIC.
3) They are only 32 keywords in ANSI C.
4) C is portable language. This means that C programs written in one computer can be run
on another computer with little or no modification.
5) C language is well suited for structured programming, this requires the programmer to
think of a problem in terms of functions.
6) C has the ability to extend itself. A C program is basically a collection of functions that
are supported by C library. We can add our own functions to C library.

Basic structure of C programs

The documentation section consists of a set of comment time giving the name of the program the
author name and other details,

The link section provides instructions to the complier to link functions from system library
likestdio.h,stdlib.h etc

In definition section, we can define all symbolic constants

These are some variables that are used in more than one function. Such variables are called
global variables and are declared in the global declaration section.

Fig: Basic structure of C program


21
Atria Institute of Technology

Every c program must have on main () function section.This section contains two parts,
declaration part and executable part. The declaration part is used todeclare all the variables which
need to be used in executable part.There should be at least one statement in the executable part.
These two parts must appear between opening and closing braces. The program execution begins
at open brace brace of main () function and ends at closing brace. The closing brace of main ()
function is the logical end of program. All statements in declaration and executable part must end
with a semicolon.

Executing a C program

Execution of a program in C involves following steps.

1. Creating the program


2. Compiling the program
3. Linking the program with functions that are needed from c library.
4. Executing the program

22
Atria Institute of Technology

Constants variables and data types


Character set

The group of characters which are used to program is called characters set. The characters in C
are grouped into following categories.

1) Letters(A-Z and a-z)


2) Digits (0 to 9)
3) Special characters
4) White spaces.

Special characters

, comma | vertical bar ^ caret


23
Atria Institute of Technology

. period / slash *asterisk


; semicolon \ backslash - Minus sign
: colon ~ tilde + plus sign
? question mark _ underscore <opening angle bracket(or)
less than sign
‘ apostrophe $ dollar sign > closing angle bracket(or)
greater than sign
“ quotation mark % percent sign ( left paranthesis
! exclamation mark & ampersand ) right paranthesis
[ left bracket ] right bracket { left brace
} right brace # number sign

White spaces:- These are used to separate words

Trigraph characters:- Many non English keyboards do not support all the characters which are
mentioned above. So ANSI C introduces the concept of trigraph characters to provide a way to
use these characters in a program, which are not available in keyboard.

Each trigraph character starts with ??for example

Trigraph Character Translation


??= #
??( [
??) ]
??< {
??> }
??! |
??/ \
??- ~

C tokens

The smallest units of a program are called tokens C token are categorized into six types They are

24
Atria Institute of Technology

Keywords and identifiers

Each C word can be categorized as keyword or an identifiers. Keywords are the words which
have special meaning and which should not be changed. There are totally 32 keywords in C.
They are

Auto continue extern long sizeof unsigred

Break default float register static double

Case do for return switch int

Char else goto short typedef struct

Const enum if signed union void

Volatile while

Identifies are names of variables, functions and arrays.

These are user defined names and consists of letters, digits and underscore.

Rules to create identifiers

1) First character of variable must be alphabet (or) underscore


2) Variable name must consist of only letters, digits and underscore
3) Variable name should not exceed 31 characters
4) Keywords should be used as variable
5) Variables should not contain white spaces.

Constants

Constants are the values which do not change throughout execution of program. C supports
several types of constants.They are

25
Atria Institute of Technology

Integer Constants

An integer constants is a number which consist of sequence of digits. Integers constants are into
3 types

1) Decimal integer constants


2) Octal integer constants
3) Hexadecimal integer constants

Decimal integer constants consist of set of digits, 0 through 9. These constants may be positive
or negative. Valid example of decimal inters constants are

12 -- 125 12468—96

Embedded space, commas and special characters should not be used. For example

12 60 20,000 5$85

are invalid

An octal integer constants consists of any combination of digits from the set 0 through 7, with a
leading 0. For example

015 0751 0468


26
Atria Institute of Technology

A sequence of digits preceded by ox or OX are called hexadecimal integer constants. They can
also contains alphabets A to F. the letter A through F represent the number 10 through 15. For
example

0x76A 0XAF 0x5D

Real constants

Real constants are numbers which have fractional part. Real constants can be positive or
negative. For example

0.0083 - 0.72 435-36

Its is possible to omit digits before decimal points or digits after decimal point for example

215. .95 -.71 .5

A real number can also be expressed as exponential (or)scientific notation. The general syntax of
scientific notation is

Mantissa E/e exponent

The mantissa is either a real number expressed in decimal notation or an integer. The exponent is
an integer number with an optional plus or minus sign. Examples are

0.65c4 12c-2 1.5c0 5 3.18 E3 -12E-1

The values 215.65 can also be written as 2.156 5e2

Single character constants

A single character constant contains a single character enclosed within a pair of single quotes.
For example

`5’ ‘x’ ‘;’

Character constants are associated with integer values called ASCII values. For example

Prints (“%c”, ‘97’)

Would print the number 97. Similarly

Print(“%c”, ‘97’)

Would print the output as ‘a’


27
Atria Institute of Technology

String constants

A string constant is a sequence of characters enclosed in double quotes. The characters may be
letters,digits,special characters and so on. Examples are

“abcd” , “1987” , “hello world” , “+ - 53”

The characters constant ‘x ’is not same as string constants “x” the string constants are not
associated with integer values.

Backslash character constants

C supports some special backslash character constants that are used in output functions. They are
also called escape sequences. They are

Variables

A variable is name of memory location where we can store data. A variable may take different
values at different times throughout program execution. The programmer should give meaningful
name for a variable.

Data Types

C supports three classes of data types. They are

1) Primary data types


2) Derived data types
3) User defined data types

The primary data types supported by C are


28
Atria Institute of Technology

1) Int (integer)
2) Float (floating point)
3) Double (double precision floating point)
4) Char (character)
5) Void

Data type Range of values


Char -128 to 127
Int -32,768 to 32,767
Float 3.4e-38 to 3.4e +38
Double 1.7e-308 to 1.7e+308
Primary data types
Integral type
Integer
character
Signed unsigned
Char
Int unsigned int
Signed char
Short int unsigned short
int Unsigned char

Long int unsigned long

Floating point type


void
Float double long
double

Integer types

Integers are where numbers. Generally, integers occupy 2 bytes or 4 bytes to store a number,
depending on the computer . The integers can be signed or unsigned. If we declare int, by default
computer assumes it as signed integer, Where we can store both positive and negative numbers.
A signed integer uses 1 bit for sign and remaining bits to store number. If an integer takes 2
bytes, then the range of values can be stored are -32768 to 32767( that is −215 to 215 -1) for
signed integer.

29
Atria Institute of Technology

C has 3 classes of integer storage namely short int, int and long int. Short int takes half the size
of int and long int takes double the size of memory to store number. Signed and unsigned are
called qualifiers.

Size and range of data types

Type Size Range


Char or signed char 8 -128 to 127
Unsigned char 8 0 to 255
Int or signed int 16 -32,768 to 32,767
Unsigned int 16 0 to 65535
Short int or signed short int 8 -128 to 127
Long int or signed long int 32 -2,147,483,648 to 2,147,483,647
Unsigned short int 8 0 to 255
Unsigned longt int 32 0 to 4,294,967,295
float 32 3.4E – 38 to 3.4E + 38
double 64 1.7E – 308 to 1.7E + 308
Long double 80 3.4E – 4938 to 1.1E + 4932

Short int
int
Long int

Integer types

Floating point types

Float uses 4 bytes to store numbers, with 6 digits of precision. Floating numbers are numbers
which have fractional part . If the accuracy provided by float is not sufficient, the type double
can be used to store number, which uses 8 bytes giving a precision of 14 digits. If the accuracy
provided by double is not sufficient, then we can use long double. Long double takes 10 bytes to
store a number.
float
double
Long double

Data types and their keywords

Data type Keyword


character char
Unsigned character Unsigned char
Signed character Signed char
Signed integer Signed int/ int
Signed short integer Signed short int/ short int/ short
Signed long integer Signed long int/ long int/ long
30
Atria Institute of Technology

Unsigned integer unsigned int/ unsigned


Unsigned short integer Unsigned short int/ unsigned short t
Unsigned long integer Unsigned long integer/ Unsigned long
Floating point float
Double precision floating point double
Extended double precision floating point Long double

Character types

A single character can be defined using char data type. Char takes 1 byte of memory. The
qualifier signed or unsigned char can be explicitely applied to char. The signed chars have range
of values 0 to 255, signed chars have range of values -128 to 127.

Void types

Void is used with functions.

Declaration of variables

Declaration of variable does two things.

1. It tells the compiler what the variable name is.


2. It specifies what type of data the variable will hold.

The declaration of variables must be done before they are used in the program. The syntax for
declaring a variable is data-type v1,v2,…….vn;

v1,v2,…….vn are name of variables. Variables are separated by commas. A declaration


statement must end with semicolon. Examples are

int amount;
float SI,CI;
double area:

User defined type declaration

typedef is a keyword which is used to give new name to existing data type, the syntax is

typedef type identifier;

type is name of existing data type, identifier is the new name given to existing data type. For ex

typedef int whole_number;

31
Atria Institute of Technology

typedef float fraction;

These new names can be used to declare variables like

whole_number a, b;

fraction x, y;

typedef cannot create new data type. The main advantage of typedef is that we can give
meaningful names to data types which increases the readability of program.

The another user defined data types is enumerated data type, the syntax is

enum identifier{ value1, value2,….valuen};

The identifier is a user defined enumerated data type. enum is used to give meaningful names to
integer constants. For ex

enum day{ Monday, Tuesday, Wednesday, Thursday };

The compiler automatically assigns integer digits beginning with 0 to all enumeration constants.
That is the enumeration constant Monday is assigned with 0, Tuesday is assigned with 1 and so
on.

To avoid automatic assignments, we can define like

enum day { Monday=10, Tuesday, Wednesday, Thursday };

Here the constant Monday is assigned with value 10. The remaining constants are assigned
values that increase successively by 1. We can also define like

enum day { Monday=10, Tuesday, Wednesday=25, Thursday };

then Tuesday will be assigned with 11 and Thursday will be assigned the value 26.

The enum data type is used to declare variables like

Day week-day=Monday;

Then week-day is assigned assigned with value 10.

Declaration of storage class

Variables in C can have not only data types but also storage class that provides information about
lifetime of variables. In C, there are 4 storage classes. They are

1. Auto: Local variable can be used only within the function/block in which it is declared.
2. Static: These variables will retain values even after completion of function execution.
3. Extern: Variable declared I one file can be used in another file using extern storage class.
32
Atria Institute of Technology

4. Register: Variables stored in registers.

Examples of declaration of variables using storage classes are


auto int count;
extern int amount;
register float rate;
static double total;

NOTE: static and extern variables are automatically initialized to zero. Auto variables
have garbage values before initialization.

Assigning values to variables

Values can be assigned to variable using assignment operator(=). For ex


a=10;
At the time of declaration itself, a variable can be initialized like
int b=25;
In single C statements, multiple assignments statements can be written like
X=25; y=25;
The variables can also be initialized by writing expressions like
X=count+2;
The expression at RHS will get evaluated first, and that value is assigned to x.

Symbolic constants

We can use constants in a program. These constants may appear in a number of places in
program. One example is 3.412, representing the mathematical constant ‘ pi’, we face
two problems in writing programs which contains constant values. They are
1] problem in modification of program
2] problem in understanding the program

Modifiablity

If we want to change value of pi from 3.14 to 3.14159 to improve accuracy, then we need
to search whole program for the usage of pi value and the we need to change the value
explicitely.

Understadibility

When a numeric value appears in a program, its use is not always clear, especially when
the same value means different things to different places. For ex, if we use 3.14 value in
our program, it may not be value of pi always. So if we give meaningful names to values,
then it increases understadibility.

The syntax to define symbolic constants are


33
Atria Institute of Technology

#define symbolic_name constant_value


#define is preprocessor directive. Symbolic_name is name of constant. Constant_value is
value associated with a constant. For ex
#define PI 3.14

The following rules need to be followed while defining symbolic constants.

1. Symbolic names have same form as variable names.


2. No blank space between # and define.
3. # must be first character in line
4. Keywords should not be used as symbolic name
5. After definition, symbolic constants should not be assigned with any other values.
6. #define statements must o ted with semicolon.
7. A blank space is required between #define and symbolic name and also between
symbolic name and value.

Declaring a variable as constant

We may want to declare certain variables as constants in a program. It can be done qualifier
const at the time of declaration. For ex

const float interest_rate=0.1;

Const is a keyword which tells the compiler that the value of intrest_rate should not be modified
by program.

Managing Input and Output Operations


The set of functions used for input and output operations are collectively known as standard I/O
library. Each program that uses a standard Input/ Output function must contain the statement
#include<stdio.h> at the beginning.

Reading a character

The simplest of all input/output operations is reading a character from the standard input unit
(keyword) ad writing it to standard output unit(monitor). The character can be read using the
function getchar( ). The general syntax of getchar( ) is

Variable_name is valid c name that has been declared as char type. For ex

Char d;

d = getchar( );

34
Atria Institute of Technology

getchar( ) function reads a character from user ad stores it in the variable d.

writing a character

Like getchar( ), putchar( ) function is used to write character to output device. The syntax is

putchar (variable_name);

Variable_name is a char variable contains a character. For ex

d=’a’

putchar( d);

putchar( ) will display character ‘a’ on output screen.

Ex: Read a character from user and print it on to output device.

#include<studio.h>

# include<stdlib.h>

int main( )

char d;

printf(“ Enter a character/n”);

d = getchar( );

printf(“ The give character is:”); output:

putchar(d); Enter a character

return 0; K

} The given character is : K

Formatted input

Formatted input refers to an input data that has been arranged in a particular format. scanf( )
function is used to read input from user. The general syntax of scanf( ) is:

scanf( “control string”, V1,V2,….Vn); The control string specifies the format in which data is to
be read and V1,V2,…..Vn specify the address of locations where data obtained be stored.
control string and variables are separated by commas.
35
Atria Institute of Technology

Inputting Integer numbers

The syntax of control string to read an integer is %wd.

The % indicates a conversion specification, w is a width specified and d indicates integer data to
be read. For ex

scanf(“%d”, &a);

& is an address operator. The width can be use as

scanf(“%2d%4d”, &a, &b);

%2d indicates read 2 digits integer number, %4d indicates read 4 digits integer number. Store
first number in address of a and second number in address of b.

An input field may be skipped by specifying * in the place of field width. For ex

scanf(“%d %*d %d”, &a, &b);

If the input given is 123 456 789 .Then it will assign 7 it will assign 123 to a, 456 will be skipped
and it will assign 789 to b.

By default, space is used as separated between two inputs. If we want to change default
separator, then we can specify it in control string like

scanf(“%d$%d”, &a, &b);

For the above, input should be given as 4$5.

The data type character d may be replaced by l to read long integers and h to read short integers.

Ex: int main( )

{ output

int a, b , c ,d;

printf(“ enter 2 numbers”); enter 2 numbers

scanf(“%d %d”, &a, &b); 2 3

printf (“a=%d, b=%d”, a, b); a=2, b=3

printf(“ enter 3 numbers”); enter 3 numbers

scanf(“%d%*d %d”, &a, &b); 2 3 4

printf (“a=%d, b=%d”, a, b); a=2 b=4

36
Atria Institute of Technology

printf(“ enter 2 numbers”); enter 2 numbers

scanf(“%d$%d”, &a, &b); 2$3

printf (“a=%d, b=%d”, a, b); enter 2 numbers

printf(“ enter 2 numbers”); 1234 58

scanf(“%2d%4d”, &a, &b); a=12 b=34

printf (“a=%d, b=%d”, a, b); 123

scanf(“%4d%d”, &a, &b); a=58 b=123

printf (“a=%d, b=%d”, a, b);

return 0;

Inputting real numbers

The control string used to read float umbers is %f. For ex,

scanf(“%f %f”, &a , &b);

If the number needs to be read in scientific rotation, then control string can be used is %e like

scanf(“%e”, &a);

If the number to be read is of double type, then the specification should be %lf instead of %f.

Inputting character strings

The %c can be used to read a character. For ex

scanf(“%c”, &d);

To read a word, we can use %s. For ex

int main( )

char name[10];

printf(“enter string”); output

scanf(“%s”, name); enter string

37
Atria Institute of Technology

printf(“name=%s”, name); vinay

return 0; name= vinay

By using %S we cannot read multiple words, because %S consider space as end of input. For
that we can write

scanf(“[a-z]”, name);

It indicates that read the input which contains any character between a to z and space.

scanf(“[^$,+]”,name);

If we use ‘^ ‘symbol, it indicates, accept input which should not contain any character which are
specified in square brackets.

Reading mixed data types

In a single statement, we can read different type of data like

scanf(“%d %f %c”, &a, &b, &c);

Commonly used scanf format codes

Code Meaning
%c Reads a single character
%d Reads a decimal integer
%e Reads float value in scientific rotation
%f Reads a floating point value
%h Reads a short integer
%o Reads an octal integer
%s Reads a string
%u Reads an unsigned decimal integer
%x Reads a hexadecimal integer
%[. .] Reads a string of words

Formatted output

It is desirable that the outputs are produced in such a way that they are understandable and are in
an easy to use form. printf( ) function is used to print output on monitor. The general syntax of
printf ( ) is

printf(“ control string”, V1,V2,V3….Vn);

Control string consists of 3 things.

38
Atria Institute of Technology

1. Characters (or) information need to be print as it is.


2. Format specifications that define the output format.
3. Escape sequence characters such as \t, \n etc

The control string indicates how many to be printed and what are its types. The variables
V1,V2…Vn are printed according to specification of control string. The variables should match
in number, type and order with format specifications.

Output of integer numbers

The format specification for printing integer number is %wd

Where w is called width specifier.

Format output

printf(“%d”, 1286); 1 2 8 6

printf(“%6d”, 1286); 1 2 8 6
printf(“%2d”, 1286); 1 2 8 6
printf(“%06d”, 1286); 0 0 1 2 8 6
printf(“%-6d”, 1286); 1 2 8 6

If the width specifier is less than number of digits of a number, the complete number will be
printed. To force left justification, we can use ‘-‘ sign. The digit (or) character before width
specifier is called fill character and is used to fill empty spaces.

Output of real numbers

The format specification to print real number is %w.pf

The integer w indicates the minimum number of positions that are to be used for the display of
value and the integer p indicates the number of digits to be printed after decimal point.

Format output

Printf(“%f”, 57.7864); 5 7 . 7 8 6 4

5 7 . 7 8 6 4 Printf(“%7.4f”, 57.7864);

The subprogram section contains all user defined functions. All sections, expect the main
function section and link section may be absent when they are not required.

Programming style
39
Atria Institute of Technology

unlike some other programming languages( COBOL, FORTRAN etc) C is a free form language.
That is the C compiler does not care, where on the line we begin typing.

We must develop the habit of writing programs in lower case letters. C program statements are to
be written in lowercase letters.

Since C is a free form language, we can group statements on one line. For example

A = b;

X = y + 1;

Can also be written as

A = b; x = y + 1;

The code segment

Main()

Printf(“hello”);

Can also be written as

main( ) { Printf(“hello”);}

however, this style make the program more difficult to understand and should not be used.

40
Atria Institute of Technology

41

You might also like