You are on page 1of 104

Elements of a computer

The elements of a computer system fall into two major categories:


hardware and software.
Hardware is the equipment used to perform the necessary computations
and includes the central processing
Click to addunit
text (CPU), monitor, keyboard, mouse,
printer, and speakers.
Software consists of the programs that enable us to solve problems with a
computer by providing it with lists of instructions to perform.
Computer Hardware
Most Computer consist of the following components:
■ Main memory
■ Secondary memory, which includes storage devices such as hard
disks, CDs, DVDs, and flash drives
■ Central processing unit
■ Input devices, such as keyboards, mouses, touch pads, scanners,
joysticks
■ Output devices, such as monitors, printers, and speakers
Computer Hardware
Computer Hardware
The program must first be transferred from secondary storage to main
memory before it can be executed.
Normally the person using a program (the program user ) must supply
some data to be processed.
These data are entered through an input device and are stored in the
computer’s main memory, where they can be accessed and manipulated
by the central processing unit.
The results of this manipulation are then stored back in main memory.
Finally, the information in main memory can be displayed through an
output device
Memory
Memory is an essential component in any computer.
Memory
each memory cell has a unique address that indicates its relative position in
memory.
Figure 1.4 shows a computer memory consisting of 1000 memory cells with
addresses 0 through 999.
Most computers, however, have Clickmillions
to add text of individual memory cells, each
with its own address.
The data stored in a memory cell are called the contents of the cell.
In Fig. 1.4 , the contents of memory cell 3 are the number 26 and the
contents of memory cell 4 are the letter H.
Memory
a memory cell can also contain a program instruction.
The ability to store programs as well as data is called the stored program
concept :
A program’s instructions must be stored in main memory before they can be
executed
Bytes and Bits
A memory cell is actually a grouping of smaller units called bytes.
A byte is the amount of storage required to store a single character, such as the
letter H in memory cell 4 of Fig. 1.4 .
The number of bytes a memory cell can contain varies from computer to
computer.
Memory
A byte is composed of even smaller units of storage called bits ( Fig. 1.5 ).
The term bit , derived from the words binary digit , is the smallest element a
computer can deal with.
Binary refers to a number system based on two numbers, 0 and 1, so a bit is
either a 0 or a 1.
Generally, there are 8 bits to a byte.
Storage and Retrieval of Information in
Memory
Each value in memory is represented by a particular pattern of 0s and 1s.
A computer can either store a value or retrieve a value.
To store a value, the computer sets each bit of a selected memory cell to either 0
or 1, destroying the previous contents of the cell in the process.
To retrieve a value from a memory cell, the computer copies the pattern of 0s
and 1s stored in that cell to another storage area for processing;
the copy operation does not destroy the contents of the cell whose value is
retrieved.
This process is the same regardless of the kind of information—character,
number, or program instruction—to be stored or retrieved.
Main Memory
Main memory stores programs, data, and results.
Most computers have two types of main memory:
random access memory (RAM) , which offers temporary storage of programs
and data,
and read-only memory (ROM) , which stores programs or data permanently
Main Memory
RAM temporarily stores programs while they are being executed (carried out)
by the computer.
It also temporarily stores such data as numbers, names, and even pictures while
a program is manipulating them.
RAM is usually volatile memory , which means that everything in RAM will be
lost when the computer is switched off.
Main Memory
ROM, on the other hand, stores information permanently within the computer.
The computer can retrieve (or read), but cannot store (or write) information in
ROM, hence its name, read-only.
Because ROM is not volatile, the data stored there do not disappear when the
computer is switched off.
Start-up instructions and other critical instructions are burned into ROM chips
at the factory.
When we refer to main memory in this text, we mean RAM because that is the
part of main memory that is normally accessible to the programmer.
Secondary Storage Devices
Computer systems provide storage in addition to main memory for two
reasons.
First, computers need storage that is permanent or semipermanent so that
information can be retained during a power loss or when the computer is
turned off.
Second, systems typically store more information than will fit in memory.
Most personal computers use two types of disk drives as their secondary
storage devices—hard drives and optical drives.
Hard disks are attached to their disk drives and are coated with a magnetic
material
Secondary Storage Devices
Most of today’s personal computers are equipped with optical drives for
storing and retrieving data on compact disks (CDs) or digital versatile disks
(DVDs) that can be removed from the drive.
A CD is a silvery plastic platter on which a laser records data as a sequence of
tiny pits in a spiral track on one side of the disk.
One CD can hold 680 MB of data.
A DVD uses smaller pits packed in a tighter spiral, allowing storage of 4.7 GB of
data on one layer.
Some DVDs can hold four layers of data—two on each side—for a total capacity
of 17 GB,
Secondary Storage Devices
Secondary Storage Devices
• flash drive device that plugs into USB port and stores data bits as
trapped electrons . Typical USB flash drives store 1 to several GB of
data, but 64-GB drives are also available.
• Information stored on a disk is organized into separate collections
called files .
• One file may contain a C program.
• Another file may contain the data to be processed by that program (a
data file ).
• A third file could contain the results generated by a program (an output
file ).
Secondary Storage Devices
The names of all files stored on a disk are listed in the disk’s directory .
This directory may be broken into one or more levels of subdirectories
or folders,
where each subdirectory stores the names of files that relate to the
same general topic
Central Processing Unit
The central processing unit (CPU) has two roles:
coordinating all computer operations and performing arithmetic and logical
operations on data.
The CPU follows the instructions contained in a computer program to determine
which operations should be carried out and in what order.
It then transmits coordinating control signals to the other computer components.
For example, if the instruction requires scanning a data item, the CPU sends the
necessary control signals to the input device
Central Processing Unit
To process a program stored in main memory, the CPU retrieves each
instruction in sequence (called fetching an instruction ), interprets the
instruction to determine what should be done, and then retrieves any data
needed to carry out that instruction.
Next, the CPU performs the actual manipulation, or processing, of the data
it retrieved.
The CPU stores the results in main memory.
The CPU can perform such arithmetic operations as addition, subtraction,
multiplication, and division.
The CPU can also compare the contents of two memory cells
Central Processing Unit
The circuitry of a modern CPU is housed in a single integrated circuit or chip,
millions of miniature circuits manufactured in a sliver of silicon.
An integrated circuit (IC) that is a full central processing unit is called a
microprocessor.
A CPU’s current instruction and data values are stored temporarily inside the
CPU in special high-speed memory locations called registers
Some computers have multiple CPUs ( multiprocessors ) or a multi-core CPU.
These computers are capable of faster speeds because they can process
different sets of instructions at the same time.
Input/Output Devices
We use input/output (I/O) devices to communicate with the computer. They
allow us to enter data for a computation and to observe the results of that
computation.
You will be using a keyboard as an input device and a monitor (display screen)
as an output device.
When you press a letter or digit key on a keyboard, that character is sent to
main memory and is also displayed on the monitor at the position of the cursor
A computer keyboard has keys for letters, numbers, and punctuation marks plus
some extra keys for performing special functions. The twelve function keys
along the top row of the keyboard are labeled F1 through F12
Input/Output Devices
A mouse is a handheld device used to select an operation. Moving the
mouse around on your desktop moves the mouse cursor (normally a small
rectangle or an arrow) displayed on the monitor’s screen.
A monitor provides a temporary display of the information that appears on
its screen.
If you want hard copy (a printed version) of some information, you must
send that information to an output device called a printer
Computer Networks
local area network (LAN) computers, printers, scanners, and storage
devices connected by cables for intercommunication.
Computer Networks
Local area networks can be connected to other LANs using the same
technology as telephone networks.
Communications over intermediate distances use phone lines, fiber-optics
cables or wireless technology, and long-range communications use either
phone lines or microwave signals that may be relayed by satellite ( Fig. 1.8 ).
Computer Networks
Computer Networks
A network that links many individual computers and local area
networks over a large geographic area is called a wide area network
(WAN) .
The most well-known WAN is the Internet, a network of university,
corporate, government, and public access networks.
The most widely used aspect of the Internet is the World Wide Web
(WWW) , the universe of Internet-accessible resources that are
navigable through the use of a graphical user interface (GUI)
Computer Networks
If you have a computer with a modem, you can connect to the
information superhighway through a telephone line, television or fiber-
optic cable, or through wireless or satellite communications.
A modem ( modulator/ demodulator) converts binary computer data
into audio tones that can be transmitted to another computer over a
normal telephone circuit.
At the computer on the receiving end, another modem converts the
audio tones back to binary data.
Computer Softwares
software that makes the hardware friendly to the user.
Operating System
The collection of computer programs that control the interaction of the
user and the computer hardware is called the operating system (OS) .
The operating system of a computer is often compared to the conductor
of an orchestra, for it is the software that is responsible for directing all
computer operations and managing all computer resources.
Usually part of the operating system is stored permanently in a read-only
memory (ROM) chip so that it is available as soon as the computer is
turned on.
Computer Softwares
The ROM-based portion of the OS contains the instructions necessary for
loading into memory the rest of the operating system code, which typically
resides on a disk.
Loading the operating system into memory is called booting the computer .
Here is a list of some of the operating system’s many responsibilities:
1. Communicating with the computer user: receiving commands and
carrying them out or rejecting them with an error message.
2. Managing allocation of memory, of processor time, and of other
resources for various tasks.
Computer Softwares
3. Collecting input from the keyboard, mouse, and other input devices, and
providing this data to the currently running program.
4. Conveying program output to the screen, printer, or other output device.
5. Accessing data from secondary storage.
6. Writing data to secondary storage.
Computer Softwares
Application Software
Application programs are developed to assist a computer user in
accomplishing specific tasks.
For example, a word-processing application such as Microsoft Word or
OpenOffice.org Writer helps to create a document, a spreadsheet
application such as Microsoft Office Excel helps to automate tedious
numerical calculations and to generate charts that depict data, and a
database management application such as Microsoft Office Access or
dBASE assists in data storage and quick keyword-based access to large
collections of records.
Computer Languages
Developing new software requires writing lists of instructions for a computer
to execute.
However, software developers rarely write in the language directly understood
by a computer, since this machine language is a collection of binary numbers.
Another drawback of machine language is that it is not standardized: There is
a different machine language for every type of CPU.
This same drawback also applies to assembly language , a language in which
computer operations are represented by mnemonic codes rather than binary
numbers and variables can be given names rather than binary memory
addresses
Computer Languages

