Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 175

.

Chapter One

Introduction to Computer

1
Content

• Definition of computer

• Characteristics of computer

• Generation of computers (Reading Assignment)

• Type of computers

• Applications of computer
What is computer?

• It is an electronic device which processes given data to


derive the required and useful information.

• Computer is a device that enables you to process


information automatically and in accordance with
instructions that you give it.

• A computer is a programmable machine. It allows the user


to store all sorts of information and then process that
information, or data, or carry out actions with the
information, such as calculating numbers or organizing
words.
How Does a Computer Work?

 A computer functions performed in the following manner:

– The computer accepts input/ instructions & data from


the user.
– The computer performs useful operations,

– The computer produces output

– The computer stores data for later use


Why we use Computers?

• Store and process large amount of information with high


speed and accuracy;
• Transmit information across continents via communication
channels;
• Perform complex mathematical computations and make
comparisons;
• Monitor ongoing industrial operations;
• Perform repetitive processes with great ease, speed, and
reliability;
Characteristics of a Computer

• Speed: - The computer is able to process the data and give the
output in fractions of seconds such that required information is
given to the user on time enabling the user to take right
decisions on right time.
• A powerful computer is capable of executing about 3 million
calculations per second.
• Accuracy: - In spite of its high speed of processing, the
computers accuracy is consistently high enough which avoids
any errors.
• If it all there are errors, they are due to errors in instructions
given by the programmer. (GIGO)
Cont…
• Reliable: - The output generated by the computer is very
reliable, but it is reliable only when the data, which is
passing as input to the computer and the program, which
gives instructions are correct and reliable.

• Storage Capacity: - The computer has a provision to store


large volumes of data in the small storage devices, which
have capacity to store huge amounts of data and help the
retrieval of data an easy task.

• Versatile: - Computers can perform multi tasks and it has


multipurpose application
Cont…

• Automation: - Once the instructions fed into computer it works


automatically without any human intervention until the
completion of execution of program until meets logical
instructions to terminate the job.
• Diligent: - The computer performance is consistent even to all
extent of more than 10 million calculations;
• Cost effectiveness: Computers reduce the amount of paper work
and human effort.
Cont…

• No IQ:-Computer is a dumb machine and it cannot do any work


without instruction from the user. It is you to decide what you
want to do and in what sequence. So, a computer cannot take its
own decision as you can.
• No Feeling:-It does not have feelings or emotion, taste,
knowledge and experience. Thus it does not get tired even after
long hours of work. It does not distinguish between users.
Limitation of Computer:

– Computer does not work on itself, it requires set of instructions


to be provided, and else computer (Hardware) is waste.
– Computer are not intelligent, they have to be instructed about
each and every step which they have to perform.
– Computers cannot take decisions on its own, one has to
program the computer to take an action if some conditional
prevail.

– Computers, unlike humans cannot learn by experience.


Types of Computers

• Computers are generally classified on the basis of various factors:

– On the basis of Data processing

– According to purpose of application

– According to the basis of Size and data processing capacity

On the basis of Data processing

• Classification by on the basis of Data processing computer classified into


three:
– Analog computer

– Digital computer

– Hybrid computers.
Analog computers

• Analog computers operate by measuring. They deal with


continues variables, they don’t compute directly with
numbers, rather, they operate by measuring physical
magnitude such as pressure, temperature, voltage, current etc.
• Examples
– Thermometer

– Voltmeter

– Speedometer

• They are special purpose computers


. Digital Computers
• A computer that performs calculations and logical operations with
quantities represented as digits, usually in the binary number
system.
• A digital computer is designed to process data in numerical form;
its circuits perform directly the mathematical operations of
addition, subtraction, multiplication, and division.
• Examples:
– Abacus
– Desk & pocket computers
• They are general-purpose computers
• Digital computers have very high accuracy and speed than the
analog ones.
Hybrid Computer

• A combination of computers those are capable of inputting and

outputting in both digital and analog signals.

• A hybrid computer system setup offers a cost-effective method of

performing complex simulations.

• Hybrid computer is a digital computer that accepts analog signals,

converts them to digital and processes them in digital form. This

integration is obtained by digital to analog and analog to digital

converter. A hybrid computer may use or produce analog data or

digital data.
Cont..

• Depending on purpose of application computers are classified into


– Special Purpose Computers and
– General Purpose Computers
• Special Purpose Computers: These are developed with a specific
purpose.
• Example
– The public telephone box
– Traffic control system
– Ticket machines (used in grocery, super market etc.)
– Pocket-calculators etc.
– Counters
Cont..

• General Purpose Computers: Developed to meet the


requirements of several areas such as simulation, solving
mathematical equations, payroll and personnel database.
• These computers are available in different sizes and capabilities
and are further classified (based on memory, speed, and
storage) as follows. Example: -
– Micro computers
– Mini computers
– Super computers etc.
Cont..

• According to the basis of size and data processing capacity


• Computers can be classified in various ways depending upon its
size, memory capacity, processing speed.
– Personal / Microcomputer

– Minicomputer

– Mainframe computer

– Super computer
Personal / Microcomputer

• A microcomputer is the smallest general purpose processing


system.
• Micro computers are also referred as ―personal computer (PC).
• These are self-contained units and usually developed for use by
one person at a time.
• They are cheap, easy to use even at homes and can be read for
variety of applications from small to medium range.
Cont…
• The main components are Monitor, CPU, Keyboard, Mouse,
Speakers, Modem and Printer.

• They are having limited peripherals attached to them.

• This type of computers can use wide range of software.

• They are used as desktops either in offices or even homes.

• Children enjoy playing games & watching movies in these computers.

• Most popular micro computer’s processing chip manufacturing


company is Intel.
Cont…
• Businesses use personal computers for word processing,
accounting, desktop publishing, and for running spreadsheet and
database management applications.
• Although personal computers are designed as single-user
systems, these systems are normally linked together to form a
network.
Minicomputers

• Have relatively lower speed, can handle multi-users, are smaller in


size than the mainframe computers.
• They use terminals for inputs and output. Mini computers are used
in small organizations.
• They have less memory & storage capacity than mainframe
computers.
• They offer limited range of peripherals.
• The end users can directly operate it.
• They are used for data processing.
Cont…

• It is a midsize multi-processing system capable of supporting up


to 250 users simultaneously.
Mainframe Computers

• Smaller than in size and capacity, lower in speed & memory


capacity than the super computers.
• They are multi-user systems and handle hundreds of users,
usually used in large organizations.
• The mainframe computers are multi terminal computers, which
can be shared simultaneously by multiple users.
• Mainframe computers can be used by as many as hundreds or
thousands of users at the same time.
Cont…
• They are big computer systems sensitive to temperature, humidity,
dust etc.
• Qualified & trained operators are required to operate them.

• They have wide range of peripherals attached.

• They have large storage capacity.

• They can use wide variety of software’s.

• They are not user friendly.

• They can be used for more mathematical calculations.

• They are installed in large commercial places or government


organizations
Cont…

•. Mainframe executes many programs concurrently and supports


many simultaneous execution of programs.
Super Computers

• Are the fastest, largest and most potential type of computer.


• They have speed of hundreds of millions of operations per second.
• They are multi-user systems in intercontinental range. They can carry
out enormously complex scientific calculations.
• They are used to process huge amount of data and are commonly used
in space technology centers, meteorology stations, and astronomical
observatories, intercontinental communications, airline organizations.
• Only scientists and mathematicians can operate them.
• They are used for weather forecasting, animation graphics etc.
Cont…

• Supercomputers are very expensive and are employed for specialized


applications that require immense amount of mathematical calculations
(number crunching).
Applications of Computer
• Learning Aids:
– Example: learning toys, programs range from simple arithmetic to calculus,
from English grammar to creative writing and foreign language, and from basic
graphics to engineering design models,)
• Entertainment:
Examples: Games, Watching Movies, listening songs, photos, animations etc.

