Basic Computer Engineering Unit II as per RGPV Syllabus

1,823 views 37 slides Mar 24, 2015
Slide 1
Slide 1 of 37
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37

About This Presentation

Algorithm, Flowchart, Categories of Programming Languages, OOPs vs POP, concepts of OOPs, Inheritance, C++ Programming, How to write C++ program as a beginner, Array, Structure, etc


Slide Content

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 1

1. Definition
A formula or set of steps for solving a particular problem. To be an algorithm, a set of rules
must be unambiguous and have a clear stopping point. Algorithms can be expressed in
any language, from natural languages like English or French to programming
languages like FORTRAN.
We use algorithms every day. For example, a recipe for baking a cake is an algorithm.
Most programs, with the exception of some artificial intelligence applications, consist of
algorithms. Inventing elegant algorithms -- algorithms that are simple and require the fewest
steps possible -- is one of the principal challenges in programming.


2. Introduction
Algorithmic complexity is concerned about how fast or slow particular algorithm performs. We
define complexity as a numerical function T(n) - time versus the input size n. We want to define
time taken by an algorithm without depending on the implementation details. But you agree
that T(n) does depend on the implementation! A given algorithm will take different amounts of
time on the same inputs depending on such factors as: processor speed; instruction set, disk
speed, brand of compiler and etc. The way around is to estimate efficiency of each
algorithm asymptotically. We will measure time T(n) as the number of elementary "steps"
(defined in any way), provided each such step takes constant time.

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 2

Let us consider two classical examples: addition of two integers. We will add two integers digit
by digit (or bit by bit), and this will define a "step" in our computational model. Therefore, we
say that addition of two n-bit integers takes n steps. Consequently, the total computational
time is T(n) = c * n, where c is time taken by addition of two bits. On different computers,
addition of two bits might take different time, say c1 and c2, thus the addition of two n-bit
integers takes T(n) = c1 * nand T(n) = c2* n respectively. This shows that different machines
result in different slopes, but time T(n) grows linearly as input size increases.
The process of abstracting away details and determining the rate of resource usage in terms of
the input size is one of the fundamental ideas in computer science.
Asymptotic Notations
The goal of computational complexity is to classify algorithms according to their performances.
We will represent the time function T(n) using the "big-O" notation to express an algorithm
runtime complexity. For example, the following statement
T(n) = O(n
2
)
says that an algorithm has a quadratic time complexity.
Definition of "big Oh"
For any monotonic functions f(n) and g(n) from the positive integers to the positive integers, we
say that f(n) = O(g(n)) when there exist constants c > 0 and n0 > 0 such that
f(n) ≤ c * g(n), for all n ≥ n0
Intuitively, this means that function f(n) does not grow faster than g(n), or that function g(n) is
an upper bound for f(n), for all sufficiently large n→∞
Here is a graphic representation of f(n) = O(g(n)) relation:

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 3


Examples:
 1 = O(n)
 n = O(n
2
)
 log(n) = O(n)
 2 n + 1 = O(n)
The "big-O" notation is not symmetric: n = O(n
2
) but n
2
≠ O(n).
Exercise. Let us prove n
2
+ 2 n + 1 = O(n
2
). We must find such c and n0 that n
2
+ 2 n + 1 ≤ c*n
2
.
Let n0=1, then for n ≥ 1
1 + 2 n + n
2
≤ n + 2 n + n
2
≤ n
2
+ 2 n
2
+ n
2
= 4 n
2

Therefore, c = 4.
Constant Time: O(1)
An algorithm is said to run in constant time if it requires the same amount of time regardless of
the input size. Examples:
 array: accessing any element
 fixed-size stack: push and pop methods
 fixed-size queue: enqueue and dequeue methods

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 4

Linear Time: O(n)
An algorithm is said to run in linear time if its time execution is directly proportional to the
input size, i.e. time grows linearly as input size increases. Examples:
 array: linear search, traversing, find minimum
 ArrayList: contains method
 queue: contains method
Logarithmic Time: O(log n)
An algorithm is said to run in logarithmic time if its time execution is proportional to the
logarithm of the input size. Example:
 binary search
Recall the "twenty questions" game - the task is to guess the value of a hidden number in an
interval. Each time you make a guess, you are told whether your guess iss too high or too low.
Twenty questions game implies a strategy that uses your guess number to halve the interval
size. This is an example of the general problem-solving method known as binary search:
locate the element a in a sorted (in ascending order) array by first comparing a with the
middle element and then (if they are not equal) dividing the array into two subarrays; if
a is less than the middle element you repeat the whole procedure in the left subarray,
otherwise - in the right subarray. The procedure repeats until a is found or subarray is a
zero dimension.
Note, log(n) < n, when n→∞. Algorithms that run in O(log n) does not use the whole input.
Quadratic Time: O(n
2
)
An algorithm is said to run in logarithmic time if its time execution is proportional to the square
of the input size. Examples:
 bubble sort, selection sort, insertion sort
Definition of "big Omega"
We need the notation for the lower bound. A capital omega Ω notation is used in this case. We
say that f(n) = Ω(g(n)) when there exist constant c that f(n) ≥ c*g(n) for all sufficiently large n.
Examples
 n = Ω(1)

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 5

 n
2
= Ω(n)
 n
