0% found this document useful (0 votes)
14 views47 pages

Computer Generations and Systems Overview

Uploaded by

shaikhjaheed09
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)
14 views47 pages

Computer Generations and Systems Overview

Uploaded by

shaikhjaheed09
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

UNIT I

Introduction to Computers
Computer Systems
Computer Systems pervades all aspects of human life. A computer is an electronic device
capable of manipulating numbers and symbols under the control of a set of instructions known as
computer program.

They are different stages of computers (generation)

1. First Generation Computers

1. Vacuum tubes were used which produce more heat


2. Speed of computing was measured in milliseconds
3. Limited storage capacity
4. punched cards were used for I/O operation

2. Second – Generation Computers

1. Transistors and diodes were used.


2. Speed of computing was measured in microseconds
3. Consider about reduction of heat
4. Remarkable improvement in reliability
5. Storage capacity was increased
6. Magnetic tapes were used instead of punching cards.

3. Third Generation Computers

1. Integrated Circuits were used.


2. Speed is measured in nanoseconds
3. Occupied less space.
4. devices like visual display unit for I/O devices

4. Fourth – Generation Computers

1. Use of micro processor chip


2. Speed was measured in nano and picoseconds
3. Occupied less space
4. Commonly available as personal computers
5. Mini & micro Computers are developed from micro-processor

Page 1 of 64
5. Fifth – Generation Computers:

1. Use of super large-scale integration (SLSI) chip in computer (super computers)


2. Capable of performing millions of instructions per seconds (MIPS)
3. Processing speed is high.
4. Use of RICS (reduced instructions set computing) for processing
5. Super computers are expensive.

Computer System

Computer Hardware
It is a physical component which is visible.

Above diagram shows the logical layout of a modern computer system: this arrangement of
components is what is generally known as the von Neumann Architecture.

Consists of 5 Parts:
1. The control unit (CU), as the name suggests, has overall responsibility for the system.
2. The arithmetic-logic unit (ALU), as its name also suggests, performs arithmetic (addition,
subtraction, etc.) and logic (and, or, etc.) operations.
3. The registers (register file, scratchpad memory) form a small memory within the CPU.
This is the only storage to which the ALU has direct access. To manipulate any values from
memory they must be loaded into registers.
4. Memory (on modern computers a combination of ROM - Read Only Memory and RAM -
Random Access Memory) is where both program code and data reside while the program
is in execution. This is the stored program concept, often attributed to John von Neumann,

Page 2 of 64
although he was clear at least in written correspondence that Alan Turing should really be
credited. Memory (or Main Memory) is sometimes referred to as Primary Storage, as
opposed to Secondary Storage, which usually refers to disk drives, tape drives and the like.
The major deference between primary and secondary storage is access time.
5. Input and Output (usually jointly referred to as I/O) are how the system communicates
with the outside world _ outside, in this case, signifying outside the CPU-Memory
subsystem. On today's computers some I/O takes place within the computer system as a
whole (e.g. to hard disks, CD-ROMs) whereas some takes place between the computer
system and what the average user would consider the outside world: across a network, for
example. I/O devices are somewhat beyond the scope of this course.
Computer Software
Broadly divided into two categories:
1. System software
2. Application software

System Software
Manages the computer resources of a computer and perform required information
processing tasks.
Can be divided into 3 classes:
• Operating system
Provides user interface to access system resources, file and database management. …
Keeps the system in an efficient manner.
• System support
System utilities and OS services like disk format, system security etc
• System development
Compilers and debugging tools… Computer assisted software engineering (CASE) tools

Page 3 of 64
Application software
Can be divided into 2 classes:
• General Purpose Software
Purchased from a software developer and can be used for more than one application. Like
word processor, DBMS which can solve a variety of computing problems.
• Application specific
This can be used only for the task for which were designed and cannot be used for other
generalized tasks.
E.g. A general ledger system use by accountants
Material requirements planning system used by a manufacturing organization.
Relation between system and application software: a layered model

Each circle represents an interface point. Inner most layer is hardware and outermost is
user. User uses some sort of application software which in turn interacts with OS which can
directly interact with hardware.
• User can also directly interact with OS when necessary (as seen by a gap)
• System Programming, OS Internals, Device Drivers.
• If users cannot buy software that supports their needs a custom developed application
must be built.
• C is one of the computer languages used to develop such applications.
Computing Environments
1. Personal Computing Environment

• From a room full of components in the late 40’s, present day desktop/laptop.
• Are many time cheaper, consumes less power and faster.

Page 4 of 64
2. Time-sharing Environment

• All computing must be done by the central computer.


• It also must manage the shared data and printing.
• Terminals used may be dumb or have a very low processing power.

3. Client / Server Environment

• Splits the computing function between a central computer and users’ computers.
• Some of the computation responsibility can be moved from the central computer and
assigned to the user’s computers (PCs or workstations).
• In client/server environment users’ computers are known as clients.
• The central computer is called as Server.

4. Distributed Computing

Page 5 of 64
• Computing functions are into different servers and clients located throughout a
geographical area.
• eBay uses several computers to provide auction services where the environment provides
reliable, scalable and highly reliable network.

Computer Languages:

1. Machine languages (1940)


a. To write a program for a computer we must use a computer language.
b. In the early days of computing only machine language was used.
c. Each computer has its own machine language which are a sequence of 1’s and 0’s.
d. The only language understood by the computer internal hardware is machine language.

2. Symbolic Languages (1950)


a. Symbolic language uses symbols or mnemonics to represent various machine language
instructions.
b. A converter program was used to translate these mnemonics to machine language
instructions.
c. Since symbolic language had to be assembled into machine language it is known as
assembly language.

3. High level languages (1960)


a. Symbolic language improved the programmer efficiency still individual machine
instructions had to be individually coded.
b. To change focus from computer to the problem being solved led to the development of high
level languages.
c. HLL are portable to many different computers.
d. HLL are to be converted to machine language and this conversion is known as compilation.
e. First widely used HLL was FORTRAN created by IBM in 1957 for scientific and engineering
applications.
f. This was followed by COBOL for business applications.
g. C was created for system software and OS (UNIX) in BELL Labs in 1970 by Dennis Ritchie.