• Commercial or business applications


– Text processing
– Accounting and Finance management
– Inventory control
– Database management
• Shopping from Home
– Individual may now shop by computer in the comfort of their home.
Cont…
• Scientific – engineering and research applications
– Space technology
– Meteorological observatory systems
– Astronomical investigations
– Design of machines
• Household Control
– For example: Security systems, refrigerators, washers, stereos, and
televisions
• Weather and Environment
• Transportation :- Many aircraft can fly under the control of the
computer; in this situation, the captain simply serves as a manger by
telling the computer what to do.
Chapter Two

Components of Computer System


Introduction

• System is a group of components, consisting of subsystems or


procedures that work in a coordination fashion to achieve
some objective.
• A computer system composed of components that are
classified either as Computer hardware or Computer software.
Computer Hardware

• Computer hardware is the physical components that


a computer system requires to function.
• The hardware part of a computer system is composed of a number
of interacting physical parts based on the need of the information
flow.
• It is the general term for the physical devices that carry out the
activities of capturing, processing, storing, and communicating
data and information.
• The computer system consists of four hardware components:
Input devices

• An input device is any machine or device that feeds data


into a computer.
• Input devices are the part of computer hardware that is
used to convert data or information into electronic
machine-readable form.
• Gets information from the user to the computer

• Reads information from input media and enters to the


computer in a coded form.
Cont…

• Some of input devices are:-


Keyboard
Mouse
Voice recognition devices
Scanner
Digital computer cameras
Microphone
Central Processing Unit
• The central processing unit (CPU) has two roles: coordinating
all computer operations and performing arithmetic and logical
operations on data.
• The CPU follows instructions in computer programs to
determine which operations to carry out and in what order.
• It then transmits control signals to the other computer
components.
• For example, when instructed to read a data item, the CPU sends
the necessary control signals to the input device.
Cont…

• CPU composed of three parts


– Control Unit (CU)
– Arithmetic Logic Unit (ALU)
– Registers/Memory Unit
Control Unit

• The control unit controls the flow of data within the system.
• The control unit controls and monitors communications
between the hardware attached to the computer.

• It controls the input and output of data, checks that signals


have been delivered successfully, and makes sure that data

goes to the correct place at the correct time.


Arithmetic and logic unit

• The arithmetic and logic unit (ALU) is where the CPU performs the

arithmetic and logic operations.

• Every task that your computer carries out is completed here. Even

typing into a word processor involves adding binary digits to the file,

and then calculating which pixels on the screen should change so that

you can see the characters.

• The ALU’s operations fall in to two parts:

– the arithmetic part, which deals with calculations, eg 1 + 2 = 3

– the logic part, which deals with any logical comparisons, eg 2>1
Registers

• The immediate access store is where the CPU holds all


the data and programs that it is currently using.
• You can think of it like the numbers typed into a
calculator – they are being stored inside the calculator
while it processes the calculations.
• The immediate access store is often referred to as the
registers in the CPU
3. Storage Devices

• A storage device is used in the computers to store the data.


• Provides one of the core functions of the modern computer.
Types of Storage
• There are four type of storage:
• Primary Storage
• Secondary Storage
• Tertiary Storage
• Off-line Storage
Primary Storage

• Also known as main memory.


• Main memory is directly or indirectly connected to the central
processing unit via a memory bus.
• The CPU continuously reads instructions stored there and
executes them as required.
• Example:
– RAM
– ROM
– Cache
Storage Devices
Secondary Storage
• It is not directly accessible by the CPU.
• Computer usually uses its input/output channels to access
secondary storage and transfers the desired data using
intermediate area in primary storage.
• Example: – Hard disk
• The hard disk drive is the main, and usually largest, data storage
device in a computer.
• It can store anywhere from 160 gigabytes to 2 terabytes.
Storage Devices
Tertiary Storage
• Typically it involves a robotic mechanism which will mount (insert)
and dismount removable mass storage media into a storage device.
• It is a comprehensive computer storage system that is usually very
slow, so it is usually used to archive data that is not accessed
frequently.
• This is primarily useful for extraordinarily large data stores, accessed
without human operators.
• Examples: – Magnetic Tape , Optical Disc
Storage Devices

Off-line Storage
• Also known as disconnected or removable storage.
• Is a computer data storage on a medium or a device that is not
under the control of a processing unit.
• It must be inserted or connected by a human operator before a
computer can access it again.
• Examples: – Floppy Disk , USB Flash drive , Memory card
4. Output Devices

• An output device is any piece of computer hardware


equipment which converts information into human-readable
form. It can be text, graphics, tactile, audio, and video.
• Sends information from computer to the user
• Decodes information and presents it to the user
• Parts of the computer that are designed to receive output from
the computer and provide it to the user.
Cont..

• The key distinction between an input device and an output


device is that an input device sends data to the computer,
whereas an output device receives data from the computer.
• For example, using a microphone to record a podcast is an
example of using an input device.
• Listening to the recorded podcast through a connected
speaker is an example of using an output device
Types of Output Devices

Monitor
• The monitor is the most common output device. It displays
information in a pictorial form or commonly referred to as pixels.
• More the number of pixels, the better is the picture clarity and
sharpness.
• It includes a screen, circuitry, and the box, in which the circuit is
enclosed. The user can view the processed data on the screen.
• There are two types of Monitor screens. They are as follows:-
– Cathode Ray Tube Monitor (CRT)
– Flat Panel Screen Monitors
Printer

• A printer is a hardware device that produces a hard copy


version of the processed data from the computer.
• It is a device that accepts texts and graphic output from the
computer and transmits the image data to the printer, usually
on a paper
• Printers are the most common output device to print text or
photos. Some printers can print only in black and white, but
today, almost all the printers can print monochrome and color
prints.
Head Phones

• The headphones or called as earphones are hardware output devices


that are either plugged in the computer or can be wireless.
• We can listen to audio or watch the video privately without
disturbing others. Headphones come in various shapes and sizes.
• Some headphones utilize Styrofoam or soft fabric around the
earpiece to provide a comfortable fit.
• The most common type of headphones is earbuds, which are small
shaped in a specific manner that fits inside the ear.
Computer Speakers

• The computer speakers are the most common output devices


used with a computer. The speakers receive audio as an input
from the computer or a sound card then this input may be either
in analog or digital form.
• Most computer speakers have internal amplifiers which can
increase the volume or the amplitude of the sound based on users
requirement.
• External speakers are connected to a computer only if a user
requires louder sounds, more bass, or surround sound.
Projector

• A projector is an output device that can take images produced


by a computer and project them onto a screen or surface.
• Projectors are used in classrooms, offices, auditoriums, and
also at places of worship, as it enables a group of people to
watch videos, presentations, or pictures generated from a
single computer.
• The projectors used nowadays are known as video projectors.
The projectors can produce still images or moving images.
Braille Reader

• A Braille Reader is an electronic device that allows a blind


person to read the text displayed on the monitor screen.
• The computer sends a text to the Braille Reader, where it
translated into Braille format and displayed by raising
rounded pins through a flat surface.
• Braille readers are available in various sizes like large
units of keyboard size for computer and small units for
laptops and tablets.
2. Computer Software
• Computer hardware is virtually useless without computer
software.
• Software is a part of computer system that contains data or set of
instructions. It is considered as set of programs, which is then
executed to perform a well-defined function.
• A program consists of a set of instructions which are used to
perform a specific task in an orderly manner.
• There are two types of software −
– System Software
– Application Software
System Software

• The system software is a group of programs designed to operate, control,


perform and extend the processing capabilities of the computer itself.

• System software is generally prepared by the computer manufacturers.

• These software products contain mainly programs which are written in low-
level languages, understandable language where they interact with the
hardware at a very basic level.