2
= Ω(n log(n))
 2 n + 1 = O(n)
Definition of "big Theta"
To measure the complexity of a particular algorithm, means to find the upper and lower
bounds. A new notation is used in this case. We say that f(n) = Θ(g(n)) if and only f(n) = O(g(n))
and f(n) = Ω(g(n)). Examples
 2 n = Θ(n)
 n
2
+ 2 n + 1 = Θ( n
2
)
Analysis of Algorithms
The term analysis of algorithms is used to describe approaches to the study of the performance
of algorithms. In this course we will perform the following types of analysis:
 the worst-case runtime complexity of the algorithm is the function defined by the
maximum number of steps taken on any instance of size a.
 the best-case runtime complexity of the algorithm is the function defined by the
minimum number of steps taken on any instance of size a.
 the average case runtime complexity of the algorithm is the function defined by an
average number of steps taken on any instance of size a.
 the amortized runtime complexity of the algorithm is the function defined by a sequence
of operations applied to the input of size a and averaged over time.
Example. Let us consider an algorithm of sequential searching in an array of size n.
Its worst-case runtime complexity is O(n)
Its best-case runtime complexity is O(1)
Its average case runtime complexity is O(n/2)=O(n)

3. Flowchart
A flow chart is a graphical or symbolic representation of a process. 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.

Process / Operation Symbols

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 6

SYMBOL
NAME

DESCRIPTION

Process
Show a Process or action step. This is the most
common symbol in both process flowcharts and
process maps.

Predefined
Process
(Subroutine)
A Predefined Process symbol is a marker for another
process step or series of process flow steps that are
formally defined elsewhere. This shape commonly
depicts sub-processes (or subroutines in programming
flowcharts). If the sub-process is considered "known"
but not actually defined in a process procedure, work
instruction, or some other process flowchart or
documentation, then it is best not to use this symbol
since it implies a formally defined process.

Alternate
Process
As the shape name suggests, this flowchart symbol is
used when the process flow step is an alternate to the
normal process step. Flow lines into an alternate
process flow step are typically dashed.

Delay
The Delay flowchart symbol depicts any waiting period
that is part of a process. Delay shapes are common in
process mapping.

Preparation
As the names states, any process step that is a
Preparation process flow step, such as a set-up
operation.

Manual
Operation
Manual Operations flowchart shapes show which
process steps are not automated. In data processing
flowcharts, this data flow shape indicates a looping

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 7

SYMBOL
NAME

DESCRIPTION
operation along with a loop limit symbol (which is not
supported by Microsoft Office, but a Manual
Operation symbol rotated 180° will do the trick.)
Branching and Control of Flow Symbols

SYMBOL
NAME
(ALIAS)
DESCRIPTION

Flow Line
(Arrow,
Connector)
Flow line connectors show the direction that
the process flows.

Terminator
(Terminal Point,
Oval)
Terminators show the start and stop points in a
process. When used as a Start symbol,
terminators depict a trigger action that sets the
process flow into motion.

Decision
Indicates a question or branch in the process
flow. Typically, a Decision flowchart shape is
used when there are 2 options (Yes/No, No/No-
Go, etc.)

Connector
(Inspection)
Ad by New Saver. More Info | Hide These Ads
Flowchart: In flowcharts, this symbol is typically
small and is used as a Connector to show a
jump from one point in the process flow to
another. Connectors are usually labelled with
capital letters (A, B, AA) to show matching jump
points. They are handy for avoiding flow lines
that cross other shapes and flow lines. They are

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 8

SYMBOL
NAME
(ALIAS)
DESCRIPTION
also handy for jumping to and from a sub-
processes defined in a separate area than the
main flowchart.
Process Mapping: In process maps, this symbol
is full sized and shows an Inspection point in the
process flow.

[Just to confuse things further, some people will
use a circle to indicate an operation and a
square to indicate an inspection. That's why it's
important to include a symbol key in the
flowchart.]

Off-Page
Connector
Off-Page Connector shows continuation of a
process flowchart onto another page. When
using them in conjunction with Connectors, it's
best to differentiate the labels, e.g. use
numbers for Off-Page Connectors and capital
letters for Connectors. In actual practice, most
flowcharts just use the Connect shape for both
on-page and off-page references.

Merge
(Storage)
Flowchart: Shows the merging of multiple
processes or information into one.
Process Mapping: commonly indicates storage
of raw materials.

Extract
(Measurement)
Flowchart: Shows when a process splits into
parallel paths. Also commonly indicates a
Measurement, with a capital 'M' inside the
symbol.
Process Mapping: commonly indicates storage

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 9

SYMBOL
NAME
(ALIAS)
DESCRIPTION
of finished goods.

Or
The logical Or symbol shows when a process
diverges - usually for more than 2 branches.
When using this symbol, it is important to label
the out-going flow lines to indicate the criteria
to follow each branch.

Summing
Junction
The logical Summing Junction flowchart shape is
shows when multiple branches converge into a
single process. The merge symbol is more
common for this use, though. This symbol and
the Or symbol are really more relevant in data
processing flow diagrams than in process
flowcharts.

Input and Output Symbols
SYMBOL
NAME
(ALIAS)
DESCRIPTION

Data
(I/O)
The Data flowchart shape indicates inputs to and outputs from a process. As
such, the shape is more often referred to as an I/O shape than a Data shape.