Complier:
This reads the entire source program and converts it to the object code. It provides error
not of one line, but errors of the entire program. It executes as a whole and it is fast.
Page 6 of 64
Interpreter:
It reads only one line of a source program at a time and converts it into an object code. In
case of errors/same will be indicated instantly. It executes line by line and it is slow.

Linker:
It is a function which links up the files that an present in the operating system, it also
links the files for the hardware and makes the system ready for executing.

Creating and running programs


• It is the job of the programmer to write and test the program.
• There are four steps in this process:
• Writing and editing, compiling, linking and executing.

e.g.
Text File myfile.c
Compiled file [Link]
Linked File [Link]

Some software vendors like Borland; Microsoft provides an integrated development (IDE)
environment to do all the four steps. In addition it also provides debugging tools to find and fix
errors in order to get a working program.
• Preprocessor reads the source code and prepares it for the translator.
• It scans for preprocessor commands which look for special code libraries.
• Make substitutions in the code and prepares the code as a translation unit.

Page 7 of 64
• Translator reads this translation unit and converts into machine language and writes into
an object module.
• This object module can be combined to other precompiled units to form the final program.
• C program is made of many functions
• Some written by the programmer.
• Other used from the readily available library programs.
• Linker combines all these functions into a final executable program.
• To execute the program we have to load it in the memory using a system program called
loader.
• Program “runs” under the control of OS.
#include <stdio.h>
int main(void)
{
printf(“Hello world!\n”);
return 0;
}

Very often C Programming language is called as Middle Level Language because


1. It behaves as High Level Language through Functions - supports modular programming for
increased efficiency for reusability.
2. It provides access to the low level memory through Pointers.
3. It also does support to low level programming using Assembly Level Language and is most
widely used for system programming.

Software Development Method


Today’s programming projects are large-scale and executed by a team of people. These are
built using a series of interrelated phases known as SDLC- Software development life cycle. One of
the models is water fall model

Page 8 of 64
1. Define the requirements of the system based on user’s requirement. (business analyst)
2. Analysis phase looks at the different alternatives. (system analyst)Input, output,
constraints
3. Design phase determines how the system will be built. (software architect/programmer)
4. Coding is the program writing phase includes testing of the code. (programmer/coder)
5. In System testing phase all programs are put together to make sure the system works as a
whole. (programmer/tester)
6. Maintenance makes sure that system works once it is put into production.(system support)
Test the program
Programs should be tested for its functionality by the programmer who developed it.
Two types of testing:

Black Box Testing


• Concept of testing the program without knowing how it works.
• Looking at the user’s requirement the test plans are developed.
• Normally done by a third party who is not a developer?

White Box Testing


• This assumes that the tester knows everything about the program.
• It is programmer’s responsibility.

There are three tools used to develop a program solution:


1. Algorithm:
An algorithm is a description of a procedure which terminates with a result. Algorithm is
a step-by-step method of solving a problem.
1. The approach or method that is used to solve a specific problem is known as an Algorithm.
2. A set of pseudo code or broken English steps written sequentially to solve a problem is
termed as on algorithm.
3. Any documentation that clearly holds the procedure of problem solving, including pictorial
representations are termed as algorithms.
Example:
Step 1: start
Step 2: ---
Step 3: ---
Step 4: stop

Page 9 of 64
Properties of an Algorithm:
a. Finiteness: - An algorithm terminates after a finite numbers of steps.
b. Definiteness: - Each step in algorithm is unambiguous. This means that the action
specified by the step cannot be interpreted (explain the meaning of) in multiple ways & can
be performed without any confusion.
c. Input: - An algorithm accepts zero or more inputs
d. Output: - An algorithm should produce at least one output.
e. Effectiveness: - It consists of basic instructions that are realizable. This means that the
instructions can be performed by using the given inputs in a finite amount of time.
2. Flowchart:
A flowchart is a graphical or pictorial representation of an algorithm.
Each step in the process is represented by a different symbol and contains a short
description of the process step. The flow chart symbols are linked together with arrows showing
the process flow direction. Some common flowcharting symbols are listed below.
Purpose Symbol

An oval flow chart shape indicating the


Terminator
start or end of the process

A rectangular flow chart shape indicating


Process
a normal process flow step.

A diamond flow chart shape indication a


Decision
branch in the process flow.

A small, labeled, circular flow chart shape


Connector used to indicate a jump in the process
flow

A parallelogram that indicates data input


Data
or output (I/O) for a process.

3. Pseudo code
• It is part English, part program logic and is a textual description.
• Purpose is to describe, in a precise algorithmic detail, what the program being designed is
supposed to do.
• Easy to translate to code, modify and transmit.

Program Development
It is a multistep process where the first five steps of SDLC is used for program
development.

Page 10 of 64
1. Understand the problem
2. Analyze the problem
3. Develop a solution
4. Write the program
5. Test the program.

Case Study
Problem is to Convert miles to kilometers.
1. Understand the problem
We are converting one system of measurement to another system.
2. Analysis
Input is in miles and output is in kilo meters.
The mathematical formula for conversion is 1 mile = 1.609 KMs
3. Develop a solution
We have to use an algorithm to get a solution.
We may use flow chart or pseudo code to design the solution.
Pseudo code
1. Get the distance in miles.
2. KMs = miles X 1.609
3. Output the distance in KMs.
4. Implementation
Write a program in C
5. Test the program
Verify proper working of the program by giving test input data.
E.g. An input of 10 miles should give an output of 16.09 KMs.