Table 1.3 shows a tiny machine language program fragment that adds two numbers and the equivalent fragment
in assembly language.
The symbol ? indicates that we do not know the contents of the memory cells with addresses 00000101 and
00000110.
Computer Languages
high-level language machine-independent programming language that
combines algebraic expressions and English symbols.
For example, the machine/assembly language program fragment shown in
Table 1.3 would be a single statement in a high-level language:
a = a + b;
Computer Languages
Computer Languages
Although programmers find it far easier to express problem solutions in
high-level languages, there remains the problem that computers do
NOT understand these languages.
Thus, before a high-level language program can be executed, it must
first be translated into the target computer’s machine language.
The program that does this translation is called a compiler . Figure 1.11
illustrates the role of the compiler in the process of developing and
testing a high-level language program. Both the input to and the output
from the compiler (when it is successful) are programs.
Computer Languages
The input to the compiler is a source file containing the text of a high-
level language program.
The software developer creates this file by using a word processor or
editor. The format of the source file is text, which means that it is a
collection of character codes.
For example, you might type a program into a file called myprog.c.
The compiler will scan this source file, checking the program to see if it
follows the high-level language’s syntax (grammar) rules.
Computer Languages
If the program is syntactically correct, the compiler saves in an object file the
machine language instructions that carry out the program’s purpose.
For program myprog.c , the object file created might be named myprog. obj .
Notice that this file’s format is binary.
This means that you should not send it to a printer, display it on your monitor, or
try to work with it in a word processor because it will appear to be meaningless
garbage to a word processor, printer, or monitor.
If the source program contains syntax errors, the compiler lists these errors but
does not create an object file.
The developer must return to the word processor, correct the errors, and
recompile the program
Computer Languages
Although an object file contains machine instructions, not all of the
instructions are complete.
High-level languages provide the software developer with many named
chunks of code for operations that the developer will likely need.
Almost all high-level language programs use at least one of these chunks of
code called functions that reside in other object files available to the system.
The linker program combines these prefabricated functions with the object
file, creating a complete machine language program that is ready to run.
For your sample program, the linker might name the executable file it creates
myprog.exe .
Computer Languages
Computer Languages
Algorithms