Document
Pretty self explanatory - the Document flowchart symbol is for a process
step that produces a document.

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 10

SYMBOL
NAME
(ALIAS)
DESCRIPTION

Multi-
Document
Same as Document, except, well, multiple documents. This shape is not as
commonly used as the Document flowchart shape, even when multiple
documents are implied.

Display
Indicates a process step where information is displayed to a person (e.g., PC
user, machine operator).

Manual
Input
Manual Input flowchart shapes show process steps where the operator/
user is prompted for information that must be manually input into a system.

Card
This is the companion to the punched tape flowchart shapes. This shape is
seldom used.

Punched
Tape
If you're very good at stretching all the life out of a machine, you may still
have use for the Punched Tape symbol - used for input into old computers
and CNC machines.

File and Information Storage Symbols
SYMBOL
NAME
(ALIAS)
DESCRIPTION

Stored Data
A general Data Storage flowchart shape used for any process step that
stores data (as opposed to the more specific shapes to follow next in this
table).

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 11

SYMBOL
NAME
(ALIAS)
DESCRIPTION

Magnetic Disk
(Database)
The most universally recognizable symbol for a data storage location, this
flowchart shape depicts a database.

Direct Access
Storage
Direct Access Storage is a fancy way of saying Hard Drive.

Internal Storage
Used in programming flowcharts to mean information stored in memory, as
opposed to on a file.

Sequential
Access Storage
(Magnetic Tape)
Although it looks like a 'Q', the symbol is supposed to look like a reel of tape.

Data Processing Symbols
SYMBOL
NAME

DESCRIPTION

Collate
The Collate flowchart shape indicates a process step that requires organizing data,
information, or materials according into a standard format or arrangement.

Sort Indicates the sorting of data, information, materials into some pre-defined order.

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 12

Introduction of Programming
An organized list of instructions that, when executed, causes the computer to behave in a
predetermined manner. Without programs, computers are useless.
A program is like a recipe. It contains a list of ingredients (called variables) and a list of
directions (called statements) that tell the computer what to do with the variables. The
variables can represent numeric data, text, or graphical images.
There are many programming languages -- C, C++, Pascal, BASIC, FORTRAN, COBOL, and LISP are
just a few. These are all high-level languages. One can also write programs in low-level
languages called assembly languages, although this is more difficult. Low-level languages are
closer to the language used by a computer, while high-level languages are closer to human
languages.
Eventually, every program must be translated into a machine language that the computer can
understand. This translation is performed by compilers, interpreters, and assemblers.
When you buy software, you normally buy an executable version of a program. This means that
the program is already in machine language -- it has already been compiled and assembled and
is ready to execute.
Categories of Programming Language
Programming languages fall into two fundamental categories low and high-level languages.
Low-level languages are machine-dependent; that is, they are designed to be run on a
particular computer. In contrast, high-level languages (for example, COBOL and BASIC) are
machine-independent and can be run on a variety of computers.
The hierarchy of programming languages in the Figure summarizes the relationships between
the various types of programming languages. Through the first four decades of computing,
programming languages evolved in generations. The first two generations were low-level and
the next two high-level generations of programming languages.
The higher-level languages do not provide us a greater programming capabilities, but they do
provide a more sophisticated programmer/computer interaction. In short, the higher the level
of the language, the easier it is to understand and use. For example, in a fourth-generation
language you need only instruct the computer system what to do, not necessarily how to do it.
Characteristics of Programming language

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 13

The following are the characteristics of a programming language


1. Readability: A good high-level language will allow programs to be written in some ways that
resemble a quite-English description of the underlying algorithms. If care is taken, the coding
may be done in a way that is essentially self-documenting.
2. Portability: High-level languages, being essentially machine independent, should be able to
develop portable software.
3. Generality: Most high-level languages allow the writing of a wide variety of programs, thus
relieving the programmer of the need to become expert in many diverse languages.
4. Brevity: Language should have the ability to implement the algorithm with less amount of
code. Programs expressed in high-level languages are often considerably shorter than their low-
level equivalents.
5. Error checking: Being human, a programmer is likely to make many mistakes in the
development of a computer program. Many high-level languages enforce a great deal of error
checking both at compile-time and at run-time.
6. Cost: The ultimate cost of a programming language is a function of many of its
characteristics.
7. Familiar notation: A language should have familiar notation, so it can be understood by most
of the programmers.
8. Quick translation: It should admit quick translation.
9. Efficiency: It should permit the generation of efficient object code.
10. Modularity: It is desirable that programs can be developed in the language as a collection of
separately compiled modules, with appropriate mechanisms for ensuring self-consistency
between these modules.
11. Widely available: Language should be widely available and it should be possible to provide
translators for all the major machines and for all the major operating systems.
Procedure Oriented Programming:- Procedure oriented programming is the conventional way
of programming where an application problem is viewed as a sequence of steps. In procedure
oriented programming the problem is broken down into various modules such as data entry
reporting querying module etc. There are two types of data, which are associated with these
modules, one is global and another is local data.
Global data items are mainly defined in main program, where local data is defined with the
associated functions.
Many of the functions in the programming language share global data, which is available to all
the functions. The procedural-oriented programming is the traditional approach of

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 14