Page 11 of 64
Introduction to C Language
Development of “C”
“C” is a programming language developed at AT & T Bell Laboratories of USA in 1972. It
was developed Dennis Ritche in late 1970‟s. it began to replace the more familiar languages of
that time like PL/1, ALGOL etc.
1. “C” became popular because of its reliability, simple and easy to use
2. It was friendly capable and reliable
3. ALGOL 60 was developed and did not become popular because it was too general and
too abstract.
4. They developed “CPU” (Combined Programming Language)
5. Next as it could not come up to make ALGOL 60 better one they moved to “BCPL”
(Basic Combines Programming Language. Developed by martin Richard Cambridge
university)
6. At the same time a language called “B” written by ken Thompson at AT & T‟S. Bell
laboratories as a further simplification of BCPL.
7. The main focus was to create a structured language to develop UNIX OS.
8. American National Standardization Institute (ANSI) adopted the standard for C in
1989 which was called ANSI C89 and later in 1999 as ANSI C99.
9. “C” s compactness and coherence is mainly due to it‟s one man language. Ex-LISP,
AASCA.

Year Lang Developed by Remarks

1960 ALGOL International Committe too general, too abstract

1963 CPL camebridge university Hard to Learn & implementation

1967 BCPL Camebridge university could deal only special problem

1970 B AT&T could deal only special problem

1972 C AT & T Lost Generality of BCPL, B restored

Note : C is a middle level language because it was due to have both a relatively good programming
efficiency and relativity good machine efficiency.

Page 12 of 64
Features of “C” Language:
1. It is robust language because of rich set of binary in – function
2. It is efficient and fast because of its variant data-types and powerful operation.
3. It is highly Portable i.e., programs written in one computer can be run on another
4. It is well suited for structure program, thus allows the user to think about the problem
in the terms of functional blocks.
5. Debugging, testing and maintenance is easy
6. ability to extend itself, we can continuously add our own functions to the program.

Structure of ‘C’ Program


• A typical C program consists of functions.
• Function is a block of code, has name and can be called by the functions’ name.
• The execution of program starts with a “main” function.
• There will be only one “main” function.

#include <stdio.h> -> Preprocessor directive


int main (void)
{
printf (“Hello world!\n”); -> Displays “Hello world”
return 0;
}
Preprocessor Directives
• All Preprocessor Commands come at the beginning of the program.
• It starts with # and a key word include.
• A Library file is included in the program for a specific purpose.
Page 13 of 64
• These library files called header file will have functions.
• These handle input/output operations, mathematical operations, string operations etc.
• Pointed brackets indicates that the library file to be included in the program.

Function
• Every function should accept parameters and return value.
• Main is also a function

Comments
• Provides readability for the program for the program developer and also to the reader.
• Compiler ignores the comments.
• Single line comment “//”
• Block comments are enclosed between /* and */

Character Set
1. Character is any value that can be represented in computer’s alphabet known as character
set.
2. 7 bit ASCII (American Standard Code for Information Interchange) represents 128
characters.
3. Displayable, non- displayable, and control characters.
The characters in C are grouped into the following four categories:
1. Letters A..Z and a..z
2. Digits 0..9
3. Special Characters , . # $ % < > *…
4. White Spaces \n, \t, blank space

C Tokens
1. In a C program the smallest individual units are called tokens.
2. There are six types of tokens and C language is written with these tokens and the syntax
of the language.
• Keywords float, int, while
• Identifiers main, amount, name …
• Constants 100, 15.5 …
• Strings “ABC”, “year”
• Operators +, -, *…
• Special symbols [], {}…
Page 14 of 64
Key Words
• Every C word is classified as either a keyword or an identifier.
• All key words have meanings and they serve as the basic building block of the language.
• ANSI C has 32 keywords like int, long, switch, return …
• All keywords should be written in small letters.
auto double int struct
break else long switch
case enum register tyedef
char extern return union
const float short unsigned
continue For sigened void
default goto sizeof volatile
do if static while

Identifier
• Identifiers are user defined names consisting of letters and digits which are used to refer to
names of variables, functions and arrays.
• Data item is stored in the computer at a unique address
• Identifiers is used symbolically represent data locations instead of object’s address in
memory.

Rules for identifiers


• Valid name symbols are alphabets A to Z, a to z, 0 to 9 and underscore.
• First character cannot be a digit.
• A name start with underscore is used for C libraries and OS programs.
• Cannot use keywords or reserved words of C.
• Identifier name should be descriptive, but short and not longer than 63 characters.

Valid Names Invalid names


a $sum
student_name 2names
_aSsyetenmName sum-salary
_Bool stdnt Nmbr
INT_MIN int

Page 15 of 64
Declaration of Variable:
It tells the complier what the variable name is used, what type of date is held by the
variable.
syntax: datatype v1,v2,….vn;
Eg : int a, b;
float sum;
double ratio;

Representation of Constant
const int r = 10;

Assigning values to variables


Eg : int x,y;
x= 10;
y=5;

Typedef :
Defined as type definition by using typedef we can create new data type.
typedef type data _ame;
Type ---- datatype
Dataname---- Name of that type.

Data Types
• A type defines set of value and a set of operations that can be applied on those values.
• ANSI C supports three classes of data types:
1. Primary (or fundamental) data types
2. Derived data types
3. User-defined data types

Fundamental types
1. Integer int
2. Character char
3. Floating point float
4. Double-precision point double
5. Void void

Page 16 of 64
1. Integer
• Integer is a number without fractional part.
• int, short int, long int in signed and unsigned form.
2. Floating point
• Floating point is a number with integer part and fractional part.
• When accuracy is not provided by floating point number is not sufficient, double-
precision point is used.
• Floating Point numbers are stored with 6 digits of precision. Those are defined with
keyword float. When the accuracy is not sufficient then the datatype double can be
used. Double gives a precession of 14 digits these known as double precession
numbers. Still for a better process we can use long double which uses 80 bits.
3. Character
• Signed char and unsigned char
4. Void type
• Void type has no values and no operations.
Modifiers
Except for type void, the basic data types may have various modifiers preceding them. You
use a modifier to alter the meaning of the base type to fit various situations more precisely. The
list of modifiers is shown here:
1. signed
2. unsigned
3. long
4. short
Size and range of data types on a 16-bit machine
Type Size(bits) Range
char or signed char 8 -128 to 127
unsigned char 8 0 to 255
int or signed int 16 -32768 to 32767
unsigned int 16 0 to 65535
signed short int 8 -128 to 127
unsigned int 8 0 to 255
signed long int 32 -2147483648 to 2147483647
unsigned long int 32 0 to 4294967295
float 32 3.4E-38 to 3.4E+38
double 64 3.4E -4932 to 1.1E +4932