• System software acts as the interface between the hardware and the end
users.

• Some examples of system software are Operating System, Compilers,


Interpreter, Assemblers, etc.
System Software

Operating systems
• The most important system software package for any computer is
its operating system.
• Every computer system runs under the control of an operating
system.
• Operating systems for computers that are shared by many users
are considerably more complex than operating systems for
personal computers.
System Software

• What Does an Operating System Do?

 Schedules programs for execution on the processor

 Allocates the memory required for each program

 Assigns the necessary input and output devices

 Manages the data and program files stored in secondary storage

 Maintains file directories and provides access to the data in the


files
 Interacts with the users
Application Software

• Application software products are specially designed to satisfy the


needs of the user to perform the functions properly.
• All software applications prepared in the computer lab can come
under the category of Application software.
• Application software may consist of a single program or series of
programs often called a software package.
• Examples :-Microsoft Word, Microsoft Excel, Microsoft
PowerPoint, Payroll Software, Student Record Software,
Inventory Management Software, Income Tax Software.
Chapter Three

Problem Solving Using Computers


Introduction

• Computer problem solving is a complicated process requiring


careful planning and attention to detail.
• The vehicle for the computer solution to a problem is a set of
explicit and unambiguous instructions called a program and
expressed in a programming language.
• A program is a sequence of instructions that determine the
operations to be carried out by the machine in order to solve a
particular problem.
Stages of Program Development

• Analysis :-requires a thorough understanding of the problem at


hand and analysis of the data and procedures needed to achieve
the desired result.
• The stage focus on what must be done rather than how to do it
– What input data are needed to the problem?
– What procedures needed to achieve the result?
– What outputs data are expected?
Cont…
• Algorithm design and flowchart

• An algorithm is a finite set of steps which, if followed accomplishes a


particular task.
• An algorithm is a map or an outline of a solution which shows the
precise order in which the program will execute individual functions to
arrive at the solution.
• Algorithm can be expressed in Narrative (pseudocode) and Flowchart.

• A flowchart consists of an ordered set of standard symbols (mostly,


geometrical shapes) which represent operations, data flow or equipment.
Basic sets of flow chart symbols

.
Examples
1) Algorithm to add two numbers.
Step 1: START
Step 2: Read two numbers n1 and n2.
Step 3: Sum ← n1 + n2
Step 4: Print Sum
Step 5: STOP
2) Algorithm to find largest number from two numbers.
Step 1: START
Step 2: Read n1 and n2.
Step 3: If n1 > n2, goto step 5
Step 4: Big←n2, goto step 6
Step 5: Big ← n1
Step 6: Print Big
Step 7: STOP
Examples of flow chart

1. Draw a flowchart to add two numbers 2. A Flowchart to find largest of two numbers
Cont…

• Coding :-The flowchart is independent of programming


language. Now at this stage we translate each step described in
the flowchart (algorithm description) to an equivalent
instruction of target programming language, that means, for
example if we want to write in JAVA program language, each
step will be described by an equivalent JAVA instruction
(Statement).
Cont..
• Implementation:-Once the program is written, the next step is to
implement it.
• Program implementation involves three steps, namely, debugging
(the process of removing errors), testing (a check of correctness),
and documenting the program (to aid the maintenance of a program
during its life time).
• Maintenance
• There are many reasons why programs must be continually
modified and maintained, like changing conditions, new user needs,
previously undiscovered bugs (errors).
• Maintenance may involve all steps from requirements analysis to
testing.
Individual Assignment
Construct an algorithm and a flowchart for the following:

1. To find the area of a circle where the radius is provided

by the user.

2. To find the average of two numbers given by the user.

3. To check whether a given character is vowel or not.

4. To swap the contents of two variables using a third

variable.

5. To determine if a whole number is odd or even.


Chapter Four
Fundamentals of C++ Programming Languages
Basic Program Structure

•Given below is the basic structure of any program written in


C+ + which when executed displays the letters “Hello World”
on the display unit.
•// First C+ + Program --- Comment Line
•# include <iostream> --- inclusion of header files called
•using namespace std; --- using standard
•int main ( ) --- Name of the main function or start of main ()
function.
•{ --- Indicates beginning of main ()
•cout<< “Hello World”; --- Executable output statement.
•return 0; --- Program execute successfully
•} --- End of main ()
Comments

• Single line comment: C++ introduces single line


comment // (double slash). Comments starts with a double
slash symbol and terminate at the end of line.
• Example: c=5.0/9*(f-32); //conversion formula.
• Multi line comment: Multi line comment symbols are /*,
*/.
E.g : /* this is an example of C++ program to illustrate
some of its features */
• The comment lines in the program are ignored by the
compiler.
Variable

• Variables are often referred to as named memory locations to


store a determined value.

• The value of a variable may vary throughout program means


that, a variable may take different values at different times
during execution.

• Each variable needs an identifier that distinguishes it from the


others, for example, in the code a=5 the variable identifier is ‘a’,
but we could have called the variables with any names we
wanted to invent, as long as they were valid identifiers.
Identifiers

• A valid identifier is a sequence of one or more letters, digits or


underscore characters (_).
• The length of an identifier is not limited, although for some compilers
only the 32 first characters of an identifier are significant (the rest are
not considered).
• Neither spaces nor marked letters can be part of an identifier.

• Variable identifiers should always begin either with a letter or


underscore character (_). They can never begin with a digit.
• Our own identifiers cannot match any key word of the C++ language nor
your compiler's specific ones since they could be confused with these.
Data Type

• A data type, in programming, is a classification that specifies which


type of value a variable has and what type of mathematical,
relational or logical operations can be applied to it without causing
an error.
Declaration of Variables

• In order to use a variable in C++, we must first declare it specifying


the data type.
• The syntax to declare a new variable is to write the data type
specifier that we want (like int, short, float...) followed by a valid
variable identifier.
– For example:
– int a; declares a variable of type int with the identifier a
– float mynumber; declares a variable of type float with the
identifier mynumber
Constant

• Constants are expressions with a fixed value.