programming for developing application software. High level languages like FORTRAN, COBOL,
PASCAL, BASIC and C are based on the procedure oriented approach and consequently are
called procedural languages.

Object-oriented programming (OOP) is a programming language model organized around
"objects" rather than "actions" and data rather than logic. Historically, a program has been
viewed as a logical procedure that takes input data, processes it, and produces output data.
The programming challenge was seen as how to write the logic, not how to define the data.
Object-oriented programming takes the view that what we really care about are the objects we
want to manipulate rather than the logic required to manipulate them. Examples of objects
range from human beings (described by name, address, and so forth) to buildings and floors
(whose properties can be described and managed) down to the little widgets on your computer
desktop (such as buttons and scroll bars).
The concepts and rules used in object-oriented programming provide these important benefits:
 The concept of a data class makes it possible to define subclasses of data objects that
share some or all of the main class characteristics. Called inheritance, this property of
OOP forces a more thorough data analysis, reduces development time, and ensures
more accurate coding.
 Since a class defines only the data it needs to be concerned with, when an instance of
that class (an object) is run, the code will not be able to accidentally access other
program data. This characteristic of data hiding provides greater system security and
avoids unintended data corruption.

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 15

 The definition of a class is reusable not only by the program for which it is initially
created but also by other object-oriented programs (and, for this reason, can be more
easily distributed for use in networks).
 The concept of data classes allows a programmer to create any new data type that is not
already defined in the language itself.

Features of OOPs:-

 Objects:- Objects are the basic run-time entities in an object-oriented system. Programming
problem is analyzed in terms of objects and nature of communication between them. When a
program is executed, objects interact with each other by sending messages. Different objects
can also interact with each other without knowing the details of their data or code.
 Classes:- A class is a collection of objects of similar type. Once a class is defined, any number of
objects can be created which belong to that class.
 Data Abstraction and Encapsulation:- Abstraction refers to the act of representing essential
features without including the background details or explanations. Classes use the concept of
abstraction and are defined as a list of abstract attributes. Storing data and functions in a single
unit (class) is encapsulation. Data cannot be accessible to the outside world and only those
functions which are stored in the class can access it.
 Inheritance:- Inheritance is the process by which objects can acquire the properties of objects of
other class. In OOP, inheritance provides reusability, like, adding additional features to an
existing class without modifying it. This is achieved by deriving a new class from the existing one.
The new class will have combined features of both the classes.
 Polymorphism:- Polymorphism means the ability to take more than one form. An operation may
exhibit different behaviors in different instances. The behavior depends on the data types used
in the operation. Polymorphism is extensively used in implementing Inheritance.

Merits of OOPs:-
 Simplicity: software objects model real world objects, so the complexity is reduced and the
program structure is very clear;
 Modularity: each object forms a separate entity whose internal workings are decoupled from
other parts of the system;

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 16

 Modifiability: it is easy to make minor changes in the data representation or the procedures in
an OO program. Changes inside a class do not affect any other part of a program, since the only
public interface that the external world has to a class is through the use of methods;
 Extensibility: adding new features or responding to changing operating environments can be
solved by introducing a few new objects and modifying some existing ones;
 Maintainability: objects can be maintained separately, making locating and fixing problems
easier;
 Re-usability: objects can be reused in different programs.
History
The C++ programming languages is an extension of C that was developed by Bjarne Stroustrup in the
early 1980s at Bell Laboratories. C++ provides a number of features that "spruce up" the C language, but
more importantly, it provides capabilities for object-oriented programming. A computer cannot
understand our language that we use in our day to day conversations, and likewise, we cannot
understand the binary language that the computer uses to do it’s tasks. It is therefore necessary for us
to write instructions in some specially defined language like C++ which is like natural language and after
converting with the help of compiler the computer can understand it.
Significant Language Features
Object-oriented programs are easier to understand, correct and modify. Many other object-oriented
languages have been developed, including most notably, Smalltalk. The best features of C++ are:
 C++ is a hybrid language-it is possible to program in either a C-like style, an object-oriented
style, or both.
 C++ programs consist of pieces called classes and functions. You can program each piece you
may need to form a C++ program. The advantage of creating your own functions and classes is
that you will know exactly how they work. You will be able to examine the C++ code.
Areas of Application
C++ provides a collection of predefined classes, along with the capability of user-defined classes. The
classes of C++ are data types,which can be instantiated any number of times. Class definitions specify
data objects (called data members) and functions (called member function). Classes can name one or
more parent classes, providing inheritance and multiple inheritance, respectively. Classes inherit the
data members and member functions of the parent class that are specified to be inheritable. Therefore
it is mainly used for:
 Software Engineering

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 17

 Graphics
C++ COMPILER
A C++ compiler is itself a computer program which’s only job is to convert the C++ program from our
form to a form the computer can read and execute. The original C++ program is called the “source
code”, and the resulting compiled code produced by the compiler is usually called an “object file”.
Before compilation the preprocessor performs preliminary operations on C++ source files. Preprocessed
form of the source code is sent to compiler.
After compilation stage object files are combined with predefined libraries by a linker, sometimes called
a binder, to produce the final complete file that can be executed by the computer. A library is a
collection of pre-compiled “object code” that provides operations that are done repeatedly by many
computer programs.

Using Turbo C++ Compiler

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 18