Page 17 of 64
Variables
• Variables are named memory locations that have a type.
• The type determines the values the variables may contain and the operations that may be
used with its values.
• Each variable is
o Declared to name an object.
o Defined to create the object in memory.
o variable type can be of any type but cannot be void
• E.g. char grade, int number, float average
What data type will be used for the following?
• Student’s height in feet
• Student’s weight in KGs
• Student’s grade
• Student’s fees for one year in Rs.
• Student’s fees for 4 years in Rs.
• Distance between Earth and Moon in KM?
Why variables should have a certain data types?
• A named memory location is called variable. Depending on the data to be represented
it may be any of the primitive types.
• When a program is compiled, the compiler need to know how much memory should be
allotted to the variable.
Eg. char : 1 byte, int : 2 bytes, long : 4 bytes, float : 8 bytes
Variable initialization
We can initialize a variable at the same time that we declare it by including an initializer.
type variable_name = value;
e.g. int count = 0; char ch = 'a'; int first = 0; float balance = 123.23;
If variables are not initialized it will contain garbage/undefined value.
Exception: Uninitialized global and static local variables are automatically set to zero.
Constants
1. Constants are data values that cannot be changed during the execution of a program.
2. Like variables constants have a type.
Numeric Constants
• Integer Constants
45, +78, -321
Embedded spaces, commas and non-digit characters not allowed.

Page 18 of 64
• Real Constants (Floating point)
215.65, 0.0083, -0.75, 2.1565e2 (exponential or scientific notation)
Character Constants
‘5’, ‘X’.
Will have values as per ASCII code
String Constants
“Hello”, “1947”
Backslash Character Constants
‘\n’, ‘\t’, ‘\”’, ‘\\’, ‘\0’
Coding constants
o Literal constant: unnamed constant used to specify data.
o If we know that the data cannot be changed we code data value itself in the
statement.
e.g. a = b + 5;
Defined constants
o Preprocessor command #define
o Placed at the beginning of the program
o Constants are written in capital letters.
Memory constants
o Use a C type qualifier, const to indicate that the data cannot be changed.
o Const type identifier = value;
o const float cPi = 3.14159;
Hexadecimal (base 16) and Octal (base 8) Constants
1. The octal number system uses the digits 0 through 7.
2. The hexadecimal number system uses the digits 0 through 9 and A thru F.
3. A hexadecimal constant must consist of a 0x followed by the constant in hexadecimal form.
4. An octal constant begins with a 0.
e.g.
int hex = 0x80; /* 128 in decimal */
int oct = 012; /* 10 in decimal */

Input / Output
o Input / Output are facilitated in C based on streams.
o A stream is a source or destination for data.
o Associated with a physical device such as terminal or files stored in auxiliary memory.

Page 19 of 64
Streams
o Text
o Binary
✓ Text is a sequence of characters divided into lines with each line terminated by a newline
(\n).
✓ Terminal is associated with a text stream where as a file can be associated with a text or
binary stream.
✓ A binary stream consists of a sequence of data values such as integer using their memory
representation.

1. A terminal keyboard and monitor can be associated only with a text stream.
2. A keyboard is a source for a text stream.
3. A monitor is a destination for a text stream
Formatting Input / Output
We can receive text streams from a terminal (keyboard) and send text streams to a
terminal (monitor).
Provides two formatting functions:
o printf for output formatting
o scanf for input formatting

printf
o Convert data into text streams.
o Uses a format control string containing conversion specifications.
o Each data to be formatted will have an appropriate control string.
E.g. printf (“%d “, quantity)
On the monitor -> 234
Conversion Specification
% Flag Minimum Width Precision Size Code

Page 20 of 64
To insert data into the stream, we use a conversion specification. Consists of a start token
(%), a conversion code and four optional parameters. 30 different types of conversion codes
character (c), integer (d) and floating point (f).

Flag modifier is used for four print modifications:


Justification (left or right), padding (0 or space), sign (+,-) and numeric conversion.
Width modifier is used to specify minimum number of positions in the output.
Precision for floating-point number to be printed with certain decimal places.

Trace the program


printf (“The number %d is my favorite number.”, 23); -> The number 23 is my favorite number
printf (“The number is%6d”, 23); -> The number is 23
printf (“The tax is %6.2f this year.”, 233.12); -> The tax is 233.12 this year.
printf (“The tax is %8.2f this year.”, 233.12); -> The tax is 233.12 this year.
printf (“The tax is %08.2f this year.”, 233.12); -> The tax is 00233.12 this year.

Input formatting: “scanf”


o scanf is the reverse of “printf”.
o scanf takes a text stream from the keyboard, extracts and formats the data from the stream
based on format string and stores the data in specified program variables.
o The destination data items should be address of the variables.
o Leading white spaces are discarded.
o Any non-conversion specification characters in the format string must be exactly matched
by the next characters in the input stream.
e.g scanf (“%f”, &value); Input: 123.4 value=123.4
scanf (“ %c%f”, &code, &price); Input: B 123.4 code = B, price=123.4

Conversion Specification
% Flag Minimum Width Size Code

o As in printf conversion specification, scanf contains start token (%) and conversion code.
o There is no precision in an input conversion.
o There is only one flag (*), called assignment suppression- filed to be read and discarded.
e.g. scanf (“%d %*c %f”, &x, &y);
o For every conversion specification there must be a matching variable in the address list.

Page 21 of 64
o The address operator is ampersand (&).
o When the Width specification is included, scanf reads until the maximum number of
characters has been processed or scanf finds a whitespace.

End of File
o Scanf stops processing if there are no more inputs indicated by EOF.
<ctrl z> in windows.