• An algorithm is a computable set of steps to achieve a desired result.


Criteria
• input
• output
• definiteness: clear and unambiguous
• finiteness: terminate after a finite number of steps
• Effectiveness: instruction is basic enough to be carried out
• Not sufficient that algorithms perform the required tasks.
• They should do so efficiently, making the best use of
• Space
• Time
Software Development Method
Software Development Method
1. Specify the problem requirements.
2. Analyze the problem.
3. Design the algorithm to solve the problem.
4. Implement the algorithm.
5. Test and verify the completed program.
6. Maintain and update the program
Algorithms

• Efficiency in Time and Space


• Time
• Instructions take time
• How fast does the algorithm perform?
• What affects its run-time?
• Space
• Data structures take space
• What kind of data structures can be used?
• How does the choice of data structure affect the runtime?
Algorithms
• Space complexity
• The space needed by a program consists of following components:
• Instruction Space – space needed to store the executable version of the program and is fixed
• Data Space – space needed to store all constants, variables values and has further two
components:
• Space needed by constants and simple variables. This space is fixed.
• Space needed by fixed sized structured variables, such as arrays and structures.
• Dynamically allocated space.
• Environment Stack space - Space needed to store the information needed to resume the
suspended function.
• Return address
• Value of all local variables and the value of formal parameters in the function being invoked.
Algorithms
Algorithms
Flowcharts