The first and frequently used method for creating program is Turbo C++'s Integrated Development
Environment (IDE). To start IDE type TC at DOS prompt. Or search the file TC.EXE in your computer and
Run it. Your IDE will look like this.

1. Now type sample program on Editor
2. Click on Compile menu choose Compile option or press Alt+F9
3. Click on Run menu choose Run option or press Ctrl+F9
4. If there is no error output will be displayed on User Screen
Before we begin to learn to write meaningful programs in C++ language, let us have a look at the various
building block of C++ language, also called elements of C++ language....
C++ BASICS
C++ CHARACTER SET
Character set is a set of valid characters that a language can recognize.
Letters A-Z, a-z
Digits 0-9
Special Characters
Space + - * / ^ \ () [] {} = != <> ‘ “ $ , ; : % ! & ? _ #
<= >= @
Formatting
characters
backspace, horizontal tab, vertical tab, form feed, and carriage
return
TOKENS
A token is a group of characters that logically belong together. The programmer can write a program by
using tokens. C++ uses the following types of tokens.
Keywords, Identifiers, Literals, Punctuators, Operators.
1. Keywords

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 19

These are some reserved words in C++ which have predefined meaning to compiler called keywords.
Some commonly used Keyword are given below:
asm auto break case catch
char class const continue default
delete do double else enum
extern inline int float for
friend goto if long new
operator private protected public register
return short signed sizeof static
struct switch template this Try
typedef union unsigned virtual void
volatile while

2. Identifiers
Symbolic names can be used in C++ for various data items used by a programmer in his program. A
symbolic name is generally known as an identifier. The identifier is a sequence of characters taken from
C++ character set. The rule for the formation of an identifier are:
 An identifier can consist of alphabets, digits and/or underscores.
 It must not start with a digit
 C++ is case sensitive that is upper case and lower case letters are considered different from each
other.
 It should not be a reserved word.
3. Literals
Literals (often referred to as constants) are data items that never change their value during the
execution of the program. The following types of literals are available in C++.
 Integer-Constants
 Character-constants

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 20

 Floating-constants
 Strings-constants
Integer Constants: Integer constants are whole number without any fractional part. C++ allows three
types of integer constants.
Decimal integer constants : It consists of sequence of digits and should not begin with 0 (zero). For
example 124, - 179, +108.
Octal integer constants: It consists of sequence of digits starting with 0 (zero). For example. 014, 012.
Hexadecimal integer constant: It consists of sequence of digits preceded by ox or OX.
Character constants
A character constant in C++ must contain one or more characters and must be enclosed in single
quotation marks. For example 'A', '9', etc. C++ allows nongraphic characters which cannot be typed
directly from keyboard, e.g., backspace, tab, carriage return etc. These characters can be represented by
using an escape sequence. An escape sequence represents a single character. The following table gives a
listing of common escape sequences.
Escape Sequence Nongraphic Character
\a Bell (beep)
\n Newline
\r Carriage Return
\t Horizontal tab
\0 Null Character
Floating constants
They are also called real constants. They are numbers having fractional parts. They may be written in
fractional form or exponent form. A real constant in fractional form consists of signed or unsigned digits
including a decimal point between digits. For example 3.0, -17.0, -0.627 etc.
String Literals
A sequence of character enclosed within double quotes is called a string literal. String literal is by default
(automatically) added with a special character ‘\0' which denotes the end of the string. Therefore the
size of the string is increased by one character. For example "COMPUTER" will re represented as
"COMPUTER\0" in the memory and its size is 9 characters.
4. Punctuators

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 21

The following characters are used as punctuators in C++.
Brackets [ ]
Opening and closing brackets indicate single and multidimensional
array subscript.
Parentheses (
)
Opening and closing brackets indicate functions calls,; function
parameters for grouping expressions etc.
Braces { }
Opening and closing braces indicate the start and end of a
compound statement.
Comma , It is used as a separator in a function argument list.
Semicolon ; It is used as a statement terminator.
Colon : It indicates a labeled statement or conditional operator symbol.
Asterisk * It is used in pointer declaration or as multiplication operator.
Equal sign = It is used as an assignment operator.
Pound sign # It is used as pre-processor directive.

5. Operators: Operators are special symbols used for specific purposes. C++ provides six types of
operators. Arithmetical operators, Relational operators, Logical operators, Unary operators, Assignment
operators, Conditional operators, Comma operator
DATA HANDLING
BASIC DATA TYPES
C++ supports a large number of data types. The built in or basic data types supported by C++ are integer,
floating point and character. These are summarized in table along with description and memory
requirement
Type Byte Range Description
int 2 -32768 to +32767 Small whole number
long int 4 -2147483648 to +2147483647 Large whole number
float 4 3.4x10-38 to 3.4x10+38 Small real number
double 8 1.7x10-308 to 1.7x10+308 Large real number

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 22

long double 10 3.4x10-4932 to 3.4x10+4932 Very Large real number
char 1 0 to 255 A Single Character