General Structure of a C program:


/* Documentation section
*/ /* Link section */
/* Definition section */
/* Global declaration section
*/ main()
{
Declaration part
Executable part (statements)
}
/* Sub-program section */

The documentation section is used for displaying any information about the program like
the purpose of the program, name of the author, date and time written etc, and this
section should be enclosed within comment lines. The statements in the documentation
section are ignored by the compiler.

The link section consists of the inclusion of header files.

The definition section consists of macro definitions, defining constants etc,.

Anything declared in the global declaration section is accessible throughout the
program, i.e. accessible to all the functions in the program.

main() function is mandatory for any program and it includes two parts, the declaration
part and the executable part.

The last section, i.e. sub-program section is optional and used when we require including
user defined functions in the program.

Page 22 of 64
1. Write a C program for variable declaration?

main( )
{
float x,p; x=10.1;
p=5.2;

printf (“x = %f”, x); printf (“p = %f”, p);


}

Output:
x= 10.10000
p = 5.2

2. Write a C program to implement typedef ?

# include < stdio.h>


main ( )
{
typedef int amt ;
amt Rupees = 20;
printf (“ Rupees %d“, Rupees);
}
Output:
Rupees 20.

Expression
• An expression is a sequence of operands and operators that reduces to a single value.
• Expressions can be simple or complex.
• An operator is a syntactical token that requires an action be taken.
• An operand is a data item on which an operation is performed.
Eg. 2 + 5 * 7 -> 37. Operands are 2, 5 and 7. Operators are + and *

Operators
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulation on data stored in variables. The variables that are operated as operands. C operator
can be classified into 8 types and 3 categories (Unary, Binary, and Ternary)
1. Arithmetic Operators : + - * / %
2. Relational Operators: < > <= >= == !=
3. Logical Operators:! && ||

Page 23 of 64
4. Increment & Decrement Operator : ++ --
5. Assignment Operators : =
6. Bitwise Operator:! & | ~ ^ << >>
7. Special Operator : sizeof( ) ,(comma)
8. Conditional Operators: ! :

Types of operators
1. Arithmetic Operators +, -, *, / and %
2+2 = 4, 5-3=2, 2*5=10, 10/2=5, 11%3=2
3. Write a C program to illustrate the use of all Arithmetic operators’?
main ( )
{
int sum, prod , sub, div, mod, a, b ;
printf(“Enter values of a, b :”) ;
scanf(“ %d %d”, & a, & b) ;
sum = a+b ;
printf(“sum = %d”, sum);
sub = a-b;
printf(“sub = %d”, sub);
prod = a * b ;
printf(“prod = %d”, a* b);
div = a/b;
printf(“ Div = %d”, div);
mod = a % b ;
printf(“ mod = %d”,a % b);
}
Output:
Enter values of a, b: 20 10
Sum=30 Sub=10 Mul=200 Div=2 mod=0
2. Relational Operators
Operator Example Value
> 5> 4 1
< 10<9 0
<= 10 <= 10 1
== 2==3 0
>= 11>=5 1
Page 24 of 64
!= 3!=3 0
4. WAP to use various relational operators and display their return values?
main ( )
{
printf(“ in condition : Return Values In”);
printf(“ In 10! = 10 : %5d”, 10! = 10);
printf(“ In 10 = 10 : %5d” , 10 == 10);
printf(“ In 10>=10 : %5d”, 10>=10);
printf(“ In 10<+100 : %5d”, 10<100);
printf(“ In 10! = 9 : %5d”, 10!=9);
}
Output:

Condition : Return values

10! = 10 : 0
10 = = 10 : 1
10> = 10 : 1
10! = 9 : 1

3. Logical Operators &&, ||, !


A B AND LOGIC OR LOGIC EX-OR LOGIC NOT LOGIC (A)
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0
e.g
Operator Example Value
&& 5>3 && 5<10 1
|| 8>5 || 8<2 1
! !(8==8) 0
5. WAP to illustrate the use of Logical Operators