– A flowchart is a type of diagram, that represents an


algorithm or process, showing the steps as boxes of
various kinds, and their order by connecting these with
arrows. This diagrammatic representation can give a
step-by-step solution to a problem.

– Data is represented in the boxes, and arrows connecting


them represent direction of flow of data.

– Flowcharts are used in designing,


documenting or analyzing, a program in
various fields .managing process or
Flowchart
Symbols:
Terminator: Shows the starting and
ending points of a program

Data Input or output: Allows the user


to input data or to display the results .
Processing: Indicates an operation
performed by the computer, such as a variable
Assignment or mathematical operation

Decision: A diamond has two flow lines going


out. One is labeled as „Yes‟ Branch and the other
as „no‟ branch.
• Common Flowchart Symbols:
Predefined Process. Denotes a group of previously
defined statements. Ex: ―Calculate m!‖ Program
executes the necessary Commands to compute m
factorial
Connector. Connectors avoid crossing flowlines,
Connectors come in pairs, one with a flowline in and
the other with a flowline out.

Off Page Connector: Come in Pairs, Extends


Flow charts to more than a page

Flowline. Flowlines connect the flowchart


symbols and show the sequence of operations during
the program execution.
Examples
• Example 1: Finding the sum of two numbers.
• – Variables:
– • A: First Number
– • B: Second Number
– • C: Sum (A+B)
• – Algorithm:
– • Step 1 – Start
– • Step 2 – Input A
– • Step 3 – Input B
– • Step 4 – Calculate C = A + B
– • Step 5 – Output C
– • Step 6 – Stop
Flowcharts:
Start

Read A

Read B

C= A+B Print C Stop


• Example 2: Find the difference and the division of two
numbers and display the results.
• – Variables: -- Algorithm:
• N1: First number * Step 1: Start
• N2: Second number * Step 2: Input N1
• D : Difference * Step 3: Input N2
• V : Division * Step 4: D=N1–N2
* Step 5: V=N1 /N2
* Step 6: Output D
* Step 7: Output V
* Step 8: Stop
Flow Chart
Start

Read N1

Read N2

D=N1-N2

V= N1/N2 Print D Print V Stop


Example 3:
Work on the algorithm and the flow chart of the problem of
calculating the roots of the equation Ax2 + Bx + C = 0

• Variables:

– A: Coefficient of X2
– B: Coefficient of X
– C: Constant term
– delta: Discriminant of the equation
– X1: First root of the equation
– X2: Second root of the equation
• Algorithm:
- Step 1: Start
– Step 2: Input A, B and C
– Step 3: Calculate delta = B2 – 4AC
– Step 4:
If delta<0 go to step 6, otherwise go to 5
– Step 5:
If delta>0 go to step 7, otherwise go to 8
– Step 6:
Output ―complex roots‖. Go to step 13
– Step 7: Output ―real roots‖. Go to step 9
– Step 8:
Output ―equal roots‖. Go to step 9
– Step 9: Calculate X1=(-b+√delta)/(2A)
– Step 10: Calculate X2=(-b-√delta)/(2A)
– Step 11: Output X1
– Step 12: Output X2
– Step 13: Stop 42
Flowch
arts:
Read
Start Delta=B*B- 4*A*C
A,B,C
Yes No
Delta < 0
Yes
“Complex Roots” Delta>0
No