VARIABLES
It is a location in the computer memory which can store data and is given a symbolic name for easy
reference. The variables can be used to hold different values at different times during the execution of a
program.
To understand more clearly we should study the following statements:
Total = 20.00; In this statement a value 20.00 has been stored in a memory location Total.
Declaration of a variable
Before a variable is used in a program, we must declare it. This activity enables the compiler to make
available the appropriate type of location in the memory.
float Total;
You can declare more than one variable of same type in a single single statement
int x,y;
Initialization of variable
When we declare a variable it's default value is undetermined. We can declare a variable with some
initial value.
int a = 20;
INPUT/OUTPUT (I/O)
C++ supports input/output statements which can be used to feed new data into the computer or obtain
output on an output device such as: VDU, printer etc. The following C++ stream objects can be used for
the input/output purpose.
cin console input
cout console output
cout is used in conjuction with << operator, known as insertion or put to operator.
cin is used in conjuction with >> operator, known as extraction or get from operator.
cout << “My first computer"; Once the above statement is carried out by the computer, the message
"My first computer" will appear on the screen.

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 23

cin can be used to input a value entered by the user from the keyboard. However, the get from
operator>> is also required to get the typed value from cin and store it in the memory location.
Let us consider the following program segment:
int marks;
cin >> marks; In the above segment, the user has defined a variable marks of integer type in the first
statement and in the second statement he is trying to read a value from the keyboard.
TYPE CONVERSION
The process in which one pre-defined type of expression is converted into another type is called
conversion. There are two types of conversion in C++.

1. Widening conversion (Expansion)
2. Narrowing conversion (Compression)

STRUCTURE OF C++ PROGRAM
#include<header file>
main ()
{
...........
...........
...........
}
A C++ program starts with function called main ( ). The body of the function is enclosed between curly
braces. The program statements are written within the braces. Each statement must end by a
semicolon;(statement terminator). A C++ program may contain as many functions as required. However,
when the program is loaded in the memory, the control is handed over to function main ( ) and it is the
first function to be executed.
// This is my first program is C++
/* this program will illustrate different components of
a simple program in C++ */

# include <iostream.h>
int main ( )
{
cout <<"Hello World!";
return 0;
}

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 24

When the above program is compiled, linked and executed, the following output is displayed on the
VDU screen.
Hello World!
Various components of this program are discussed below:
Comments
First three lines of the above program are comments and are ignored by the compiler. Comments are
included in a program to make it more readable. If a comment is short and can be accommodated in a
single line, then it is started with double slash sequence in the first line of the program. However, if
there are multiple lines in a comment, it is enclosed between the two symbols /* and */
#include <iostream.h>
The line in the above program that start with # symbol are called directives and are instructions to the
compiler. The word include with '#' tells the compiler to include the file iostream.h into the file of the
above program. File iostream.h is a header file needed for input/ output requirements of the program.
Therefore, this file has been included at the top of the program.
int main ( )
The word main is a function name. The brackets ( ) with main tells that main ( ) is a function. The word
int before main ( ) indicates that integer value is being returned by the function main (). When program
is loaded in the memory, the control is handed over to function main ( ) and it is the first function to be
executed.
Curly bracket and body of the function main ( )
A C++ program starts with function called main(). The body of the function is enclosed between curly
braces. The program statements are written within the brackets. Each statement must end by a
semicolon, without which an error message in generated.
cout<<"Hello World!";
This statement prints our "Hello World!" message on the screen. cout understands that anything sent to
it via the << operator should be printed on the screen.
return 0;
This is a new type of statement, called a return statement. When a program finishes running, it sends a
value to the operating system. This particular return statement returns the value of 0 to the operating
system, which means “everything went okay!”.

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 25

/* This program illustrates how to
declare variable, read data and display data. */

#include <iostream.h>
int main()
{
int rollno; //declare the variable rollno of type int
float marks; //declare the variable marks of type float
cout << "Enter roll number and marks :";
cin >> rollno >> marks; //store data into variable rollno & marks
cout << "Rollno: " << rollno<<"\n";
cout << "Marks: " << marks;
return 0;
}
Sample Run: In this sample run, the user input is shaded.
Enter roll number and marks :102 87.5
Rollno: 102
Marks: 87.5
OPERATORS
Operators are special symbols used for specific purposes. C++ provides six types of operators.
Arithmetical operators, Relational operators, Logical operators, Unary operators, Assignment operators,
Conditional operators, Comma operator
Arithmetical operators
Arithmetical operators +, -, *, /, and % are used to performs an arithmetic (numeric) operation. You can
use the operators +, -, *, and / with both integral and floating-point data types. Modulus or remainder %
operator is used only with the integral data type.
Operators that have two operands are called binary operators.
Relational operators
The relational operators are used to test the relation between two values. All relational operators are
binary operators and therefore require two operands. A relational expression returns zero when the
relation is false and a non-zero when it is true. The following table shows the relational operators.
Relational Operators Meaning
< Less than

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 26

<= Less than or equal to
== Equal to
> Greater than
>= Greater than or equal to
! = Not equal to
Logical operators
The logical operators are used to combine one or more relational expression. The logical operators are
Operators Meaning
|| OR
&& AND
! NOT

Unary operators
C++ provides two unary operators for which only one variable is required.
For Example a = - 50;
a = + 50; Here plus sign (+) and minus sign (-) are unary because they are not used between two
variables.
Assignment operator
The assignment operator '=' is used for assigning a variable to a value. This operator takes the
expression on its right-hand-side and places it into the variable on its left-hand-side. For example: m = 5;
The operator takes the expression on the right, 5, and stores it in the variable on the left, m. x = y = z =
32; This code stores the value 32 in each of the three variables x, y, and z.
in addition to standard assignment operator shown above, C++ also support compound assignment
operators.
Compound Assignment Operators
Operator Example Equivalent to
+ = A + = 2 A = A + 2

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 27