void main ( )
{
clrscr ( );
printf(“In 5>3 && 5<10 : %3d”, 5>3&&5<10);

Page 25 of 64
printf(“ In 8<5 || 5= =5 :% 3d”, 8<5 || 5= =5);
printf(“In !(8 = =8) : %3d”, !(8= =8) ;
}
Output:
5>3&&5<10: 1
8<5|5= =5:1
!(8 = =8):0

4. Increment and Decrement Operators ++, --


a= a+1; which is same as a++; a--; is same as a = a - 1;
6. WAP to show the effect of increment and decrement operators?
main ( )
{
int x = 10,y = 20, z, a ;
z= x * y ++;
a=x*y;
printf(“ %d % d\n”, z,a);
z = x * ++y;
a = x * y;
printf(“ %d %d\n”, z, a);
printf(“ ++ x = %d, x++=%d”, ++x, x++);
}
Output:
200 210
220 220
12 10

5. Assignment Operator =
x=2

6. Bitwise Operator &, |, ^, >>, << and ~

Operator Example Before Execution After Execution


>> x>>=2 0000000000001000 0000000000000010
<< x<<=3 0000000000000010 0000000000010000
~ ~x 0000000000000010 1111111111111101

Page 26 of 64
x=9, y=5 0000000000001001
0000000000000101
& x&y 0000000000000001
| x|y 0000000000001101
^ x^y 0000000000001100

7. Comma Operator
The Comma Operator is used to separate two or more expressions.
a=2, b=4, c=a+b;
sizeof operator : is used to find the on. of bytes occupied by a variable / data type in
computer memory

Eg. int m,x[50];

sizeof(m) return 2

sizeof(x) returns 100 (50 * 2)

7. WAP to illustrate the use of size of operator?


main ( )
{
int x = 2;
float y = 2;
printf (“ in size of ( x ) is %d bytes “, sizeof ( x ));
printf (“ in size of ( y ) is %d bytes “, sizeof ( y ));
printf (“ in Address of x = % u and y = % u “, & x, & y);
}
Output:
sizeof ( x ) = 2
sizeof ( y ) = 4
Address of x = 4066 and y = 25096

8. Conditional Operator
expr1? exp2: exp3; if expr1 is true exp2 is executed, else exp3 is executed.
x = 10; y = x>9 ? 100 : 200; y = 100.
x= 8; y = 200

Page 27 of 64
8. WAP to print whether a given number is even or odd?
main()
{
int a, b
printf(“ Enter a number “); scanf(“
%d”, & a);
b = a%2;
((b = =o)? printf(“Even”): printf(“odd”);
}
Output:
Enter a number 5
odd

9. WAP to print logic 1 if input character is capital otherwise 0?


main ( )
{
char x ; int y;
printf((“ \n enter a character” );
scanf(“ % C “, & x);
y = (x>=65 && x <=90? 1:0); printf(“ y : %d”, y);

}
Output:
Enter a character D
y:1

A simple expression
• A simple expression contains only one operator.
e.g. 5 + 2 = 7, -a is also an expression

A complex expression
• A complex expression contains more than one operator.
• To evaluate a complex expression it is reduced to a series of simple expression.
e.g. 2 + 5 * 7 evaluated to 2 + 35 giving 37.

Page 28 of 64
Six categories of Expression
1. Primary Expression
• Consists of only one operand with no operator.
Names
• A name is any identifier for a variable, function or any other object in the language.
e.g. a b12 price
Literal Constants
• Constant is a piece of data where value cannot be changed during the execution of the
program.
e.g. 5, 123.45, ‘A’, “Welcome”
Parenthetical Expressions
• Any value enclosed in parenthesis must be reduced to a single value and is therefore a
primary expression.
e.g. (2 * 3 + 4)

2. Postfix Expressions
• Postfix Increment / Decrement
• x = a++; Value of expression is a, but value of a is incremented by 1 after
assignment.
• The operand in a postfix expression must be a variable
Trace the program:
int a = 4;
printf (“Value of a: %d\n”, a); a=4
printf (“Value of a: %d\n”, a++); a=4
printf (“Value of a: %d\n”, a); a=5

3. Prefix Expressions
• x = ++a; Value of expression is a, but value of a is incremented by 1 before assignment.
Trace the program
int a = 4;
printf (“Value of a: %d\n”, a); a=4
printf (“Value of a: %d\n”, ++a); a=5
printf (“Value of a: %d\n”, a); a=5

Page 29 of 64
4. Unary Expressions
• sizeof
• The size of operator tells us the size in bytes of a type or a primary expression.
• e.g size(int), size(x)
• Unary Plus/Minus
• One operand and operator, the operand comes after the operator.
e.g. ++a; -b; -c; +d;
• Cast Operator
• The cast operator converts one expression type to another.
• To covert an integer to real number, float(x).

5. Binary Expressions
Binary expressions are formed by an operand - operator- operand combination.
a + b; c*d;
• Multiply operator
• Divide operator
• Modulus operator

Assignment Expressions
• Evaluates the operand on the right side of the operator (=) and places its value in the
variable on the left of the assignment operator.
• It has a value and a side effect.
Value:
Value of the expression on the right side of the assignment operator.
Side effect:
Places the expression value in the variables on the left side of the assignment
operator.
Two types of assignment
Simple assignment
• It is like that found in algebraic expressions. E.g. a = 5; b = x+1;
• For the side effect to take place, left variable should be able to receive it.
Compound Statement
• It is a short hand notation for a simple assignment.
• Five compound assignment operators: *=, /=, %=, +=, -=

Page 30 of 64
e.g. x*=y+3; Calculate for x=10, y=5
Compound statement is evaluated as x = x*(y+3);

6. Ternary Expressions
Consists of a ternary operator pair “?:”
expr1? exp2: exp3;
if expr1 is true exp2 is executed, else exp3 is executed.
x = 10;
y = x>9 ? 100 : 200; y = 100. x = 8, y = 200.
Equivalent IF
x = 10;
if(x>9) y = 100;
else y = 200;

Precedence and Associativity


• If an expression contains many operators, the order of evaluation is determined by a set of
priorities known as precedence.
• Higher precedence expressions are evaluated first.
• In the case of same precedence associativity determines the order of evaluation.
• Precedence is applied before associativity.

Precedence
• Precedence is well known in Algebra. Multiplication and division are performed before
addition and subtraction. E.g BODMAS
• C has precedence levels as shown below
• Parenthetical expression has the highest level of 16,
• “=” -> priority level of 2
• “+” and “-“ -> priority level of 12
• *, / and % 1 -> priority level of 12

Page 31 of 64
2+3* 4 is evaluated as 2 + (3*4) -> 2 + 12 = 14
-b++. If b=5, the value is -5, side effect value of b= 6

Associativity
• If two operators with the same precedence occur then associativity of the operator is
applied.
• Associativity is the parsing direction used to evaluate an expression.
• It can be either left to right or right to left.
• When two operators with the same precedence occur left operator is evaluated first.
E.g. 3 * 4 / 6 -> Multiplication are evaluated before the division.

Complete listing of the C operators

Symbol Description Associativity Precedence

() Function call and sub expression


[] Array subscript
-> Structure pointer
left to right Highest 15
. Structure member
++ Prefix increment
-- Prefix decrement

! Logical negation
~ 1's complement
- Unary negation
+ Unary plus
right to left 14
(type) Type cast
* Pointer dereference
& Address of
sizeof Size of

* Multiplication
/ Division left to right 13
% Modulus (integer remainder)

+ Addition
left to right 12
- Subtraction

Page 32 of 64
<< Bitwise left shift
left to right 11
>> Bitwise right shift

< Less than


<= Less than or equal to
left to right 10
> Greater than
>= Greater than or equal to

== Equal test
left to right 9
!= Not equal test

& Bitwise AND left to right 8

^ Bitwise exclusive OR (XOR) left to right 7

| Bitwise inclusive OR left to right 6

&& Logical AND left to right 5

|| Logical inclusive OR left to right 4

?: Conditional test right to left 3

= Assignment
+= Compound add
-= Compound subtract
*= Compound multiply
/= Compound divide
%= Compound modulus right to left 2
<<= Compound bitwise left shift
>>= Compound bitwise right shift
&= Compound bitwise AND
^= Compound bitwise exclusive OR
| Compound bitwise inclusive OR

, Sequence point (list separator)


++ Postfix increment left to right Lowest 1
-- Postfix decrement

Side effects
• A side effect is an action that results from the evaluation of an expression.

Page 33 of 64
• The expression on the right of the assignment operation is evaluated as the value and is
placed in the left variable.
x=4
The right side of the assignment operator, the primary expression has a value of 4.
The whole expression has a value of 4.
As a side effect x receives a value of 4.

Type conversion
• When an expression involves two different data types like one is an integer and other is a
floating point number, one of the types should be converted.

Implicit conversion
When the types of the two operands in a binary expression are different, C automatically
converts one type to another

Conversion in Simple Assignment Expressions


In a simple assignment C will either promote or demote the right expression to make the
same rank as the left expression.

Promotion
There is no problem with promotion as the rank of right is elevated to the left.
e.g.
char c = ‘A’;
int i = 1234;
double d = 3456.1234
i = c; -> value of i is 65
d = i; -> value of d is 1234.0

Demotion
If the size of the variable at the left side can accommodate the value of the expression there
is no problem. Otherwise the results will be unpredictable.
e.g.
short s = 78;
int j = 12345;
s = j; -> value of s is unpredictable

Page 34 of 64
Explicit Type Conversion
Instead of compiler converts data, programmer can convert the data using cast operator.
E.g. to convert an integer a to float we can use, (float) a

What is the result of the following?


int a = 3;
(a / 10) -> 0.0
To get the result as float, (float) a / 10 -> 0.3

Statements
A statement causes an action to be performed by the program. It translates directly into
one or more executable computer instructions. A statement is terminated by a semicolon.

Statement Type
There are 11 types. We will examine 4 here: Null, Expression, Return, and Compound

Null Statement
• The Null Statement is just a semicolon;

Expression statement
• An expression is turned into a statement by placing a semicolon after it.
• When C sees the semicolon it completes any pending side effects and discards the
expression value before continuing with the next statement.
• An expression without side effects does not cause any action.
e.g. a = 2 ; a = b = 3; b; 3; ;

Return Statement
• Return Statement terminates a function.
• It can return a value to the calling function.
• In the case of “main” it returns the value to the operating system.
• A value of 0 indicates that the program executed successfully.

Compound Statements
Compound Statement is a unit of code consisting of zero or more statements.
This is also known as block, allows a group of statements to become one single entity.

Page 35 of 64
Enclosed between { and }
Logical Data and Operators
• A piece of data is called logical if it conveys the idea of true or false.
• Traditionally, C has no logical data type.
• C Programmers used other data type such as int.
• If data value is zero it is considered as false, otherwise true
Logical Operators
• C has three Operators for combining logical values and creating new values: not, and & or
• The following truth table gives the logical relationship:

C uses short-circuit methods for evaluating logical expressions involving and & or

• That is, in the case of and if first expression is false second expression is not evaluated.
• Similarly, in the case of or if the first expression is true second expression is not evaluated.

Comparative Operator
C provides six comparative operators which are divided into two categories:
• Relational
• Equality

Each operator is a complement of another operator in the group.

Page 36 of 64
Unformatted I/O functions:

1. getchar():Used to read a character


[Link]():Used to display a character
[Link]():Used to read a string
[Link]():Used to display a string which is passed as argument to the function

Formatted I/O functions:


• printf() and scanf() are examples of formatted I/O functions.
• printf() is an example of formatted output function and scanf() is an example of
formatted input function.

scanf ( ) function is used to read values using key board. It is used for runtime assignment of
variables.
The general form of scanf( ) is
scanf(“format String “ , list_of_addresses_of_Variables );
The format string contains
- Conversion specifications that begin with % sign
Eg: Scan f(“ %d %f %c”, &a &b, &c)
„&‟ is called the “address” operator. In scanf( ) the „&‟ operator indicates the memory location of
the variable. So that the Value read would be placed at that location.

printf( ): function is used to Print / display values of variables using monitor:


The general form of printf( ) is
printf(“control String “ , list_of_ Variables );
- Characters that are simply printed as they are
- Conversion specifications that begin with a % sign
- Escape sequences that begin with a „\‟ sign.

Page 37 of 64
Eg: main ( )
{ float per;
printf(“Enter values for avg & per”);
scanf(“ %d %f”, & avg, & per);
printf( “ Average = %d \n Percentage = %f”, avg. per);
}
Output:
Enter values for avg & per 346 69.2
Average = 346
Percentage = 69.200000
Escape Sequence Use ASC|| Value
\n New line 10
\b Backspace 8
\f Form feed 12
\‟ Single Quote 39
\\ Back slash 92
\o Null 0
\t Horizontal tab 9
\r Carriage return 13
\a Alert 7
|? Question marks 63
\“ Double Quote 34
\v Vertical tab 11

Page 38 of 64
CONTROL STRUCTURES / STATEMENTS
✓ A program is nothing but the execution of sequence of one or more instructions.
✓ Quite often, it is desirable to alter the sequence of the statements in the program
depending upon certain circumstances.
o (i.e., we have a number of situations where we may have to change the order of
execution of statements based on certain conditions)
(or)
✓ Repeat a group of statements until certain specified conditions are met.
✓ This involves a kind of decision making to see whether a particular condition has occurred
or not and direct the computer to execute certain statements accordingly.
✓ Based on application, it is necessary / essential
o To alter the flow of a program
o Test the logical conditions
o Control the flow of execution as per the selection these conditions can be placed in
the program using decision-making statements.

Conditional Statements:
Conditional statements control the sequence of statement execution, depending on the
value of an integer expression.

1 If Statement
a) Simple If statement
b) If-else statement
c) Nested if statement
d) Else –if ladder
2. Switch Statement