• Literals
• Literals are used to express particular values within the source
code of a program. For example, when we wrote: a = 5 ; the 5 in
this piece of code was a literal constant.
• Literal constants can be divided in Integer Numerals, Floating-
Point Numerals, Characters, Strings and Boolean Values.
Defined constants (#define)

• To define our own names for constants that we use very often
without having to resort to memory consuming variables, simply by
using the #define preprocessor directive. Its format is: #define
identifier value
– For example: #define PI 3.14159
– #define NEWLINE '\n'
• This defines two new constants: PI and NEWLINE. Once they are
defined, you can use them in the rest of the code as if they were any
other regular constant.
• The #define directive is not a C++ statement but a directive for the
preprocessor; therefore, it assumes the entire line as the directive
and does not require a semicolon (;) at its end.
Declared constants (const)

• With the const prefix you can declare constants with a specific
type in the same way as you would do with a variable:
– const int PI = 3.14159;
– const char tab = '\t';
• Here, PI and tabulator are two typed constants.
• They are treated just like regular variables except that their
values cannot be modified after their definition.
Introduction to Strings

• Variables that can store non-numerical values that are longer than one single character are

known as strings.

• A first difference with fundamental data types is that in order to declare and use objects

(variables) of this type we need to include an additional header file in our source code:

<string>

#include<iostream>
 Both initialization formats are valid
using namespace std;
with strings:
#include <string> o string mystring = "This is a string";
int main () o string mystring ("This is a string");
{
string mystring = "This is a string";
cout << mystring;
return 0;
}
Operators

• An operator is a symbol that tells the computer to perform certain


mathematical (or) logical manipulations.
• Operators are used in programs to manipulate data and variables.
• C++ operators can be classified into number of categories. They
include
– Arithmetic operators.
– Relational operators.
– Logical operators.
– Assignment operators.
– Increment / Decrement operators.
– Conditional operators.
– Bitwise operators
Cont…

• Arithmetic operators: C++ provides all the basic arithmetic operators

like add (+), subtract (-), multiply (*), divide (/), and mod (%).mod

gives remainder of division.


– Eg.. For mod: if a = 10; b = 3; c = a % b;  c = 1;

• Relational operators: These are the operators which relate the

operands on either side of them like less than (<), less than or equal

(<=), equal (==), Greater than (>), Greater than or equal (>=)and not

equal(!=). The result of a relational operation is a Boolean value that

can only be true or false, according to its Boolean result.


Cont…

• Logical operators: C++ has the following three logical operators. &&
(meaning logical AND), || (logical OR), ! (logical NOT).
E.g:( (5 == 5) && (3 > 6) )
// evaluates to false ( true && false ).

((5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).


• Assignment operators: used to assign the result of an expression to a
variable and the symbol used is ‘= ‘.
– The part at the left of the assignment operator (=) is known as the lvalue
(left value) and the right one as the rvalue (right value). The lvalue has to
be a variable whereas the rvalue can be either a constant, a variable, the
result of an operation or any combination of these.
– It is of 3 types:.
– Simple assignment E.g: a = 9;
– Multiple assignment E.g: a = b = c = 36; a = 2 + (b = 5);
– Compound assignment E.g: a + = 15; (add 15 to a .Equivalent a =a +15;)
Cont…

• Auto increment / decrement (+ + / - - ): used to automatically


increment and decrement the value of a variable by 1. There are 2
types of incrementing or decrementing.
Prefix auto increment / decrement --- Adds /subtracts 1 to the operand &
result is assigned to the variable on the left.
Eg. : a = 5; a=5;
b=++a; b=--a;
Result a=b=6;a=b=4;
Postfix auto increment / decrement --- This first assigns the value to the
variable on the left & then increments/decrements the operand.
Eg. : a = 5; a=5;
b=a++; b=a--;
Result b=5, a=6 b=5,a=4;
Generally a=a+1 can be written as ++a, a++ or a+=1. Similarly a=a-1 can
be written as a--, --a or a -= 1.
Cont…

Conditional operator (ternary operator):


• Conditional expressions are of the following form.
• exp1 is evaluated first. If the result is true then exp2 is
evaluated else exp3 is evaluated. It is this evaluated value that
becomes the value of the expression.
• For example, consider the following statements.
• a=10; b=15; x = (a>b)? a: b; In this example x will be assigned
the value of b
Chapter Five
Flow of Control Statements
Flow of Control

• A running program spends all of its time executing instructions or


statements in that program.
• The order in which statements in a program are executed is called
flow of that program.
• Programmers can control which instruction to be executed in a
program, which is called flow control.
• This term reflects the fact that the currently executing statement
has the control of the CPU, which when completed will be
handed over (flow) to another statement.
• Flow control in a program is typically sequential, from one
statement to the next.
Cont…

• But we can also have execution that might be divided to


other paths by branching statements. Or perform a block
of statement repeatedly until a condition fails by
Repetition or looping.
• Flow control is an important concept in programming
because it will give all the power to the programmer to
decide what to do to execute during a run and what is not,
therefore, affecting the overall outcome of the program.
Selection Statements

• Selection statements are statements in a program where there are points at


which the program will decide at runtime whether some part of the code
should or should not be executed.
• There are two types of selection statements in C++, which are the “if
statement” and the “switch statement”
• The if Statement
– It is sometimes desirable to make the execution of a statement
dependent upon a condition being satisfied.
– The different forms of the ‘If” statement will be used to decide
whether to execute part of the program based on a condition which
will be tested either for TRUE or FALSE result.
– The different forms of the “If” statement are:
• The simple if statement
• The If else statement
• The if else if statement
The simple if statement

• The simple if statement will decide only one part of the


program to be executed if the condition is satisfied or
ignored if the condition fails.
 The General Syntax is:
if (expression)
statements;

• In any “if” statement, first the “expression” will be evaluated and if the
outcome is non zero (which means TRUE), then the “statements” is
executed. Otherwise, nothing happens (the statement will not be
executed) and execution resumes to the line immediately after the “if”
block.
The If else statement

• Another form of the “if” is the “if …else” statement.


– The “if else” statement allows us to specify two alternative
statements:
• One which will be executed if a condition is satisfied and
• Another which will be executed if the condition is not satisfied.
• The General Syntax is:
if (expression)
statements1;
else
statements2;

• First “expression” is evaluated and if the outcome is none zero (true), then “statements1” will be executed.
Otherwise, which means the “expression” is false “statements2” will be executed.
The “if else if” statement

• The “if else if” statement allows us to specify more than two alternative
statements each will be executed based on testing one or more
conditions. if (expression1)
• The general syntax is: statements1;
else if(expression2)
statements2;
..
else if(expressionN)
statementsN;
else
statements

• First “expression1” is evaluated and if the outcome is none zero (true), then “statements1” will be executed.
Otherwise, which means the “expression1” then “expression2” will be evaluated: if the output of expression2 is
True then “statements2” will be executed otherwise the next “expression” in the else if statement will be executed
and so on.
• If all the expressions in the “if” and “else if” statements are False then “statements” under else will be executed.
Nesting If statements within another if statement

• One or more if statements can be nested with in another if statement.


• The nesting will be used to test multiple conditions to perform a task.
• It is always recommended to indent nested if statements to enhance
readability of a program.
• The General Syntax might be:- if (expression1)
{
if (expression2)
statementsN;
else
statementsM;
}
else
{
if (expression3)
statementsR;
else
statementsT;
}
Cont..

• StatementsN will be executed if and only if “expression1” and


“expression2” are evaluated and if the outcome of both is none
zero (TRUE).
• StatementsM will be executed if and only if “expression1” is
TRUE and “expression2” is FALSE.
• StatementsR will be executed if and only if “expression1” is
FALSE and “expression3” is TRUE.
• StatementsT will be executed if and only if “expression1” is
FLASE and “expression3” is FALSE.
The Switch Statement

• Another C++ statement that implements a selection control flow is


the switch statement (multiple-choice statement).
• The switch statement provides a way of choosing between a set of
alternatives based on the value of an expression.:
• The switch statement has four components: switch(expression)
{
• Switch case constant1:
• Case
statements;
• Default … …..
case constant n:
• Break
• Where Default and Break are Optional statements;
default:

statements;
}
Cont…

• Expression is called the switch tag and the constants preceding


each case are called the case labels.
• The output of “expression” should always be a constant value.
• First expression is evaluated, and the outcome, which is a
constant value, will compared to each of the numeric constants in
the case labels, in the order they appear, until a match is found.
• Note, however, that the evaluation of the switch tag with the case
labels is only for equality
• The statements following the matching case are then executed.
• each case may be followed by zero or more statements (not just
one statement).
Repetition Statements

• Repetition statements control a block of code to be executed


repeatedly for a fixed number of times or until a certain condition
fails.
• There are three C++ repetition statements:
– The For Statement or loop
– The While statement or loop
– The do…while statement or loop
• The for statement / loop
– The “for” statement (also called loop) is used to repeatedly
execute a block of instructions until a specific condition fails.
– The General Syntax is: for(expression1 ; expression2 ; expression3)
statements;
Cont..

• The for loop has three expressions:


– expression1: is one or more statements that will be executed only
once and before the looping starts.
– Expression2: is the part that decides whether to proceed with
executing the instructions in the loop or to stop. Expression2 will be
evaluated each time before the loop continues. The output of
expression2 should be either non zero (to proceed with the loop) or
zero (to stop the loop) to represent true and false output respectively.
– Expression3: is one or more statements that will be executed after
each iteration.
– Thus, first expression1 is evaluated and then each time the loop is
executed, expression2 is evaluated. If the outcome of expression2 is
non zero then statements is executed and expression3 is evaluated.
Otherwise, the loop is terminated.
Cont..

• The general format can be expressed as follows for the sake of


clarity:
for(initialization ; condition ; increase/decrease)
statement;
• Steps of execution of the for loop:
– Initialization is executed. (will be executed only once)
– Condition is checked, if it is true the loop continues,
otherwise the loop finishes and statement is skipped.
– Statement is executed.
– Finally, whatever is specified in the increase or decrease
field is executed and the loop gets back to step two.
The while statement

• The while statement (also called while loop) provides a way of


repeating a statement or a block as long as a condition holds / is
true. while(expression)
• The general form of the while loop is: statements;

• First expression (called the loop condition) is


evaluated. If the outcome is non zero then statement
(called the loop body) is executed and the whole
process is repeated. Otherwise, the loop is terminated.
Do…while loop

• The do statement (also called the do while loop) is similar to the while
statement, except that its body is executed first and then the loop
condition is examined.
• In do…while loop, we are sure that the body of the loop will be
executed at least once. Then the condition will be tested.
• The general syntax is:
do
{
statement;
}
while(expression);
Jumping Statements

• The continue statement


• The break statement
• The goto statement
• The continue statement
• The continue statement terminates the current iteration
of a loop and instead jumps to the next iteration.
• It is an error to use the continue statement outside a
loop.
• In while and do while loops, the next iteration
commence from the loop condition.
• In a “for” loop, the next iteration commences from the
loop’s third expression
The break statement

• A break statement may appear inside a loop (while, do, or for)


or a switch statement. It causes a jump out of these constructs,
and hence terminates them.
• Like the continue statement, a break statement only applies to
the “loop” or “switch” immediately enclosing it. It is an error
to use the break statement outside a loop or a switch statement.
Chapter Six
Introduction to Functions
What is Function?

 C ++ enables its programmers to break up a program into segments commonly known as functions, each of

which can be written more or less independently of the others.


 A function is a group of statements that together perform a task.
 Every function in the program is supposed to perform a well-defined task.
 Every C++ program has at least one function, which is main(), and all the most trivial programs can define
additional functions.

 A function is a block of code designed to tackle a specific problem.


 One of the best ways to tackle a problem is to start with the overall goal,
then divide this goal into several smaller tasks. You should never lose sight
of the overall goal, but think also of how individual pieces can fit together
to accomplish such a goal.
 Function makes a program much easier to read, test and debug
Cont…

 In the figure, we can see that main() calls a function named func1().
 Therefore, main() is known as the calling function and func1() is known
as the called function.
 The moment the compiler encounters a function call, the control jumps
to the statements that are a part of the called function.
 After the called function is executed, the control is returned to the calling
program.
Cont…

 The main() function can call as many functions as it wants and as many times
as it wants.
 For example, a function call placed within a for loop, while loop, or do–while
loop may call the same function multiple times till the condition holds true.
 Not only main(), any function can call any other function.
Why?

 Dividing the program into separate well-defined functions facilitates each function to be

written and tested separately.

 Understanding, coding, and testing multiple separate functions is easier than doing the

same for one big function.

 When a big program is broken into comparatively smaller functions, then different

programmers working on that project can divide the workload by writing different

functions.

 Like C/C++ libraries, programmers can also write their own functions and use them from

different points in the main program or any other program that needs its functionalities.
C++ functions generally adhere to the following rules:

1. Every function must have a name.

2. Function names are made up and assigned by the programmer following the same
rules that apply to naming variables. They can contain up to 32 characters, they must
begin with a letter, and they can consist of letters, numbers, and the underscore (_)
character.

3. All function names have one set of parenthesis immediately following them. This
helps you (and C++ compiler) differentiate them from variables.

4. The body of each function, starting immediately after parenthesis of the function

name, must be enclosed by braces .


Components of Function

 Function declaration :-Before using a function, the compiler must know the
number of parameters and the type of parameters that the function expects to
receive and the data type of value that it will return to the calling program.
 Placing the function declaration statement prior to its use enables the compiler to
make a check on the arguments used while calling that function.
 It is the interface of a function (also called function prototype) specifies how it may
be used.
 Function declaration is required when you define a function in one source file and
you call that function in another file. In such case, you should declare the function
at the top of the file calling the function.
return_type function_name( parameter list );
Cont…

 return_type:-specifies the data type of the value that will be returned to the calling
function as a result of the processing performed by the called function.

 Some functions perform the desired operations without returning a value. In this case,
the return_type is the keyword void.
 Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters: A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
 Parameter names are not important in function declaration only their type is required.
Cont…

 A function definition consists of two parts: interface (prototype or function


header ) & body.

 The function header is same as the function declaration. The only difference

between the two is that a function header is not followed by a semi-colon.


 Function Body − The function body contains a collection of statements that
define what the function does. Syntax of function definition
return_type function_name( parameter list )
{
body of the function
}

 If function definition is done before the main function, then there is no need to put
the prototype, otherwise the prototype should be script before the main function
starts
Function Calling

 Calling a function means making the instruction of the function to be executed.

 While creating a C++ function, you give a definition of what the function has to do.

 When a function call is executed, the arguments are first evaluated and their

resulting values are assigned to the corresponding parameters.

 The function call statement invokes the function.

 When a function is invoked, the compiler jumps to the called function to execute

the statements that are a part of that function.

 Once the called function is executed, the program control passes back to the calling

function.
Function calling

The following points are to be noted while calling a function:


 Function name and the number and the type of arguments in the function call must be
same as that given in the function declaration and the function header of the function
definition.
 Names (and not the types) of variables in function declaration, function call, and header
of function definition may vary.
 Arguments may be passed in the form of expressions to the called function. In such a
case, arguments are first evaluated and converted to the type of formal parameter and
then the body of the function gets executed.
 If the return type of the function is not void, then the value returned by the called
function may be assigned to some variable as given below.
variable_name = function_name(variable1, variable2, ...);
Example

1. Write a program to find whether a number is even or odd using functions.

int evenodd(int); Function Declaration


int main()
{
int evenodd(int a) // Function header
int num, flag; {
cout<<"\n Enter the number : "; // Function body
if(a%2 == 0)
cin>>num; return 1;
flag = evenodd(num); Function calling else
if (flag == 1) retun 0;
}
cout<< num <<" IS EVEN";
else
cout<< num<<“IS ODD";
return 0;
}
Example

2. Write a function which calculates the area of rectangle. Note the dimensions of
the polygon should be provided from the user.

void AreaRectangle (int l,int w);


void main()
{
int length,width,area;
cout<<Enter Length and width of rectangle”;
cin>>length>>width;
AreaRectangle(length,width);
}
void AreaRectangle (int l,int w)
{
int area;
area=l*w;
cout<<“The area of rectangle is=”<<area;
}
Example 2

3 . Write a function which return the maximum of two numbers. Note that the numbers should be
provided from the user.
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
void main()
{
int FirstNum,SecondNum, maximum;
cout<<“Enter the two numbers”;
cin>> FirstNum>>SecondNum;
maximum=max(FirstNum,SecondNum);
cout<<“Maximum of two numbers is=”<<maximum;
}
Home Work

.
3 Write C++ program using function which perform all arithmetic operations for two
numbers.
Note:- 1. Use different functions for each operation
2. Check divide by zero exception (If denominator is zero your program display
error message).
3. Your program display menu for the user to select the operation.
Function Parameters

 A parameter is like a placeholder.


 Arguments or parameters are divided into two: Formal and Actual parameters
o When a function is called some parameters are written within the parenthesis . These
are know as actual parameters.
eg AreaRectangle (length, width);
o Formal parameters are those who are written in the function header.

eg void AreaRectangle (int length,int width);


 The formal parameter and the variable which declare inside the body of function are
created when function called and they exist only upto control remain on the function.
 We can give same name for actual and formal parameters but their implementation is
different.
 If in any function there is no formal parameters then we can write void instead.
Passing Arguments

There are 2 ways to pass arguments into a function

1. Passing By value :- The value of the actual parameter is passed to formal parameters when we

call the function.

• In this method, the called function creates new variables to store the value of the arguments

passed to it.

• Therefore, the called function uses a copy of the actual arguments to perform its intended task.

• If the called function is supposed to modify the value of the parameters passed to it, then the

change will be reflected only in the called function.


Cont…

• In the calling function, no change will be made to the value of the variables. This is because

all the changes are made to the copy of the variables and not to the actual variables.
void add(int n);
int main()
{

int num = 2;
cout<<"\nThe value of num before calling the function "<< num;
add(num);
cout<<"\nThe value of num after calling the function = "<<num;
return 0;
}
void add(int n)
{
n = n + 10;
cout<<"\n The value of num in the called function = "<< n;
}
Cont…

Output
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 2
 Following are the points to remember while passing arguments to a function using the call-by
value method:
 When arguments are passed by value, the called function creates new variables of the
same data type as the arguments passed to it.
 The values of the arguments passed by the calling function are copied into the newly
created variables.
 Values of the variables in the calling functions remain unaffected when the arguments are
passed using the call-by-value technique.
Cont…

2. Passing By Reference

 In this method, we declare the function parameters as references rather than normal variables.

 When this is done, any changes made by the function to the arguments it received are also

visible in the calling function.

 To indicate that an argument is passed using call by reference, an asterisk (*) is placed after

the type in the parameter list.

 A reference parameter, on the other hand, receives the argument passed to it and works on it

directly.

 Any change made by the function to a reference parameter is in effect directly applied to the

argument.
Cont…

void add(int *n);


int main()
{
int num = 2;
cout<<"\nThe value of num before calling the function "<< num;
add(&num);
cout<<"\nThe value of num after calling the function = "<<num;
return 0;
}
void add(int *n)
{
*n = *n + 10;
cout<<"\n The value of num in the called function = "<< n;
} Output
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 12
Exercise :- What is the output of this program ?

void swap_call_val(int, int); void swap_call_val(int a, int b)


void swap_call_ref(int *, int *); {
int main() int temp;
temp = a;
{
a = b;
int a=1, b=2, c=3, d=4; b = temp;
cout<<"\n In main() a = "<<a<<" and b = "<<b; cout<<"\n In function (Call By Value Method) – a = "<<a <<"and b = "<<b;
swap_call_val(a, b); }
cout<<"\n In main() a = "<<a<<" and b = "<<b; void swap_call_ref(int *c, int *d)
cout<<"\n\n In main() c = "<<c<<" and d = "<<d; {
int temp;
swap_call_ref(&c, &d);
temp = *c;
cout<<"\n In main() c =“<<c <<"and d =“<<d; *c = *d;
return 0; *d = temp;
} cout<<"\n In function (Call By Reference Method) – c ="<<c<<" and d = "<<d,
}
Global versus local variables

1. Local variables:
 Variables that are declared inside a function or block are local variables.

 They can be used only by statements that are inside that function or block of code.
 Local variables are not known to functions outside their own.

2. Global variables;
 Global variables are defined outside of all the functions, usually on top of the
program.
 The global variables will hold their value throughout the life-time of your program.

 A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration.
Example
void sum ();
int c; // global variable declaration: void sum()
{
int main () {
int x=25;
// local variable declaration:
int y=45;
int a, b,c1; c1=x+y; // error
// actual initialization cout<<“The sum is =”<<c1;
a = 10; }
b = 20;
c = a + b;
cout << c;
sum();
return 0;
}
Cont…

 It’s possible to declare local and global variables of the same name.

 C++ provides the unary scope resolution operator (::) to access a global variable
when a local variable of the same name is in scope.
 The unary scope resolution operator cannot be used to access a local variable of
the same name in an outer block.
 A global variable can be accessed directly without the unary scope resolution
operator if the name of the global variable is not the same as that of a local
variable in scope.
Example

#include <iostream>
using namespace std;
int num =15;
int main()
{
double num=77.5;
// display values of local and global variables
cout << "Local double value of number = " <<num;
cout<< "\nGlobal int value of number = " <<::num << endl;
} // end main
Output
Local double value of number =77.5
Global int value of number = 15
Const Argument

 In C++ we can declare constant like the following

const datatype variable _name ;


 const is a reserved word and any variable declared with this keyword is can’t be
modified.
 While trying to modify any constant argument the compiler gives syntax error
which detect that the argument is non-modifiable value.
eg
int Add (const int c)
{
c=c+3;// error
}
Defualt argument

 A function in C++ can be called without specifying all its arguments.

 In such cases the function declaration must provide default values for those
arguments that are not specified.
 The compiler look at the prototype to see how many arguments a function uses
and alerts the program for possible default values.
 Default argument must be added from right to left, we can not provide a default
value to a particular argument in the middle or first of an argument list.

Eg float Add(int a,int b=2,int c=5);

float Add(int a,int b=2,int c); // illegal


Example

1. Write a function which calculates A where A=P*(1+r/100) n for data p,r


and n having fixed value of 50.
float func(float p,int n,float r=50);
void main()
{ // Function definition
float p,r,A; float func(float p,int n,float r)
int n;
{
cout<<“Enter the value of P and n”;
cin>>p>>n; float temp=1+r/100;
A=func(p,n); float final=p*pow(temp,n);
cout<<“The value of A for default value of r is =”<<A; return final;
}
cout<<“Enter the value of p, n and r”;
cin>>p>>n>>r;
A=func(p,n,r);
cout<<“The value of A for default value of r is =”<<A;
}
Function overloading

 Two or more functions having same name but different argument(s) are known
as overloaded functions.
 It allows the programmer to write functions to do conceptually the same thing
on different types of data without changing the name.
 The overloaded function should be different interns of number of arguments,
data type of the arguments and order of argument lists.
 If two or more functions differ only in their return types, C++ can’t overload
them.
 To be execute the compiler identifies the overloaded function based on the
difference they encounter while the function is invoked.
Example

// Overloaded functions based on argument type


int square(int x)
{
return x*x;
}
double square(double x)
{
return x*x;
}
int main()
{
cout<<"The square of integer 7 is"<<square(7);
cout<<"\nThe square of double 7.5 is"<<square(7.5);
return 0;
}
Exercise

1. Write a function which prints area of rectangle and circle using function

overloading. While developing the function the value of pi is constant.

2. What is the output of this segment code of program

int main(void)
void func1(int a, int b) {
{ int i=10,j=40;
a*=2; cout<<“i=“<<i<” and j= ”<<j<<endl;
b+=10; func1(i,j);
cout<<“a=“<<a<” and b= ”<<b<<endl; cout<<“i=“<<i<” and j= ”<<j<<endl;
func2(&i,&j);
}
cout<<“i=“<<i<” and j= ”<<j<<endl;
void func2(int *x, int *y) }
{
*x*=2;
*y+=10;
cout<<“x=“<<*x<” and y= ”<<*y<<endl;
}
3. What is the output of the program?

void printChar(int num, char ch)


#include <iostream>
{
using namespace std;
int i=0;
void printChar(int num, char ch); cout<<endl;
void printChar(char ch , int num); for(i=0;i<num;i++)
int main() cout<<ch;
{ }
printChar(10, '@'); void printChar(char ch, int num)
printChar('*', 12); {
return 0; int i=0;
} cout<<endl;
for(i=0;i<num;i++)
cout<<ch;
}
Recursion Function

 A recursive function is one that calls itself.

void message(void)
{
cout << "This is a recursive function.\n";
message();
}
 The function above displays the string "This is a recursive function.", and then calls
itself.
 The function is like an infinite loop because there is no code to stop it from repeating.

 Like a loop, a recursive function must have some algorithm to control the number of
times it repeats.
Cont…

void message(int times)


{
if (times > 0)
{
cout << "This is a recursive function.\n";
message(times ‑ 1);
}
return;
}
 The function contains an if/else statement that controls the repetition.

 As long as the times argument is greater than zero, it will display the message and
call itself again.
 Each time it calls itself, it passes times - 1 as the argument.
Cont..

 For example, let's say a program calls the function with the following statement:

Message(5);
The Recursive Factorial Function

 In mathematics, the notation n! represents the factorial of the number n. The factorial of

a number is defined as:


n! = 1 * 2 * 3 * ... * n if n > 0
1 if n = 0

 Another way of defining the factorial of a number, using recursion, is:

Factorial(n) = n * Factorial(n - 1) if n > 0


1 if n = 0

 The following C++ function implements the recursive definition shown above:
int factorial(int num)
{
if (num > 0)
return num * factorial(num - 1);
else
return 1;
}
Cont…

// Function prototype
int factorial(int);

void main(void)
{
int number;

cout << "Enter an integer value and I will display\n";


cout << "its factorial: ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial(number) << endl;
}

int factorial(int num)


{
if (num > 0)

return num * factorial(num - 1);


else
return 1;
}
Chapter Six
Introduction to Array and Structure
Outline

o Introduction to array
o Declaration and Initialization of array (1D)
o Accessing 1D array
o Strings and operations on string
o Two dimensional array
o Array manipulation
o Introduction to structure
o Structure declaration
o Arrays of structure
Introduction to array

• An array is a series of elements of the same type placed in contiguous


memory locations that can be individually referenced by adding an
index to a unique identifier.
• That means that, for example, five values of type int can be declared as
an array without having to declare 5 different variables (each with its
own identifier). Instead, using an array, the five int values are stored in
contiguous memory locations, and all five can be accessed using the
same identifier, with the proper index.
• Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
Cont..

• For example, an array containing 5 integer


values of type int called foo could be
represented as:-

• where each blank panel represents an element of the array. In


this case, these are values of type int.
• These elements are numbered from 0 to 4, being 0 the first and
4 the last; In C++, the first element in an array is always
numbered with a zero (not a one), no matter its length.
How To Declare Arrays?

 Like variables an array must be declared before being used

 To declare an array in C++, you should specify the following things

 The data type of the values which will be stored in the array

 The name of the array (i.e. a C++ identifier that will be used to access and
update the array values)
 The dimensionality of the array:

• One dimensional (i.e. list of values ),


• Two-dimension array (a matrix or a table), etc.
 The size of each dimension
INITILIAZING ONE DIMENTIONAL ARRAYS

• When we declare an array, we are just allocating space for its


elements; no values are stored in the array.
• There are three ways to store values in an array

Initialize the elements during declaration

Storing values in an array Input values for the elements from the keyboard

Assign values to individualelements


INITIALIZING ARRAYS DURING DECLARATION

 The elements of an array can be initialized at the time of declaration,


just as any other variable.
 When an array is initialized, we need to provide a value for every
element in the array.
 It is a compiler error to specify more values than there are elements in
the array.
 While initializing the array at the time of declaration, the programmer
may omit the size of the array.
– type array_name[size]={list of values};
– For example, int marks[]= {98, 97, 90};
INPUTTING VALUES FROM THE KEYBOARD

 An array can be initialized by inputting values from the keyboard.

 In this method, a while/do–while or a for loop is executed to input


the value for each element of the array.
for (int i =0,i<10;i++)
cin>>marks[i];

 We start at the index i at 0 and input the value for the first element
of the array.

 Since the array has 10 elements, we must input values for elements
whose index varies from 0 to 9.
ASSIGNING VALUES TO INDIVIDUAL ELEMENTS

 Any value that evaluates to the data type as that of the array can be
assigned to the individual array element.
 A simple assignment statement can be written as marks[3] = 100; Here,
100 is assigned to the fourth element of the array which is specified as
marks[3].
 we cannot assign one array to another array, even if the two arrays have
the same type and size.
 To copy an array, you must copy the value of every element of the first
array into the elements of the second array.
Accessing the values of an array

• The values of any of the elements in an array can be accessed just like the value
of a regular variable of the same type. The syntax is:
name[index]
• Following the previous examples in which foo had 5 elements and each of those
elements was of type int, the name which can be used to refer to each element is
the following:
• For example, the following statement stores the value 75 in the third element of
foo:
foo [2] = 75;
• and, for example, the following copies the value of the third element of foo to a
variable called x: x = foo[2];
Multidimensional arrays

• Multidimensional arrays can be described as "arrays of arrays". For example, a


bidimensional array can be imagined as a two-dimensional table made of elements,
all of them of a same uniform data type.

• jimmy represents a bidimensional array of 3 per 5 elements of type int. The C++
syntax for this is:
int jimmy [3][5];
and, for example, the way to reference the second element vertically and fourth
horizontally in an expression would be:
jimmy[1][3]
INITIALIZING TWO-DIMENSIONAL ARRAYS

 A two-dimensional array is initialized in the same way as a one-dimensional


array is initialized.

– int marks[2][3]={90, 87, 78, 68, 62, 71};


 The initialization of a two-dimensional array is done row by row

– int marks[2][3]={{90,87,78},{68, 62, 71}};


 If the array is completely initialized, we may omit the first size of the array

– int marks[][3]={{90,87,78},{68, 62, 71}};


 In order to initialize the entire two-dimensional array to zeros, simply
specify the first value as zero.
 That is, int marks[2][3] = {0};
ACCESSING THE ELEMENTS OF TWO-
DIMENSIONAL ARRAYS

 Since the two-dimensional array contains two subscripts, we will use two for
loops to scan the elements. The first for loop will scan each row in the 2D
array and the second for loop will scan individual columns for every row in
Output
the array. Eg. a[0][0]: 0
int main () { a[0][1]: 0
// an array with 5 rows and 2 columns. a[1][0]: 1
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; a[1][1]: 2
// output each array element's value a[2][0]: 2
a[2][1]: 4
for ( int i = 0; i < 5; i++ ) a[3][0]: 3
for ( int j = 0; j < 2; j++ ) { a[3][1]: 6
cout << "a[" << i << "][" << j << "]: "; a[4][0]: 4
cout << a[i][j]<< endl; a[4][1]: 8
}
return 0;
}
Strings

 Computers are widely used for word processing applications such as

creating, inserting, updating, and modifying textual data.

 Besides this, we need to search for a particular pattern within a text,

delete it, or replace it with another pattern.

 One of the most useful data types supplied in the C++ libraries is the

string.

 A string is a variable that stores a sequence of letters or other

characters,suchas"Hello"or"May10th is my birthday!".
Cont…

 In C/C++, a string is a null-terminated character array. This means that after


the last character, a character ('\0') is stored to signify the end of the
character array.

 For example, if we write char str[] = "HELLO"; then we are declaring an


array that has five characters, namely, H, E, L, L and O.

 Apart from these characters, a null character ('\0') is stored at the end of the
string.

 To store a string of length 5, we need 5 + 1 locations (1 extra for the null


character).
Cont…

 The subscript starts with a zero (0). All the characters of a string are
stored in successive memory locations
Cont…

 The statement, char str[] = "HELLO"; declares a constant string, as


we have assigned a value to it while declaring the string.
 However, the general form of declaring a string is :- char str[size];

 When we declare the string like this, we can store size–1 characters
in the array because the last character would be the null character. For
example, char mesg[100]; can store a maximum of 99 characters.
 The other way to initialize a string is to initialize it as an array of
characters. For example,

– char str[] = {'H', 'E', 'L', 'L', 'O', '\0'};


Reading and writing strings

 How to read a string entered from the keyboard?

 Make an array, that will receive the string, the target of a cin stream.

The following program reads (part of) a string entered by the user:
int main()
{
char str[80];
cout << “Enter a string: “;
cin >> str; // read string from keyboard
cout << “Here is your string: “;
cout << str;
return 0;
}
Cont…

 Problem: Entering the string “ This is a test”, the above program only
returns “This ”, not the entire sentence.
 Reason: The C++ input/output system stops reading a string when the
first whitespace character is encountered.
 Solution: Use another C++ library function, gets() or cin.getline().

 To use gets() libraray function we have to include <cstdio> as


header.
 The function takes one argument i.e name of the string.

 cin.getline() function takes the name and size of the string as argument
Cont…
# include <iostream>
using namespace std;
int main()
{
//declaring string (character array)
char text[100]={0};
cout<<"Enter a string: ";
cin.getline(text,100);
cout<<"Input string is: "<<text<<endl;
return 0;
}
STRUCTURES

 C/C++ arrays allow you to define variables that combine several data
items of the same kind, but structure is another user defined data type
which allows you to combine data items of different kinds.
 Structure is basically a user-defined data type that can store related
information (even of different data types) together.
 Structure is a collection of data items. The data item can be different
type, some can be int type, some can be float, some can be char and so
on.
 A structure is therefore a collection of variables under a single name.
 The data item of structure is called member of the structure.
Cont…
 The difference between array and structure is the element of the array
has same type, while the element of structure can be different.
 The other difference is that each element of the array referred by its
position while each element of a structure has a unique name.
Declaration of structure
struct [structure tag] struct Books
{ {
Data type 1 member 1; char title[50];
Data type 2 member 2; char author[50];
char subject[100];
Data type n member n; int book_id;
}; };
Creating Structure variable

 Structure variable can be creating in the following 3 ways.


 Structure declaration does not allocate any memory or consume storage
space.
 Like any other variable memory is allocated when a structure variable
is created.
struct [structure tag] struct [structure tag]
{ {
Data type 1 member 1; struct [structure tag] Data type 1 member 1;
Data type 2 member 2; { Data type 2 member 2;
Data type 1 member 1;
Data type n member n; Data type 2 member 2; Data type n member n;
} a, b …; };
Data type n member n; struct structure tag a,b..;
};
structure tag a,b..;
Initialization of Structures

• A structure can be initialized in the same way as other data types


are initialized.
• Initializing a structure means assigning some constants to the
members of the structure.
• When the user does not explicitly initialize the structure, then
C/C++ automatically does it.
• For int and float members, the values are initialized to zero, and
char and string members are initialized to '\0' by default.
The general syntax to initialize a structure variable is as follows:

struct struct_name
struct struct_name
{
{
data_type member_name1;
data_type member_name1; OR data_type member_name2;
data_type member_name2; data_type member_name3;
data_type member_name3; .......................
....................... };

}struct_var = {constant1, constant2, constant3,...}; struct struct_name struct_var = {constant1,


constant2, constant 3,...};

• When all the members of a structure are not initialized, it is called partial
initialization.
• In case of partial initialization, first few members of the structure are

initialized and those that are uninitialized are assigned default values.
Accessing Member of Structure

 To access any member of a structure, we use the member access


operator (.).
 The member access operator is coded as a period between the structure
variable name and the structure member that we wish to access
 The dot operator is used to select a particular member of the structure.
 Syntax : stracture _variableName.member
struct student
{ Helen
char Name[30]; 1234
int RollNo; Female
char Sex[7]; 23
int age;
} S1={“Helen”,1234,”Female”,23};
struct Books {
char title[50]; strcpy( Book2.author, "Yakit Singha");
char author[50]; strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
char subject[100];
int book_id; // Print Book1 info
} Book1; // Declare Book1 of type Book cout << "Book 1 title : " << Book1.title <<endl;
Books Book2; // Declare Book2 of type Book cout << "Book 1 author : " << Book1.author <<endl;
int main() { cout << "Book 1 subject : " << Book1.subject
<<endl;
cout << "Book 1 id : " << Book1.book_id <<endl;
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming"); // Print Book2 info
strcpy( Book1.author, "Chand Miyan"); cout << "Book 2 title : " << Book2.title <<endl;
strcpy( Book1.subject, "C++ Programming"); cout << "Book 2 author : " << Book2.author <<endl;
Book1.book_id = 6495407; cout << "Book 2 subject : " << Book2.subject
// book 2 specification <<endl;
cout << "Book 2 id : " << Book2.book_id <<endl;
strcpy( Book2.title, "Telecom Billing");
return 0;
}
Cont…

 When the above code is compiled and executed, it produces the following result

Book 1 title : Learn C++ Programming


Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Yakit Singha
Book 2 subject : Telecom
Book 2 id : 6495700
Cont…

• Memory is allocated only when we declare the variables of the


structure. In other words, the memory is allocated only when we
instantiate the structure.
• In the absence of any variable, structure definition is just a template
that will be used to reserve memory when a variable of type struct is
declared.
• Once the variables of a structure are defined, we can perform a few
operations on them.
• For example, we can use the assignment operator (=) to assign the
values of one variable to another.
Array of Structure

 Structure is collection of different data type.

 An object of structure represents a single record in memory, if we want more


than one record of structure type, we have to create an array of structure or
object.
 As we know, an array is a collection of similar type, therefore an array can be
struct structure-name
of structure type.
{
Syntax for declaring structure array datatype var1;
datatype var2;
----------
----------
datatype varN;
};

structure-name obj [ size ];


Cont…

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void main()
{
int i;
Employee Emp[ 3 ]; //Statement 1
for(i=0;i<3;i++)
{
cout << "\nEnter details of " << i+1 << " Employee";
cin >> Emp[i].Id>> Emp[i].Name>> Emp[i].Age >> Emp[i].Salary;
}
Array within Structure

 Like normal data type, structure can also store an array as well.
Syntax for array within structure
struct structure-name
{
datatype var1; // normal variable
datatype array [size]; // array variable
----------
---------- Eg. struct Student
datatype varN; {
int Roll;
}; char Name[25];
int Marks[3]; //Statement 1 : array of
structure-name obj; marks
int Total;
float Avg;
};
Cont…

void main()
{
int i;
Student S;
cout << "\n\nEnter Student Roll : ";
cin >> S.Roll;
cout << "\n\nEnter Student Name : ";
cin >> S.Name;
S.Total = 0;
for(i=0;i<3;i++)
{
cout << "\n\nEnter Marks " << i+1 << " : ";
cin >> S.Marks[i];
S.Total = S.Total + S.Marks[i];
}
S.Avg = S.Total / 3;
}
Structure within structure

 When a structure contains another structure, it is called nested structure.

 For example, we have two structures named Address and Employee.

 To make Address nested to Employee, we have to define Address structure


before and outside Employee structure and create an object of Address structure
inside Employee structure.
struct structure1
{
Syntax for structure within structure or nested -------
structure - -------
};
struct structure2
{------------
--------
structure1 obj;
};
Cont…

struct Address void main()


{ {
char HouseNo[25]; int i;
Employee E;
char City[25];
cout << "\n\tEnter Employee Id : ";
char PinCode[25]; cin >> E.Id;
}; cout << "\n\tEnter Employee Name : ";
struct Employee cin >> E.Name;
{ cout << "\n\tEnter Employee Salary : ";
int Id; cin >> E.Salary;
cout << "\n\tEnter Employee House No : ";
char Name[25]; cin >> E.Add.HouseNo;
float Salary; cout << "\n\tEnter Employee City : ";
Address Add; cin >> E.Add.City;
}; cout << "\n\tEnter Employee House No : ";
cin >> E.Add.PinCode;

}
D ! !
EN

You might also like