- = A - = 2 A = A - 2
% = A % = 2 A = A % 2
/= A/ = 2 A = A / 2
*= A * = 2 A = A * 2
Increment and Decrement Operators
C++ provides two special operators viz '++' and '--' for incrementing and decrementing the value of a
variable by 1. The increment/decrement operator can be used with any type of variable but it cannot be
used with any constant. Increment and decrement operators each have two forms, pre and post.
The syntax of the increment operator is:
Pre-increment: ++variable
Post-increment: variable++
The syntax of the decrement operator is:
Pre-decrement: ––variable
Post-decrement: variable––
In Prefix form first variable is first incremented/decremented, then evaluated
In Postfix form first variable is first evaluated, then incremented/decremented
int x,y;
int i=10,j=10;
x = ++i; //add one to i, store the result back in x
y= j++; //store the value of j to y then add one to j
cout<<x; //11
cout<<y; //10
Conditional operator
The conditional operator ?: is called ternary operator as it requires three operands. The format of the
conditional operator is:
Conditional_ expression ? expression1 : expression2;
If the value of conditional expression is true then the expression1 is evaluated, otherwise expression2 is
evaluated. int a = 5, b = 6;
big = (a > b) ? a : b; The condition evaluates to false, therefore biggets the value from b and it becomes
6.
The comma operator
The comma operator gives left to right evaluation of expressions. When the set of expressions has to be
evaluated for a value, only the rightmost expression is considered.

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 28

int a=1, b=2, c=3, i; // comma acts as separator, not as an operator
i = (a, b); // stores b into i Would first assign the value of a to i, and then assign value of b to variable i.
So, at the end, variable i would contain the value 2.
The order of Precedence
The order in which the Arithmetic operators (+,-,*,/,%) are used in a. given expression is called the order
of precedence. The following table shows the order of precedence.
Order Operators
First
Second
Third
()
*, /, %
+, -
The following table shows the precedence of operators.
++, --(post increment/decrement)
Highest
To

Lowest
++ (Pre increment) -- (Pre decrement), sizeof ( ), !(not), -(unary),
+(unary)
*,/, %
+, -
<, <=, >, >=
==,!=
&&
? :
=
Comma operator

FLOW OF CONTROL
Statements
Statements are the instructions given to the computer to perform any kind of action. Action may be in
the form of data movement, decision making etc. Statements form the smallest executable unit within a
C++ program. Statements are always terminated by semicolon.

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 29

Compound Statement
A compound statement is a grouping of statements in which each individual statement ends with a
semi-colon. The group of statements is called block. Compound statements are enclosed between the
pair of braces ({}.). The opening brace ({) signifies the beginning and closing brace (}) signifies the end of
the block.
Null Statement
Writing only a semicolon indicates a null statement. Thus ';' is a null or empty statement. This is quite
useful when the syntax of the language needs to specify a statement but the logic of the program does
not need any statement. This statement is generally used in for and while looping statements.
Conditional Statements
Sometimes the program needs to be executed depending upon a particular condition. C++ provides the
following statements for implementing the selection control structure.
 if statement
 if else statement
 nested if statement
 switch statement
if statement
syntax of the if statement
if (condition)
{
statement(s);
}
From the flowchart it is clear that if the if condition is true, statement is executed; otherwise it is
skipped. The statement may either be a single or compound statement.

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 30


if else statement
syntax of the if - else statement
if (condition)
statement1;
else
statement2;
From the above flowchart it is clear that the given condition is evaluated first. If the condition is true,
statement1 is executed. If the condition is false, statement2 is executed. It should be kept in mind that
statement and statement2 can be single or compound statement.
if example if else example
if (x == 100)
cout << "x is 100";
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
Nested if statement
The if block may be nested in another if or else block. This is called nesting of if or else block.
syntax of the nested if statement
if(condition 1)
{
if(condition 2)
{
statement(s);

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 31

}
}
if(condition 1)
statement 1;
else if (condition 2)
statement2;
else
statement3;

if-else-if example
if(percentage>=60)
cout<<"Ist division";
else if(percentage>=50)
cout<<"IInd division";
else if(percentage>=40)
cout<<"IIIrd division";
else
cout<<"Fail" ;
switch statement
The if and if-else statements permit two way branching whereas switch statement permits multiple
branching. The syntax of switch statement is:
switch (var / expression)
{
case constant1 : statement 1;
break;
case constant2 : statement2;
break;
.
.
default: statement3;
break;
}
The execution of switch statement begins with the evaluation of expression. If the value of expression
matches with the constant then the statements following this statement execute sequentially till it

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 32

executes break. The break statement transfers control to the end of the switch statement. If the value of
expression does not match with any constant, the statement with default is executed.
Some important points about switch statement
 The expression of switch statement must be of type integer or character type.
 The default case need not to be used at last case. It can be placed at any place.
 The case values need not to be in specific order.