Two-Way Selection
• This is a basic decision statement that can be determined as true or false.
• Two-Way Selection in ‘C’ is achieved through if .. else

Page 39 of 64
• The expression can be any C expression and will be evaluated to be true or false.
• If value is true statement1 is evaluated, otherwise ststement2 is evaluated.

Both true and false statement can be


• Single statement
• A compound statement
• Another if .. else statement.
• If else condition is not required it can be omitted.
10. Write a program to print the given number is even or odd.
# include<stdio.h>
void main( )
{
int n;
printf(“Enter a number:”);
scanf(“%d”, &n);
if( (n%2)==0 )
printf(“\n The given number is EVEN ”);
else
printf(“\n The given number is ODD ”);
}
Output:
Run 1:
Enter a number: 24
The given number is EVEN
Run 2: /* that means one more time we run the program */
Enter a number: 17
The given number is ODD

Page 40 of 64
Nested if statements
When an if .. else statement is included within another if .. else statement it is known as
Nested if statement.

[Link] to select and print the largest of the three float numbers using nested “if-else”
statements.
# include<stdio.h>
void main( )
{
float a,b,c;
printf(“Enter Three Values:”);
scanf(“%f%f%f ”, &a, &b, &c);
printf(“\n Largest Value is:”) ;
if(a>b)
{
if(a>c)
printf(“ %f ”, a);
else
printf(“ %f ”, c);
}
else
{
if (b>c)
printf(“ %f ”, b);
else
printf(“ %f ”, c);

Page 41 of 64
}

}
Output:
Run 1: Enter three values: 9.12 5.34 3.87
Largest Value is: 9.12
Run 2: Enter three values: 45.22 35.44 23.76
Largest Value is: 45.22