“Equal Roots”
“Real Roots”

X1=(-b+√delta)/(2*A)

X2=(-b-√delta)/(2*A)

Print X1 Print X2 Stop


43
Intoduction to C :
• A high-level programming language developed in 1972 by
Dennis
Ritchie at AT&T Bell Labs.
• C is a structured Language
• It was designed as a language to develop UNIX operating system
• American National Standards Institute (ANSI) approved first version
of C in 1989 which called C89
• Major changes were made in 1995 and is known as C95
• Another update was made in 1999 and is known as C99
Characteristics of C
• A high level programming language .
• Small size. C has only 32 keywords. This makes it relatively easy to learn.
• Makes extensive use of function calls.
• C is a structured programming.
• It supports loose typing (as a character can be treated as an integer and vice
versa).
• Facilitates low level (bitwise) programming
• Supports pointers to refer computer memory, array, structures and
functions.
• C is a Portable language.
• C is a core language
• C is an extensible language
Uses of C Language:
• C language is primarily used for system programming. The portability,
efficiency, the ability to access specific hardware addresses and low
runtime demand on system resources makes it a good choice for
implementing operating systems and embedded system applications.
• C has been so widely accepted by professionals that compilers,
libraries, and interpreters of other programming languages are often
implemented in C.
• For portability and convenience reasons, C is sometimes used as an
intermediate language by implementations of other languages.
Example of compilers which use C this way are BitC, Gambit, the
Glasgow Haskell Compiler, Squeak, and Vala.
• C is widely used to implement end-user applications
• C Programs
Structure Of C Program:
Preprocessor directives:

• Every C program is made of one or more