FLOW OF CONTROL
Looping statement
It is also called a Repetitive control structure. Sometimes we require a set of statements to be executed
a number of times by changing the value of one or more variables each time to obtain a different result.
This type of program execution is called looping. C++ provides the following construct
 while loop
 do-while loop
 for loop
While loop
Syntax of while loop
while(condition)
{
statement(s);
}
The flow diagram indicates that a condition is first evaluated. If the condition is true, the loop body is
executed and the condition is re-evaluated. Hence, the loop body is executed repeatedly as long as the
condition remains true. As soon as the condition becomes false, it comes out of the loop and goes to the
statement next to the ‘while’ loop.
do-while loop
Syntax of do-while loop
do
{statements;
} while (condition);

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 33



Note : That the loop body is always executed at least once. One important difference between the while
loop and the do-while loop the relative ordering of the conditional test and loop body execution. In the
while loop, the loop repetition test is performed before each execution the loop body; the loop body is
not executed at all if the initial test fail. In the do-while loop, the loop termination test is Performed
after each execution of the loop body. hence, the loop body is always executed least once.

for loop

It is a count controlled loop in the sense that
the program knows in advance how many times
the loop is to be executed.
syntax of for loop for (initialization; decision;
increment/decrement)
{
statement(s);
}







The flow diagram indicates that in for loop three operations take place:
 Initialization of loop control variable

BCE/UNIT II Truba College of Science & Technology,
Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 34

 Testing of loop control variable
 Update the loop control variable either by incrementing or decrementing.

Operation (i) is used to initialize the value. On the other hand, operation (ii) is used to test whether the
condition is true or false. If the condition is true, the program executes the body of the loop and then
the value of loop control variable is updated. Again it checks the condition and so on. If the condition is
false, it gets out of the loop

BCE/UNIT II Truba College of Science & Technology, Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 35

Jump Statements
The jump statements unconditionally transfer program control within a function.
 goto statement
 break statement
 continue statement
The goto statement
goto allows to make jump to another point in the program. goto pqr;
pqr: pqr is known as label. It is a user defined identifier. After the execution of goto statement, the control
transfers to the line after label pqr.
The break statement
The break statement, when executed in a switch structure, provides an immediate
exit from the switch structure. Similarly, you can use the break statement in
any of the loop. When the break statement executes in a loop, it immediately exits from the loop.
ARRAY
An array is a collection of data elements of same data type. It is described by a single name and each
element of an array is referenced by using array name and its subscript no.
Declaration of Array
Type arrayName[numberOfElements];
For example, int Age[5] ;
float cost[30];


Initialization of One Dimensional Array
An array can be initialized along with declaration. For array initialization it is required to place the elements
separated by commas enclosed within braces. int A[5] = {11,2,23,4,15}; It is possible to leave the array size
open. The compiler will count the array size. int B[] = {6,7,8,9,15,12};
Referring to Array Elements

BCE/UNIT II Truba College of Science & Technology, Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 36

In any point of a program in which an array is visible, we can access the value of any of its elements
individually as if it was a normal variable, thus being able to both read and modify its value. The format is
as simple as:
name[index]

Examples: cout<<age[4]; //print an array element
age[4]=55; // assign value to an array element
cin>>age[4]; //input element 4
Using Loop to input an Array from user
int age [10], i ;
for (i=0 ; i<10; i++)
{
cin>>age[i];
}
Arrays as Parameters
At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to
pass a complete block of memory by value as a parameter to a function, but we are allowed to pass its
address.
For example, the following function: void print(int A[]) accepts a parameter of type "array of int"
called A.
In order to pass to this function an array declared as: int arr[20]; we need to write a call like this:
print(arr);

STRUCTURE
A structure is a collection of variable which can be same or different types. You can refer to a structure as a
single variable, and to its parts as members of that variable by using the dot (.) operator. The power of
structures lies in the fact that once defined, the structure name becomes a user-defined data type and
may be used the same way as other built-in data types, such as int, double, char.
struct STUDENT
{
int rollno, age;
char name[80];
float marks;
} ;

int main()
{
// declare two variables of the new type
STUDENT s1, s3;
//accessing of data members

BCE/UNIT II Truba College of Science & Technology, Bhopal

By: Ms. Nandini Sharma [CSE Deptt.] Page 37

cin>>s1.rollno>>s1.age>>s1.name>>s1.marks;
cout<<s1.rollno<<s1.age<<s1.name<<s1.marks;
//initialization of structure variable
STUDENT s2 = {100,17,”Aniket”,92};
cout<<s2.rollno<<s2.age<<s2.name<<s2.marks;
//structure variable in assignment statement
s3=s2;
cout<<s3.rollno<<s3.age<<s3.name<<s3.marks;
return 0;
}

Defining a structure
When dealing with the students in a school, many variables of different types are needed. It may be
necessary to keep track of name, age, Rollno, and marks point for example. struct STUDENT
{
int rollno, age;
char name[80];
float marks;
}; STUDENT is called the structure tag, and is your brand new data type, like int, double or char.

rollno, name, age, and marks are structure members.
Declaring Variables of Type struct
The most efficient method of dealing with structure variables is to define the structure globally. This tells
"the whole world", namely main and any functions in the program, that a new data type exists. To declare
a structure globally, place it BEFORE void main(). The structure variables can then be defined locally in
main, for example…
Tags