Multiway Selection
• Multiway selection chooses among several alternatives.
• C has two ways of implementing multiway selection.

Switch Statement

• Expression must be reduced to an integral expression.


• The selection alternatives, known as case labels must be C integral types.
• For every possible of switch expression a separate case label is used.
• A default label is used when none of the case values match with the switch expression.

Trace the program


int printFlag ;
switch(printFlag)
{
case 1: printf (“This is case 1\n”);
case 2: printf (“This is case 2\n”);
default: printf (“This is default\n”);

Page 42 of 64
}
What is the output when
printFlag =1
printFlag =2
printFlag =3

When program enters through a switch it executes the code of all of the cases until the end.
But, if we want to execute only one case statement we must use break statement, which causes the
program to jump out of the switch statement.

The above code can be modified as:


switch (printFlag)
{
case 1: printf (“This is case 1\n”);
break;
case 2: printf (“This is case 2\n”);
break;
default: printf (“This is default\n”);
break;
}
12. Write a program to provide multiple functions such as 1. Addition 2. Subtraction
[Link] 4. Division 5. Remainder 6. Larger out of two 7. Exit using “switch” statement.
# include<stdio.h>
void main( )
{
int a, b, c, ch;
printf(“\t = = = = = = = = = = = = = =”);
printf (“n\t MENU”);
printf(“\n\t= = = = = = = = = = =”);
printf(“\n \t [1] ADDITION” );
printf(“\n \t [2] SUBTRACTION” );
printf(“\n \t [3] MULTIPLICATION” );
printf(“\n \t [4] DIVISION” );
printf(“\n \t [5] REMAINDER” );
printf(“\n \t [6] LARGER OUT OF TWO” );

Page 43 of 64
printf(“\n \t [7] EXIT” );
printf(“\n \t = = = = = = = = = =”);
printf(“ \n\n\t ENTER YOUR CHOICE:”);
scanf(“%d”, &ch);
if(ch < = 6 && ch >=1)
{
printf(“ENTER TWO NUMBERS:”);
scanf(“%d %d”, &a, &b);
}
switch(ch)
{
case 1: c = a+b ;
printf(“ \n Addition: %d”, c);
break;
case 2: c=a-b;
printf(“\n Subtraction: %d”, c);
break;
case 3: c = a* b ;
printf(“\n Multiplication: %d”, c);
break;
case 4: c = a / b;
printf(“\n Division: %d”, c);
break;
case 5: c = a % b;
printf(“ \n Remainder: %d”, c);
break;
case 6: if (a > b)
printf(“\n \t %d is larger than %d”, a, b);
else if (b > a)
printf(“ \n \t %d is larger than %d ”, b, a);
else
printf(“\n \t %d and %d are same”, a, b);
break;
case 7: printf( “ \ n Terminated by choice”);
exit( );
break;
Page 44 of 64
default: printf(“ \ n invalid choice”);
}

}
Output:
=========
MENU
=========
[1] ADDITION
[2] SUBTRACTION
[3] MULTIPLICATION
[4] DIVISION
[5] REMAINDER
[6] LARGER OUT OF TWO
[7] EXIT
===============
Enter your choice: 6
Enter two numbers: 8 9
9 is larger than 8
13. Write a program to display the traffic control signal lights based on the following.
• If user entered character is R or r then print RED Light Please STOP.
• If user entered character is Y or y then print YELLOW Light Please Check and Go.
• If user entered character is G or g then print GREEN Light Please GO.
• If user entered some other character then print THERE IS NO SIGNAL POINT.
# include<stdio.h>
void main( )
{
char L;
printf(“ \n Enter your Choice( R,r,G,g,Y,y):”);
scanf(“%c”, &L);
switch(L)
{
case ‘R’:
case ‘r’: printf(“RED Light Please STOP”); break;

Page 45 of 64
case ‘Y’:
case ‘y’: printf(“YELLOW Light Please Check and Go”); break;
case ‘G’:
case ‘g’: printf(“GREEN Light Please GO”); break;
default: printf(“THERE IS NO SIGNAL POINT ”);
}

}
Output:
Run-1: Enter your Choice(R,r,G,g,Y,y): g
GREEN Light Please GO
Run-2: Enter your Choice(R,r,G,g,Y,y): G
GREEN Light Please GO

Page 46 of 64
Page 47 of 64

You might also like