Preprocessor directives or commands.
• They are special instructions to the preprocessor that tell
it how to prepare the program for compilation.
• The preprocessor directives are commands that
give instructions to the C preprocessor.
• A preprocessor directive begins with a number
symbol (#) as its first non-blank character.
• A common preprocessor command is
―include‖. The
―include‖ command tells the preprocessor
that information is needed
• Preprocessor commands can start in any column, but they
traditionally start in column 1.
Ex: #include <stdio.h>
• This command tells the preprocessor that definitions from the
library file in the brackets < > is included in the program. The
name of the header file is ―stdio.h‖. This is an abbreviation
for ―standard input / output header file.
• C requires that certain standard libraries be provided in every
ANSI C implementation.
Global Declaration Section :
• Contains declarations that are visible to all parts of the
program
Declaration section :
• It is at the beginning of the function. It describes the data that
will be used in the function. Declarations in a function are
known as local declarations as they are visible only to the
function that contains them.
Statements:
• Statements follows the declaration section. It
contains the instructions to the computer.
•Every statement ends with a semi colon.

Comments:
Comment about the program should be
enclosed within /* */.
 Any number of comments can be written at any place
in the program.
Comments in the code helps to understand the code
Comments cannot be nested.
 For example, /* Cal of SI /* Author sam date 01/01/2002 */
*/ is invalid.
− A comment can be split over more than one line, as
/* This is
a jazzy
comment
main( ):
• The executable part of the program begins with
the function main‘. All statements that belong to
main are enclosed in a pair of braces { }.
First C Program
#include <stdio.h>
void main ()
{
printf("―Hello
World:\n");
}
• The main function
contains single
statement
C TOKENS

C TOKENS

KEYWORDS CONSTANTS STRINGS OPERATORS

IDENTIFIERS SPECIAL SYMBOLS


KEYWORDS

• Keywords are predefined, reserved words


used in programming that have special
meaning. Keywords are part of the syntax and
they cannot be used as an identifier. For
example: int money;
• Here, int is a keyword that indicates 'money' is
a variable of type integer.
Identifiers
Identifiers are names given to program elements such as
variables, arrays and functions.
Each identified object in the computer is stored at a unique address.
If we didn‘t have identifiers that we could use to
symbolically represent data locations, we would have to know and
use object‘s addresses. Instead, we simply give data identifiers and let
the compiler keep track of where they are physically located.
Rules for Identifiers:
Examples of Valid and
Invalid Names:
Constants:
• Constants are data values that cannot be changed during the
execution of a program.
• C constants can be divided into two
major categories:
Constants

Secondary
Primary Constants
Constants

Array
Pointer
Boolean Constants Structure
Integer Constants Union
Real Constants Enum etc..
Character Constants
• Boolean constants
A Boolean data type can take only two values. The
values are true and false.
• Integer Constants

Rules for Constructing Integer Constants


• An integer constant must have at least one digit.
• It must not have a decimal point.
• It can be either positive or negative.
• If no sign precedes an integer constant it is
assumed to be positive.
• No commas or blanks are allowed within an integer constant.
Example of Integer Constans
Constants
• Rules for Constructing Real Constants
: • Real constants are often called Floating Point constants. It
consists of integral part and fractional part. The real constants
can be in
– Fractional form
– Exponential form.
• In Fractional Form
– A real constant must have at least one digit.
– It must have a decimal point.
– It could be either positive or negative.
– Default sign is positive.
– No commas or blanks are allowed within a real constant.
Examples of Real
Constants
• Exponential Form
• In exponential form of representation, the real constant is
represented in two parts. The part appearing before ‗e‘ is
called mantissa, whereas the part following ‗e‘ is called
exponent.
Rules for constructing real constants expressed
in exponential form:
• The mantissa part and the exponential part should be separated
by a letter e.
• The mantissa and exponent part may have a positive or negative
sign.
• Default sign of mantissa part is positive.
• The exponent must have at least one digit, which
must be a positive or negative integer. Default sign is
positive.
Ex: 1.23 x 105 = 123000.0 is written as 1.23e5 or
1.23E5
Character Constants

• A character constant is a single alphabet, a single digit or


a single special symbol enclosed within two single quotes
(apostrophes).
• The maximum length of a character constant can be 1
character.
• The character in the character constant comes from the
character supported by the computer.

Ex: `A` `I` `5` `=` `a`


Fig: Symbolic Names for Control Characters
Coding constants
Literal Constant
• A literal is an unnamed constant used to specify
data. Ex: a=b+5;
hear 5 is a literal constant.

Defined constants

• A defined constant uses the preprocessor command


#define
Ex: #define rate 0.85
Preprocessor replaces each defined name, rate with
the value
0.85 wherever it is found in the source program

Memory Constants

• Memory constant use a C type qualifier, const to indicate that


STRINGS
• A string in C is merely an array of characters.
The length of a string is determined by a
terminating null character: '\0' .
• So, a string with the contents, say, "abc"
has four characters: 'a' , 'b' , 'c' , and the
terminating null character. The terminating
null character has the value zero.
SPECIAL SYMBOLS
• The following special symbols are used in C having some
special meaning and thus, cannot be used for some other
purpose.
• *+ () ,- , ; : * … = #
• Braces{}: These opening and ending curly braces marks the
start and end of a block of code containing more than one
executable statement.
• Parentheses(): These special symbols are used to indicate
function calls and function parameters.
• Brackets[]: Opening and closing brackets are used as array
element reference. These indicate single and
multidimensional subscripts.
Variables:
Variables are named memory locations that have a type, such as
integer or character, which is inherited from their type.
The type determines the values that a variable may contain and
the operations that may be used with its values.
To declare a variable specify data type of the variable followed by
its
name. Variable declaration always ends with a semicolon
Variable names should always be meaningful and must reflect
the purpose of their usage in the program.
Variable Declaration
Synatax: Type
var_name; Ex: int
float alary;
emp_num; char grade;
double balance_ amount;
unsigned short int acc_no;
Variable Initialization
– When a variable is defined, it contains unknown value.
The variable has to be initialized with a known value
– If a variable is not initialized, the value of variable may be either
0 or garbage depending on the storage class of the variable.
– We must initialize any variable with known data before executing
the function

Fig: Variable Initialization


Types
A type defines a set of values and a set of operations that can be applied
on those values.

Ex: – Type - light switch


Values –‘ON‘ or
‗OFF‘
Operations – ‗turn on‘ and ‗turn off‘

Fig:Data Types
Void Type:
– Is identified by the key word ‗void‘ and no operations.
– It is used to designate that a function has no parameters.
– It can also be used to define that a function has no return
value.

Integral Type:
Boolean:
–B
o
o
l
e
a
n

t
y
p
e
Integer
– An integer type is a number without a fraction part
– C supports four different sizes of the integer type and
is denoted by the keyword int
» short int
» sizeof (short) ≤ sizeof (int) ≤ sizeof (long) ≤ sizeof (long long)
» long int
int
» long long int
– Each integer size can be signed or unsigned integer. If
the integer is signed, one bit is used for signed( 0 is plus,
1 is minus). An unsigned integer can store a positive
number that is twice as large as the signed integer of the
same size.

Fig: Integer Types


Floating-point type:

Real
– Real type holds values that consists of
integral and fractional part.
– C support types float and double.
– Real type values are always signed.

Fig : Floating-Point Types


sizeof (float) ≤ sizeof (double) ≤ sizeof (long double)
• Data Types
Data Type Abbreviation Size Range
(byte)

char char 1 -128 ~ 127


unsigned char 1 0 ~ 255
int 2 or 4 -215 ~ 215-1 or -231 ~ 231-1
unsigned int unsigned 2 or 4 0 ~ 65535 or 0 ~ 232-1
int
short int short 2 -32768 ~ 32767
unsigned short unsigned 2 0 ~ 65535
int short
long int long 4 -231 ~ 231-1
unsigned long unsigned 4 0 ~ 232-1
int long

float 4
double 8

Note: 27 = 128, 215 =32768, 231 = 2147483648 73


Operators in C
• C language supports a lot of operators to be used in expressions.
These operators can be categorized into the following major groups:
1) Arithmetic operators
2) Relational Operators
3) Equality Operators
4) Logical Operators
5) Unary Operators
6) Conditional Operators
7) Bitwise Operators
8) Assignment operators
9) Comma Operator
10) Sizeof Operator
Operators in C
Arithmetic operators
• Assume the values a=9 and b=3

OPERATION OPERATOR SYNTAX COMMENT RESULT


Addition + a+b result = a + b 12

Subtraction - a-b result = a – b 6

Multiply * a*b result = a * b 27

Divide / a/b result = a / b 3

Modulus % a%b result = a % b 0


Equality Operators Operators in C
• C language supports two kinds of equality operators to compare
their operands for strict equality or inequality. They are equal to (==)
and not equal to (!=) operator.

OPERATOR MEANING
== RETURNS 1 IF BOTH OPERANDS ARE
EQUAL, 0 OTHERWISE
!= RETURNS 1 IF OPERANDS DO
NOT HAVE THE SAME VALUE, 0
OTHERWISE
Operators in C

Relational Operators
• Thease operators compares two values so also
called Comparison operators.
• Relational operators return true or false value,
depending on the MEANING
conditional relationship
the two
OPERATOR
between perands. EXAMPLE
< LESS THAN 3 < 5 GIVES 1
o > GREATER THAN 7 > 9 GIVES 0
<= 100 <=
LESS THAN OR EQUAL TO
100 GIVES 1
>= GREATER THAN EQUAL TO 50 >=100 GIVES 0
Operators in C
Logical Operators
• C language supports three logical operators.
They are 1) Logical AND (&&)
2) Logical OR (||)
3) Logical NOT (!)
• In case of arithmetic expressions, the logical expressions are
evaluated from left to right.
A B A &&B A B A || B A !A
0 0 0 0 0 0 0 1
0 1 0 0 1 1 1 0
1 0 0 1 0 1
1 1 1 1 1 1
Operators in C
Unary Operators
Unary operators act on single operands.
C language supports three unary
operators. They are :
1) Unary minus(-)
2) Increment (++)
3) Decrement(--)
Click to add text
When an operand is preceded by a minus sign, the unary
operator negates its value.
Ex: int x=5; int y= -x; then y store the value -5.
The increment increases the value of its operand by
operator Ex: 1.
int x=3,y;
printf(“x=%d",x++); x=3
y=x; y=4;
printf(“y=%d",++y);
y=5;
Operators in C
Unary Operators
• The decrement operator decreases the value of its operand by
1.
Ex: int x=3,y;
printf("x=%d",x--); x=3
y=x; y=2;
printf("y=%d",--y); y=1;
Conditional Operator or Ternary Operator
• The conditional operator (?:) is just like
an if .. else statement.
• The syntax of the conditional operator is
exp1 ? exp2 : exp3
Ex: a=10 b=5
large = ( a > b) ? a : b
Operators in C
Bitwise Operators
• Bitwise operators perform operations at bit
level. They are : 1) Bitwise AND(&)
2) Bitwise OR (|)
3) Bitwise XOR (^)
4) Bitwise Shift (<< and >>)
5) Bitwise NOT (~)
• The bitwise AND operator (&) is a small version of the boolean AND
(&&) as it performs operation on bits instead of bytes, chars,
integers, etc.
A B A&B Ex: x=2 y=3 x&y
0 0 0 0010
0 1 0
0011
1 0 0
x&y= 0010
1 1 1
Operators in C
• The bitwise OR operator (|) is a small version of the boolean OR (||) as
it performs operation on bits instead of bytes, chars, integers, etc.

A B A Ex:
|B x=2 y=3 x|y
0 0 0 0010
0 1 1
0011
1 0 1
1 1 1 x|y= 0011

• The bitwise XOR operator (^) performs operation on individual bits


of x=2 y=3
the
A
operands.
B A^B
Ex:
x^y 0 0 1 0
0 0 0 0011
0 1 1
1 0 1
1 1 0 x^y= 0001
Operators in C
• In bitwise Shift operations, the digits are moved, or shifted, to the left
or right.
• The CPU registers have a fixed number of available bits for storing
numerals, so when we perform shift operations; some bits will be
"shifted out" of the register at one end, while the same number of bits
are "shifted in" from the other end.

Ex:
In a left arithmetic shift,the right side end filled with 0‘s.
int x = 11000101;
Then x << 2 = 00010100
In a right arithmetic shift,the left side end filled with 0‘s.
int x = 11000101;
Then x >> 2 = 00110001
Operators in C

• The bitwise NOT (~), or complement, is a unary operation


that performs logical negation on each bit of the operand.

• Byperforming negation of each bit, it actually produces the


1‗s complement of the given binary value.
Ex: int
x=4,y;
y=(~x); Hear x is 0 1 0 0
y=11 ~x is 1 0 1 1
Operators in C
Assignment operators
• The assignment operator is responsible for assigning values to the variables.
• The equal sign (=) is the fundamental assignment operator.
• C supports other assignment operators that provide
shorthand
(Compact)ways to represent
OPERATOR SYNTAX
common variable assignments.
EQUIVALENT TO
/= variable /= expression variable = variable / expression
\= variable \= expression variable = variable \ expression
*= variable *= expression variable = variable * expression
+= variable += expression variable = variable + expression
-= variable -= expression variable = variable - expression
&= variable &= expression variable = variable & expression
^= variable ^= expression variable = variable ^ expression
<<= variable <<= amount variable = variable << amount
>>= variable >>= amount variable = variable >> amount
Operators in C
Comma operator
• The Comma operator in C takes two operands. It works by evaluating
the first and discarding its value, and then evaluates the second and
returns the value as the result of the expression.
• Comma separated operands when chained together are evaluated in
left-to-right sequence with the right-most value yielding the result of
the expression.
• Among all the operators, the comma operator has the lowest
precedence.
Ex: int a=2, b=3, x=0;
x = (++a, b+=a);
Now, the value of x =
6.
Operators in C
Sizeof Operator
• Sizeof operator used to calculate the sizes of data types.
• It can be applied to all data types.
• The operator returns the size of the variable, data type or expression
in bytes.
Ex:
 sizeof(char) returns 1 byte, that is the size of a character
type. data If we have,
int a = 10;
unsigned int result;
result = sizeof(a);
then result =
2 bytes.
References
Problem solving and Program design in C: Jery R Hanly Paerson Education.7th
Edison
Byron Gottfried, Schaum's Outline of Programming with C, McGraw-Hill
E. Balaguruswamy, Programming in ANSI C, Tata McGraw-Hill
R.G.Dromey, How to Solve it by Computer, Pearson Education

You might also like