Module Computer Programming Edited
Module Computer Programming Edited
1|Page
2.4.3. Data types............................................................................................................... 34
2.4.4. Keyword ................................................................................................................. 36
2.4.5. Working on Variables ............................................................................................. 37
2.4.6. Constants ................................................................................................................ 39
2.4.7 Comment in Programming ........................................................................................... 40
2.4.8 Operators and Expressions ........................................................................................... 41
2.4.9 Special Printing Characters. ......................................................................................... 47
2.4.10 Input /Output Statements ........................................................................................... 48
3. 4 CHAPTER THREE: CONTROL STATEMENTS IN C++ PROGRAMMING LANGUAGE ....................... 52
3.1. Overview of Control Statement ................................................................................. 52
3.2. Selection Statements ................................................................................................. 54
3.2.1. The if Statement........................................................................................................... 54
3.2.2. The if….else Statement ............................................................................................... 57
3.2.3. The if...else if Statement: ............................................................................................. 60
3.2.4. Switch Statement ......................................................................................................... 61
3.2.5. Nested statement .......................................................................................................... 66
3.2.6. Nested if Statement...................................................................................................... 66
3.2.7. Nested if else ............................................................................................................... 68
3.2.8. Nested Switch Statements ........................................................................................... 69
3.3. Looping Statements ................................................................................................... 72
3.3.1. The „while‟ Statement................................................................................................. 73
3.3.2. The Do While Loop ..................................................................................................... 75
3.3.3. The “for” Statement .................................................................................................... 76
4.3.4. Nested Loop................................................................................................................. 81
4.4. Other Statements ........................................................................................................ 83
4.4.1. The “continue” Statement ............................................................................................ 83
4.4.2. The “break” Statement................................................................................................. 84
4.4.3. The “goto” Statement .................................................................................................. 85
4.4.4. The “return” Statement ............................................................................................... 85
4. CHAPTER FOUR: ARRAYS AND STRINGS .................................................................................................. 88
4.1. Introduction ................................................................................................................ 88
4.2. Array Definition ......................................................................................................... 89
4.3. Types of array............................................................................................................ 89
4.3.1. One Dimensional Array ............................................................................................... 89
2|Page
4.3.2. Multidimensional arrays .............................................................................................. 96
4.3. String................................................................................................................................... 98
4.3.1. String Definition .......................................................................................................... 98
4.3.2. String declaration and initialization............................................................................. 98
4.3.3. String Manipulation ..................................................................................................... 99
3|Page
Table of Figures
Figure 1-1 software development concept .................................................................................... 14
Figure 3-1 Compilation process of c++ program .......................................................................... 35
Figure 4-1 Program flow example ................................................................................................ 58
Figure 4-2 Flow diagram for if statement .................................................................................. 60
Figure 4-3 Flow diagram for If else statement.............................................................................. 63
Figure 4-4 Flow diagram for the switch statement ....................................................................... 68
Figure 4-5 flow chart for loop statement ...................................................................................... 79
Figure 4-6 flow chart for do while loop ........................................................................................ 81
Figure 4-7 Flow diagram of the for statement .............................................................................. 83
Figure 5-1 Two dimensional array .............................................................................................. 104
4|Page
List of Tables
Table 2-1 Flow chart symbols....................................................................................................... 20
Table 3-1 List of Data Types in c++ ............................................................................................. 40
Table 3-2 List of some key words used in c++ ............................................................................. 41
Table 3-3 operators and their description ..................................................................................... 48
Table 4-1 while loop trace for the example .................................................................................. 81
5|Page
COMPUTER PROGRAMMING
Computer, in simple terms, is an electronic machine that can be instructed to accept, process,
store and present data and information. It processes data (raw facts or figures) into useful
information that gives meaning to users.
Storage and retrieval – unlike other machines, computer can store data for indefinite period of time
and makes the data available for later use (retrieval).
6
COMPUTER PROGRAMMING
A. Hardware – the physical architecture of the computer or the physical devices that carry out
the activities of capturing, processing, storing and communicating data and information to
other computer.
B. Software – the program or instructions that control the system or hardware.
A. Hardware
• Input devices: - are device that feeds data into a computer and used to convert data into
electronic machine-readable form. The devices that are commonly used to input data to the
computer such as keyboard, mouse, scanner, barcode reader, microphone, digital cameras
and so on.
• Processors: - sometimes called CPU (Central Processing Unit) and executes program
instructions and performs the computer‘s processing actions. The CPU is like the human
brain and it oversee and control all of the activities of the computer. The CPU has two major
components: Control Unit (CU) and Arithmetic Logic Unit (ALU). The Control Unit issues,
selects and interprets program instructions and supervises that they are executed. It also
manages and coordinates the entire computer system. The ALU contains the electronic
circuitry that performs the two activities that underline all computing capabilities:
arithmetic operations and logic operations.
• Storage devices: - is hardware part of computer that retains data permanently or
temporarily. There are two major categories of storage devices in a computer system:
Primary storage device (RAM and ROM) and Secondary storage device (Hard disk, Floppy
discs, CD and DVD discs).
• Output devices: - are devices that accept result or information generated by the computer
and present this information to the user in a variety of different means. I t display in human
7
COMPUTER PROGRAMMING
readable form in soft copy or hard copy. Examples of output devices are monitors, speakers,
and printers.
B. Software
Software is a term for computer programs. A program is a set of instructions that enables a
computer to operate or instructions that tell the computer how to perform a specific task. Computer
software has two major categories:
a. System software: - it includes the computer's basic operating system and language
software. The term also usually covers any software used to manage the computer and the
network.
b. Application software: - it allows a user to accomplish one or more specific tasks. Typical
applications software includes office suites, business software, educational software,
databases and computer games. The following are examples of application software:
languages. A programming language is an artificial language that can be used to control the
behaviour of a machine, particularly a computer. Programming languages, like natural language
(such as Amharic), are defined by syntactic and semantic rules which describe their structure and
meaning respectively. The syntax of a language describes the possible combinations of symbols
that form a syntactically correct program. The meaning given to a combination of symbols is
handled by semantics. Many programming languages have some form of written specification of
their syntax and semantics; some are defined only by an official implementation. In general,
programming languages allow humans to communicate instructions to machines.
Available programming languages come in a variety of forms and types. Thousands of different
programming languages have been developed, used, and discarded. Programming languages can
be divided in to two major categories: low-level and high-level languages.
a common person until other languages such as assembly language was developed, which were
easier to learn and understand. Assembly language correspondences symbolic instructions and
executable machine codes and was created to use letters (called mnemonics) to each machine
language instructions to make it easier to remember or write. For example: ADD A, B – adds two
numbers in memory location A and B
Assembly language is nothing more than a symbolic representation of machine code, which allows
symbolic designation of memory locations. However, no matter how close assembly language is
to machine code, computers still cannot understand it. The assembly language must be translated
to machine code by a separate program called assembler. The machine instruction created by the
assembler from the original program (source code) is called object code. Thus assembly languages
are unique to a specific computer (machine). Assemblers are written for each unique machine
language.
The question of which language is best is one that consumes a lot of time and energy among
computer professionals. Every language has its strengths and weaknesses. For example,
10
COMPUTER PROGRAMMING
FORTRAN is a particularly good language for processing numerical data, but it does not lend itself
very well to organizing large programs. Pascal is very good for writing well-structured and
readable programs, but it is not as flexible as the C programming language. C++ embodies
powerful object-oriented features.
As might be expected in a dynamic and evolving field, there is no single standard for classifying
programming languages. Another most fundamental ways programming languages are
characterized (categorized) is by programming paradigm. A programming paradigm provides
the programmer's view of code execution. The most influential paradigms are examined in the next
three sections, in approximate chronological order.
Procedural programming specifies a list of operations that the program must complete to reach the
desired state. Each program has a starting state, a list of operations to complete, and an ending
point. This approach is also known as imperative programming. Integral to the idea of procedural
programming is the concept of a procedure call.
Procedures, also known as functions, subroutines, or methods, are small sections of code that
perform a particular function. A procedure is effectively a list of computations to be carried out.
Procedural programming can be compared to unstructured programming, where all of the code
resides in a single large block. By splitting the programmatic tasks into small pieces, procedural
programming allows a section of code to be re-used in the program without making multiple
copies. It also makes it easier for programmers to understand and maintain program structure.
Two of the most popular procedural programming languages are FORTRAN and BASIC.
frowns upon the use of global variables and instead uses variables local to each subroutine. One
of the well-known features of structural programming is that it does not allow the use of the GOTO
statement. It is often associated with a "top-down" approach to design. The top-down approach
begins with an initial overview of the system that contains minimal details about the different parts.
Subsequent design iterations then add increasing detail to the components until the design is
complete.
The most popular structured programming languages include C, Ada, and Pascal.
12
COMPUTER PROGRAMMING
13
COMPUTER PROGRAMMING
1.4.5. Coding
This step is known as programming phase. The implementation of software design starts in terms
of writing program code in the suitable programming language and developing error-free
executable programs efficiently.
1.4.6. Testing
Software testing is done while coding by the developers and thorough testing is conducted by
testing experts at various levels of code such as module testing, program testing, product testing,
in-house testing, and testing the product at user‘s end. Early discovery of errors and their remedy
is the key to reliable software.
1.4.7. Implementation
This means installing the software on user machines. At times, software needs post-installation
configurations at user end. Software is tested for portability and adaptability and integration related
issues are solved during implementation.
1.4.8. Operation and Maintenance
This phase confirms the software operation in terms of more efficiency and less errors. If required,
the users are trained on, or aided with the documentation on how to operate the software and how
to keep the software operational. The software is maintained timely by updating the code according
to the changes taking place in user end environment or technology.
This phase may face challenges from hidden bugs and real-world unidentified problems.
14
COMPUTER PROGRAMMING
1.4.9. Documentation
A well written document provides a great tool and means of information repository necessary to
know about software process. Software documentation also provides information about how to use
the product.
Objectives
After completing this chapter, you will be able to:
❖ Understand the basics and usefulness of an algorithm,
❖ Analyse various algorithms,
❖ Understand a flowchart and its advantages and limitations,
❖ Steps involved in design algorithm
15
COMPUTER PROGRAMMING
1.6.1. Algorithm
What are algorithms? Why is the study of algorithms useful? What is the role of algorithms relative
to other technologies used in computers? In this chapter, we will answer these questions.
Definition and characteristics of Algorithm
Definition:
Informally, an algorithm is any well-defined computational procedure that takes some value, or set
of values, as input and produces some value, or set of values, as output[1].
Formally: An Algorithm is a method of representing the step-by-step procedure for solving a
problem. It is a method of finding the right answer to a problem or a different problem by breaking
the problem into simple cases[2].
Characteristics of algorithm
An algorithm can be as
16
COMPUTER PROGRAMMING
In computing, there are dozens of different symbols used in flowcharting (there are even national
and international flowcharting symbol standards). Basic symbols commonly used in flowcharting
of programs are Terminal, Process, and input/output, Decision, Connector, and Predefined Process.
Symbol Name Representation Function
Rectangle or Memory
17
COMPUTER PROGRAMMING
Predefined process
Internal storage
Document
Multi-document
Or operation
Stored data
18
COMPUTER PROGRAMMING
- All flow charts start with a Terminal or Predefined Process (for interrupt programs or
subroutines) symbol.
- All flowcharts end with a terminal or a contentious loop.
Practical Exercise to develop a flow chart
1. Draw a flowchart for an algorithm that gets two numbers and prints the sum of their value
Start
Read X,Y
Z X+Y
Print Z
End
2. Write a flowchart for finding the greater number between two numbers.
Start
Read A,B
False
True
If A>B
Print A Print B
End
19
COMPUTER PROGRAMMING
Start
E 6
Write E
E E+2
Yes
E <= 20
No
End
4. Draw a flowchart to determine a student‘s final grade and indicate whether it is passing or
failing. The final grade is calculated as the average of four marks.
Start
Accept
M1,M2,M3,M5
Grade (M1+M2+M3+M4)/4
Is Grade<50
?
Print Print
―Pass‖ ―Fail‖
Stop
20
COMPUTER PROGRAMMING
21
COMPUTER PROGRAMMING
❖ Flowcharts are used to help team members, identify who provides inputs or resources to
whom, establish important areas for monitoring or data collection identify areas for
improvement or increased efficiency, and generate hypotheses about causes.
❖ It is recommended that flowcharts be created through group discussion, as individuals rarely
know the entire process and the communication contributes to improvement.
Pseudo code is one of the methods that can be used to write an initial plan that can be developed
into a computer program. It is a generic way of describing an algorithm without the use of any
specific programming language syntax. It is, as the name suggests, pseudo code: which means fake
code, it cannot be executed on a real computer, but it models and resembles real programming
code, and is written in English at roughly the same level of detail. Pseudo code cannot be compiled
nor executed, and there are no real formatting or syntax rules.
How to Write Pseudo code Statements? There are six basic guidelines to develop pseudo code
1. A computer can receive information
Read (information from a file)
Get (information from the keyboard)
2. A computer can put out information
Write (information to a file)
Display (information to the screen)
22
COMPUTER PROGRAMMING
3. A computer can perform arithmetic. Use actual mathematical symbols or the words for the
symbols
Add a number to the total
Total = total + number
+, -, *, / Calculate, Compute also used
4. A computer can assign a value to a piece of data. There are three cases to assign value.
i. to give data an initial value: Initialize, Set
IF condition THEN
Some action
ELSE
Alternative action
ENDIF
6. A computer can repeat a group of actions
23
COMPUTER PROGRAMMING
24
COMPUTER PROGRAMMING
Summary
The a lgorithm is the sequence of steps to be performed to solve a problem by the
computer.
Three reasons for using algorithms are efficiency, abstraction, and reusability.
Algorithms can be expressed in many different notations, including natural languages,
pseudo code, flowcharts, and programming languages.
The practical goal of algorithm analysis is to predict the performance of different algorithms in
order to guide program design decisions.
Flowchart is a graphical or symbolic representation of an algorithm. It is the diagrammatic
representation of the step-by step solution to a given problem.
Flowcharts are used in analysing, designing, documenting or managing a process or program in
various fields.
Benefits of using flowcharts include ease of communication, effective and efficient analysis and
coding, proper documentation and maintenance.
Limitations of using flowcharts include complex logic and multiple modifications.
Computer is an electronic device that accepts data, performs computations, and makes
logical decisions according to instructions that have been given to it.
Basically computer is composed of two parts: hardware and software .
Hardware the physical architecture of the computer while Software is the program or
instructions that control the system or hardware.
The terms computer programs, are the instructions that tells the computer what to do.
A programming language is an artificial language that can be used to control the behaviour
of a machine, particularly a computer.
Programming languages can be divided in to two major categories: low-level and highlevel
languages.
A programming paradigm provides the programmer's view of code execution. The most
influential paradigms are procedural, structural and object-oriented programming
paradigms.
In developing a software we will have problem definition, analysis , design , coding , testing
, implementation and maintenance steps.
25
COMPUTER PROGRAMMING
While developing a software , there may be a mismatch between in what the software can
deliver and the capacity of computer system as well as expectation of the user. Such kind of
mismatch is called software crisis.
Exercises
part 1
Part 2
Writing programs that solve the Programming Projects helps to get hard your understanding
of the material and demonstrates how the chapter‘s concepts are applied.
1) Write an algorithm to find the sum of the first 50 natural numbers and also draw the
corresponding flowchart.
2) Write an algorithm to read a number N from the user and print all its divisors.
3) Write an algorithm to find the sum of given N numbers and also draw the
corresponding flowchart.
4) Draw a flow chart to log in to a Facebook account.
5) Write an algorithm to compute the sum of the squares of integers from 1 to 50 and also
draw the corresponding flowchart.
6) Draw a flowchart explaining the process of waking up in the morning. [Hint: Use
steps Alarm Ringing, Ready to get up, climbing out of bed]
7) Write and algorithm that prints ―Hello Engineering‖ five times and draw flow chart.
8) Describe the following flow chart by pseudo code. What it do?
26
COMPUTER PROGRAMMING
Start
In X
Sum=0
X>=0
X= X-1
End
27
COMPUTER PROGRAMMING
Any C++ program file should be saved with file name extension ― .CPP ‖ . Type the program
directly into the editor (such as Dev-C++, Code:: Blocks , etc.), and save the file as [Link],
compile it and then run it. It will print the words Hello World! on the computer screen.
The first character is the #. This character is a signal to the pre-processor. Each time you start
your compiler, the pre-processor runs through the program and looks for the pound (#) symbols
and act on those lines before the compiler runs.
The include instruction is a pre-processor instruction that directs the compiler to include a copy
of the file specified in the angle brackets in the source code.
If the path of the file is not specified, the pre-processor looks for the file under c:\include\ folder or
in include folder of the location where the editor is stored.
The effects of line 1, i.e. include<iostream> is to include the file iostream into the program as if
the programmer had actually typed it.
28
COMPUTER PROGRAMMING
The effects of line 2, i.e using namespace std; is to define namespace standard used in this program.
When the program starts, main() is called automatically. Every C++ program has a main()
function. The return value type for main() here is int, which means main function will return a
value to the caller (which is the operating system). The main function can be made to return a
value to the operating system.
The Left French brace “{“signals the beginning of the main function body and the corresponding
Right French brace “}” signals the end of the main function body. Every Left French Brace needs
to have a corresponding Right French Brace. The lines we find between the braces are statements
or said to be the body of the main function. The statement found between the opening and
closing brace or the body of the main function is a computation step which may produce a value
or interact with input and output streams. The end of a single statement ends with semicolon (;).
The statement in the above example causes the string ―Hello World!‖ to be sent to the ―cout‖
stream which will display it on the computer screen.
What is a compilation?
The compilation is a process of converting the source code into object code. It is done with the
help of the compiler. The compiler checks the source code for the syntactical or structural errors,
and if the source code is error-free, then it generates the object code.
Any program written in a language other than machine language needs to be translated to machine
language. The set of instructions that do this task are known as translators. There are different
kinds of translator software, among which compilers and interpreters are of interest for most
programmers. There are different kinds of translator software, among which compilers and
interpreters are of interest for most programmers.
Compilers: a compiler is a computer program that translates a series of statements written in
source code (a collection of statements in a specific programming language) into a resulting object
code (translated instructions of the statements in a programming language). A compiler changes
or translates the whole source code into executable machine code (also called object code) which
is output to a file for latter execution. E.g. C++, Pascal, FORTRAN, etc.
29
COMPUTER PROGRAMMING
Interpreters: is a computer program that translates a single high level statement and executes it
and then goes to the next high level language line etc. E.g. QBASIC, Lisp etc.
It is fundamental to know how C++ compilation works to understand how programs are compiled
and executed. C++ programs typically go through five edit, pre-process, compile, link, and load.
Edit: this is accomplished with an editor program. The programmer types C++ statements with
the editor and makes corrections if necessary. The programs source file is then stored on secondary
storage device such as a disk with a ―.cpp‖ file name.
After the program is edited, C++ is principally compiled in three phases: pre-processing,
translation to object code, and linking (the last two phases are what is generally thought of as the
"compilation" process).
Compile: Then, the C++ compiler translates the program code. The compiler may be a true C++
compiler which generates native (assembly or machine) code. The outcome may be incomplete
due to the program referring to library routines which are not defined as a part of the program.
For example, the << operator which is actually defined in a separate IO library.
Linking: C++ programs typically contain references to functions and data defined elsewhere, such
as in the standard libraries. The object code produced by the C++ compiler typically contains
―holes‖ due to these missing parts. A linker links the object code with the code for the missing
function to produce an executable image (with no missing pieces). Generally, the linker completes
the object code by linking it with the object code of any library modules that the program may
have referred to. The final result is an executable file.
30
COMPUTER PROGRAMMING
Loading: the loader takes the executable file from disk and transfers it to memory. Additional
components from shared libraries that support the program are also loaded. Finally, the computer,
under the control of its CPU, executes the program.
In practice all these steps are usually invoked by a single command and the user will not even see
the intermediate files generated.
When developing programs there are three types of error that can occur:
1. Syntax errors: errors due to the fact that the syntax of the language is not respected.
2. Semantic errors: errors due to an improper use of program statements.
3. Logical errors: errors due to the fact that the specification is not respected.
31
COMPUTER PROGRAMMING
1. Compile time errors: syntax errors and static semantic errors indicated by the compiler.
2. Runtime errors: dynamic semantic errors, and logical errors, that cannot be detected by the
compiler (debugging).
A program cannot run if it has syntax errors. Any such errors must be fixed first. A good integrated
development environment (IDE) usually points out any syntax errors to the programmer.
A logic error is an error in the way a program works. The program can run but does not do what it
is expected to do.
Logic errors can be caused by the programmer:
32
COMPUTER PROGRAMMING
• incorrectly using logical operators, e.g. expecting a program to stop when the value of a
variable reaches 5, but using <5 instead of <=5
• incorrectly using Boolean operators
• unintentionally creating a situation where an infinite loop may occur
• incorrectly using brackets in calculations
• unintentionally using the same variable name at different points in the program for different
purposes
• using incorrect program design
Unlike a syntax error, a logic error does not usually stop a program from running. The program
will run, but not function as expected. This type of error is not caught during compilation, but
causes an exception to be thrown at runtime.
2.4.1. Identifiers
It is a unique name which is given to an entity to distinctly identify it meanwhile the execution of
the source-code. Both an identifier and a variable are the names allotted by users to a particular
entity in a program. The identifier is only used to identify an entity uniquely in a program at the
time of execution whereas, a variable is a name given to a memory location that is used to hold a
value.
A valid identifier is a sequence of one or more letters, digits or underlined symbols. The length of
an identifier is not limited. Neither space nor marked letters can be part of an identifier.
2.4.2. Variables
A Variable is a name that is assigned to a memory location, which is used to contain the
corresponding value in it. Identifiers are not variables, nor are variables identifiers.
o Data Type: a type which is established when the variable is defined. (E.g. integer,
real, character etc.). Data type describes the property of the data and the size of
the reserved memory
o Name: a name which will be used to refer to the value in the variable. A unique
identifier for the reserved memory location. o Value: a value which can be
changed by assigning a new value to the variable.
Data types define the type of data a variable can hold, for example an integer variable can hold
integer data, a character type variable can hold character data etc.
All variables use data-type during declaration to restrict the type of data to be stored. Therefore,
we can say that data types are used to tell the variables the type of data it can store. Whenever a
variable is defined in C++, the compiler allocates some memory for that variable based on the
data-type with which it is declared. Every data type requires a different amount of memory.
1. Primitive Data Types: These data types are built-in or predefined data types and can be
used directly by the user to declare variables. Example: int, char , float, bool etc.
Primitive data types available in C++ are:
2. Derived Data Types: The data-types that are derived from the primitive or built-in data
types are referred to as Derived Data Types. These can be of four types namely:
34
COMPUTER PROGRAMMING
• Function
• Array
• Pointer
• Reference
3. Abstract or User-Defined Data Types: These data types are defined by user itself. Like,
defining a class in C++ or a structure. C++ provides the following user-defined data types:
• Class
• Structure
• Union
• Enumeration
• Typedef defined DataType
In this course we will discuss all primitive data types and from derived data types we will
discuss array.
The following table shows the data type, how much memory it takes to store the value in memory,
and what is the maximum and minimum value which can be stored in such type of variables. (Here:
remember the definition of variables)
35
COMPUTER PROGRAMMING
float 4bytes
double 8bytes
2.4.4. Keyword
Keywords are the reserved keywords that are defined by the compiler to perform the internal
operation, written in lowercase.
Keywords have some meaning which is defined by the compiler to accomplish a task in code; they
cannot be used as a variable in programming. C++ provides different keywords such as– int, float,
double, char, main, bool etc. Primitive data types are key words used to define or declare a
variable value. The following table indicates some of the key words used in c++ programming
auto break case char const Continue default Do
36
COMPUTER PROGRAMMING
Example 1: int myage; (i.e. The Datatype: indicate type of data that can be stored
in this variable is integer; and Variable_Name: Name given to the variable is myage.
float simpleInterest;
Example 3: Declaring multiple variables
Syntax: Datatype Variable_Name, variable2_name, variable3_name;
int myage,myphonenumber,weight;
• Good variable names indicate the purpose of the variable or they should be selfdescriptive.
• The name of a variable sometimes is called an identifier which should be unique in a
program.
• Certain words are reserved by C++ for specific purposes and cannot be used as identifiers.
• A variable name can consist of alphabets (both upper and lower case), numbers and the
underscore ‗_‘ character. However, the name must not start with a number.
• C++ is not case sensitive. Small letter and capital letters are different for C++. E.g.:
37
COMPUTER PROGRAMMING
The variable declaration refers to the part where a variable is first declared or introduced before
its first use. A variable definition is a part where the variable is assigned a memory location and
a value. Most of the times, variable declaration and definition are done together. See the following
example 4 for better clarification:
This is identical with declaring a variable and then assigning a value to the variable immediately
after declaration. (i.e. The syntax: DataType variable name ; variable name = initial value; )
E.g. int a = 0;
or: int a; a=0; Example 6: How define / Initilize
/ assign value for variable during declaration
Scope of a variable is the boundary or block in a program where a variable can be accessed. The
boundary or block is identified by the left and right French brackets. In C++, we can declare
variables anywhere in the source code. But we should declare a variable before using it no matter
38
COMPUTER PROGRAMMING
where it is written. There are mainly two types of variable scopes: Local Variables and Global
Variables.
Example 1 : Simple c++ program to declare variable as local variable and global variable
1: #include<iostream>
2: using namespace std;
3: int global_variable;
4: int main()
5: {
6: int local_variable;
7: return 0;
8: }
Local Variables
• The scope of the local variable is limited to the code level or block within which they are
declared.
• Anything between ‗{‗ and ‗}‘ is said to inside a block.
• Local variables do not exist outside the block in which they are declared, i.e. they can not
be accessed or used outside that block.
• As illustrated example 1 : line 6 : the scope of the variable is local; int local_variable
Global variables:
• There are variables that can be referred/accessed anywhere in the code, within any function,
as long as it is declared first.
• A variable declared before any function immediately after the include statements are global
variables
• As illustrated example 1 : line 3 : the scope of the variable is global; int global_variable
2.4.6. Constants
A constant is any expression that has a fixed value. A constant value is the one which does not
change during the execution of a program. Constants can be of any of the basic data types. The
way each constant is represented depends upon its type. Constants are also called literals.
Like variables, constants are data storage locations in the computer memory. But, constants, unlike
variables their content cannot be changed after the declaration.
39
COMPUTER PROGRAMMING
Constants must be initialized when they are created by the program, and the programmer can‘t
assign a new value to a constant later. In C++ two types of constants can be implemented: literal
and symbolic constants.
Literal constant: is a value typed directly into the program wherever it is needed.
Example 1: int num = 43;
43 is a literal constant in this statement:
Symbolic constant: is a constant that is represented by a name, similar to that of a variable. But
unlike a variable, its value can‘t be changed after initialization.
In C++, we have two ways to declare a symbolic constant. These are using the #define and the
const key word.
Using #define pre-processor directive:
• This directive is used to declare an alias name for existing variable or any value.
• The #define directive makes a simple text substitution.
• The define directive can define only integer constants
40
COMPUTER PROGRAMMING
• A program which contains so much comment that you can hardly see the code can by no
means be considered readable.
• It can also be used to prevent execution when testing alternative code.
• Use of descriptive names for variables and other entities in a program, and proper
indentation of the code can reduce the need for using comments.
• C++ provides two types of comment delimiters:
o Single Line Comment: Anything after // {double forward slash} (until the end of
the line on which it appears) is considered a comment. o The // (two slashes)
characters, followed by any sequence of characters. A new line not immediately
preceded by a backslash terminates this form of comment.
Example 1:
#include <iostream> using namespace std; int
main() { int x = 11; // x is a variable with
integer type cout<<x<<"\n";
}
o Multiple Line Comment: Anything enclosed by the pair /* and */ is considered a
comment
o The /* (slash, asterisk) characters, followed by any sequence of characters
(including new lines), followed by the */ characters. Example 2
#include <ostream>
using namespace std;
int main() {
/* declare and
print variable in C++. */
int x = 35;
cout<<x<<"\n";
}
[Link] Operators
Once introduced to variables and constants, we can begin to operate with them by using operators.
An operator is a symbol that makes the machine to take an action. Different Operators act on one
or more operands and can also have different kinds of operators.
• Assignment operator
41
COMPUTER PROGRAMMING
• Arithmetic operator
• Relational operator
• Logical operator
• Increment/decrement operator
• Conditional operator
• Comma operator
• The size of operator
• Explicit type casting operators, etc.
Assignment operator (=). The assignment operator causes the operand on the left side of the
assignment statement to have its value changed to the value on the right side of the statement.
• Syntax: Operand1=Operand2;
• Operand1 is always a variable
• Operand2 can be one or combination of:
o A literal constant: E.g.: x=12;
o A variable: E.g.: x=y; o
An expression: E.g.: x=y+2;
Arithmetic operators (+, -, *, /, % ). Except for remainder or modulo (%), all other arithmetic
operators can accept a mix of integers and real operands. Generally, if both operands are integers
then, the result will be an integer. However, if one or both operands are real then the result will be
real.
When both operands of the division operator (/) are integers, then the division is performed as an
integer division and not the normal division we are used to.
• To obtain a real division when both operands are integers, you should cast one of the
operands to be real.
o E.g.: int cost = 100; o Int volume =
80; o Double unitPrice =
cost/(double)volume;
The module(%) is an operator that gives the remainder of a division of two integer values.
E.g.: a = 11 % 3; ,then a is 2
Relational operator (==, !=, > , <, >=, <=).
• In order to evaluate a comparison between two expressions, we can use the relational
operator.
• The result of a relational operator is a bool value that can only be true or false according to
the result of the comparison.
• Two expressions can be compared using relational and equality operators. For example, to
know if two values are equal or if one is greater than the other.
• The result of such an operation is either true or false (i.e., a Boolean value).
43
COMPUTER PROGRAMMING
• Logical negation (!) is a unary operator, which negates the logical value of its operand. If
its operand is non-zero, it produce 0, and if it is 0 it produce 1
• Logical AND (&&) produces 0 if one or both of its operands evaluate to 0 otherwise it
produces 1.
• Logical OR (||) produces 0 if both of its operands evaluate to 0 otherwise, it produces 1.
Example
!20 //gives 0
10 && 5 //gives 1
10 || 5.5 //gives 1
10 && 0 // gives 0
N.B. In general, any non-zero value can be used to represent the logical true, whereas only zero
represents the logical false.
• The auto increment (++) and auto decrement (--) operators provide a convenient way of,
respectively, adding and subtracting 1 from a numeric variable.
• Example: if a was 10 and if a++ is executed then a will automatically changed to 11.
• Example: if b was 10 and if b++ is executed then a will automatically changed to 9.
• The prefix type is written before the variable. E.g. (++ myAge), whereas the postfix type
appears after the variable name (myAge ++).
• Prefix and postfix operators cannot be used at once on a single variable: E.g.: ++age-- or -
age++ or ++age++ or - - age - - is invalid
• In a simple statement, either type may be used. But in complex statements, there will be a
difference.
• The prefix operator is evaluated before the assignment, and the postfix operator is evaluated
after the assignment. #
• Example int k = 5;
(auto increment prefix) y= ++k + 10; //gives 16 for y
44
COMPUTER PROGRAMMING
• The conditional operator takes three operands. It has the general form:
• Example 1:
o This expression means that if X is less than Y the value of X will be assigned to Z
otherwise (if X>=Y) the value of Y will be assigned to Z.
• Example 2:
o int m=1,n=2,min; o min = (m < n ? m : n); o The value
stored in min is 1.
• Example 2:
• Multiple expressions can be combined into one expression using the comma operator.
• The comma operator takes two operands. Operand1,Operand2
• The comma operator can be used during multiple declarations, for the condition operator
and for function declaration, etc.
• It the first evaluates the left operand and then the right operand, and returns the value of the
latter as the final outcome.
45
COMPUTER PROGRAMMING
• This operator is used for calculating the size of any data item or type.
• It takes a single operand (e.g. 100) and returns the size of the specified entity in bytes.
The outcome is totally machine dependent.
• Example 1:
Type casting operators allows you to convert a datum of a given type to another data type.
Example 1: int i; float f = 3.14; i = (int)f; → equivalent to i = int(f); Then
variable i will have a value of 3 ignoring the decimal point.
Compound assignment operators (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=):
• Compound assignment operator is the combination of the assignment operator with other
operators like arithmetic and bit wise operators.
• The assignment operator has a number of variants, obtained by combining it with other
operators. o Example 1:
increase;
o a -= 5; is equivalent to a = a – 5; o a
46
COMPUTER PROGRAMMING
• Statements are the ―commands‖ or ―line of code‖ that can be executed whereas
expressions are not executed by themselves.
• White spaces: white spaces characters (spaces, tabs, new lines) can‘t be seen and generally
ignored in statements. White spaces should be used to make programs more readable and
easier to maintain.
• Blocks: a block begins with an opening French brace ({) and ends with a closing French
brace (}).
• Example: the statement 3+2; returns the value 5 and thus is an expression.
2.4.9 Special Printing Characters.
In C++, there are some special characters used for formatting. These are:
• \n new line
• \t tab
• \b backspace
• \” double quote
• \‟ single quote
• \? Question mark
• \\ backslash
47
COMPUTER PROGRAMMING
Standard output stream (cout): Usually the standard output device is the display screen.
The C++ cout statement is the instance of the ostream class. It is used to produce output
on the standard output device which is usually the display screen. The data needed to be
displayed on the screen is inserted in the standard output stream (cout) using the insertion
operator(<<).
#include <iostream>
using namespace
std; int main() {
char sample= „G‟;
cout << sample;
return 0;
}
In the above program, the insertion operator(<<) inserts the value of the character variable sample
in the standard output stream cout which is then displayed on the screen.
Standard input stream (cin): Usually the input device in a computer is the keyboard. C++ cin
statement is the instance of the class istream and is used to read input from the standard input
device which is usually a keyboard.
The extraction operator(>>) is used along with the object cin for reading inputs. The extraction
operator extracts the data from the object cin which is entered using the keyboard.
48
COMPUTER PROGRAMMING
int main()
{
int age;
return 0;
}
Output:
Enter your age:
Your age is: 18
The above program asks the user to input the age. The object cin is connected to the input device.
The age entered by the user is extracted from cin using the extraction operator(>>) and the
extracted data is then stored in the variable age present on the right side of the extraction operator.
Summary
• Any C++ program file should be saved with file name extension ― .CPP ‖ .
• When the program starts, main() is called automatically
• The compilation is a process of converting the source code into object code. It is done with
the help of the compiler.
• When developing programs there are three types of error that can occur: Syntax errors:
semantic errors and logical errors:
• Identifier is a unique name which is given to an entity to distinctly identify it meanwhile the
execution of the source-code
• A Variable is a name that is assigned to a memory location, which is used to contain the
corresponding value in it
49
COMPUTER PROGRAMMING
• Depending on the type of data a variable can hold data types can be categorized as primitive
data types, derived data types and abstract or user defined data types
• Keywords are the reserved keywords that are defined by the compiler to perform the internal
operation, written in lowercase.
• Scope of a variable is the boundary or block in a program where a variable can be accessed.
There are mainly two types of variable scopes: Local Variables and Global Variables.
• A constant is any expression that has a fixed value. A constant value is the one which does
not change during the execution of a program. Constants can be of any of the basic data
types.
• A comment is a piece of descriptive text which explains some aspect of a program.
Comments are normally used to annotate code for future reference.
• An operator is a symbol that makes the machine to take an action. C++ provides several
categories of operators, including the following: Assignment operator, Arithmetic operator,
Relational operator, Logical operator, Increment/decrement operator, Conditional operator,
Comma operator, The size of operator and Explicit type casting operators.
• In C++, there are some special characters used for formatting. These are: \n new line, \t tab
, \b backspace, \” double quote, \‟ single quote, \? Question mark, and \\ backslash.
• The two instances cout in C++ and cin in C++ of iostream class are used very often for
printing outputs and taking inputs respectively
50
COMPUTER PROGRAMMING
Exercise
1. Write a c++ program which display the size of each data types in c++;
2. Write a c++ program which read two number from the user and display the sum and the
product of the two numbers.
3. Write a program in C++ to check the upper and lower limits of integer.
4. Write a program in C++ to swap two variables value without additional third variable.
5. Write a program in C++ which calculate the area of a square.
6. Write a program in C++ to convert temperature in Celsius to Fahrenheit.
7. Write a program in C++ to find the third angle of a triangle.
8. Write a program in C++ to convert distance in kilometre to meter.
9. Write a program in C++ which accept two number from the user and compute quotient
and remainder.
10. Write a C++ program to display the current date and time.
51
COMPUTER PROGRAMMING
A running program spends all of its time executing statements. The order in which statements
are executed is called flow control (or control flow). This term reflect 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, but may be
diverted to other paths by branch statements. Flow control is an important consideration because
it determines what is executed during a run and what is not, therefore affecting the overall
outcome of the program. Not many programs execute all their statements in strict order from
beginning to end. Most programs (like many humans) decide what to do in response to changing
circumstances. The flow of control jumps from one part of the program to another, depending
on calculations performed in the program. Program statements that cause such jumps are called
control statements.
The statements inside your source files are generally executed from top to bottom, in the order
that they appear. Control flow statements, however, break up the flow of execution by employing
decision making, looping, and branching, enabling your program to conditionally execute
particular blocks of code. This section describes the decision-making statements (if-then, if-then-
else, switch), the looping statements (for, while, do-while), and the branching statements (break,
continue, return) supported by the c++ programming language.
52
COMPUTER PROGRAMMING
▪ Loop statements are used for specifying computations, which need to be repeated until
a certain logical condition is satisfied.
Flow control statements are used to divert the execution path to another part of the program. They
are also known as decision making statements. Decision making structures require that the
programmer specify one or more conditions to be evaluated or tested by the program, along with
a statement or statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false. Following is the general
from of a typical decision making structure found in most of the programming languages:
&& : and
|| : or
! : not
For example, the following are all valid conditional expressions in C++:
((x > 0) && (x <= 10))
((x <= 0) || (x > 10))
(!((a == 1) && (b == 1)) || (c != 0))
if(boolean_expression)
➢ If the Boolean expression evaluates to true, then the block of code inside the if block will
be executed.
54
COMPUTER PROGRAMMING
➢ If Boolean expression evaluates to false, then the first set of code after the end of the if
block (after the closing curly brace) will be executed.
➢ If we have only one statement inside the if block so that we are not expected to use opening
and closing curly brace. However if we have more than one number of statement we are
expected to write those statements inside curly brace.
55
COMPUTER PROGRAMMING
Example 1:
The following program will check if the value of a is less than 20 and if it is less than 20 it will
display a text ―a is less than 20‖ and ―value of a is : 20‖ otherwise it only display the text ―value
of a is ‖ combined with the a‘s values.
of a is : 10
Example 2:- the following program will read a temperature value from the user and it will display
the text ―warning- overheating ‖ if the temperature value is greater than 60.
#include <iostream.h> int
main ()
{ float temperature; // declaring a float type variable
cin>> temperature; // accept the temperature value
// compare if the temperature value is greater than 60 or not
if (temperature > 60) cout<<"Warning-overheating\n";//display
the text if the //above
condition is true return 0; // return the integer value 0 }
Example 3: The following program will read income value from the user and compute the tax if
the income is greater than 15000. The tax will be 20% of the income.
#include <iostream.h>
56
COMPUTER PROGRAMMING
int main ()
{ float income; // declaring a float type variable
named cin>> income; // accept the income value if
(income < 15000) { cout << “Tax rate = 20%\n”; tax =
income * 0.2; cout<<”the tax is”<< tax;
}
return 0;
}
Notice that you can use curly brackets to cause more than one statement to be conditionally
executed. This is called creating a compound statement.
An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false. It allows you to specify an alternative statement that is executed if
the expression is not true. The If-Else statement allows the programmer to specify a condition for
the execution of a statement, or group of statements.
Syntax:
The syntax of an if...else statement in C++ is:
if (boolean_expression)
{
// statement(s) will execute if the boolean expression is
true } else
{
// statement(s) will execute if the boolean expression is
false
}
If the Boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Flow Diagram:
57
COMPUTER PROGRAMMING
Example 1:- The following program will identify if the value a is greater than 20 or not and
display its value.
#include <iostream> using
namespace std; int main
()
{
// local variable declaration: int
a = 100;
// check the boolean condition if( a < 20 ) // if
condition is true then print the
//following
{
cout << "a is less than 20;" << endl;
} else // if condition is false then print the
following
{ cout << "a is not less than 20;" <<
endl;
58
COMPUTER PROGRAMMING
of a is : 100
Example 2:- The following program will accept the value of balance from the user and compute
and display the interest and the reaming balance based on the credit and debit rate.
Alterative one Alterative Two
float balance; cin>>balance; if float balance;
(balance > 0) { interest = cin>>balance;
balance * creditRate; balance if (balance > 0)
interest = balance
+= interest; * creditRate;
} else { interest = balance * else interest =
balance *
debitRate; balance += debitRate;
balance += interest;
interest;
}
cout<< balance<<endl;
cout<< interest<<endl;
59
COMPUTER PROGRAMMING
➢ An if can have zero or one else's and it must come after any else if's.
➢ An if can have zero to many else if's and they must come before the else.
➢ Once an else if succeeds, none of the remaining else if's or else's will be tested.
➢ The final else block will be execute If all if conditions are not true.
Syntax:
Example 1:
#include <iostream>
using namespace std;
int main ()
60
COMPUTER PROGRAMMING
Syntax:
61
COMPUTER PROGRAMMING
switch(expression){
//check if expression and constant-expression1 are matched case
constant-expression1:
// executed if expression and constant-expression1
matched statement(s); break;
➢ The expression used in a switch statement must have an integral or enumerated type, or
be of a class type in which the class has a single conversion function to an integral or
enumerated type. You can have any number of case statements within a switch. Each case
is followed by the value to be compared to and a colon.
➢ The constant-expressions for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal. When the variable being switched on is equal
to a case, the statements following that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to
the next line following the switch statement. Not every case needs to contain a break. If no
break appears, the flow of control will fall through to subsequent cases until a break is
reached.
➢ A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.
62
COMPUTER PROGRAMMING
➢ Note that the Switch statement is used only for equality tests – you cannot use it for other
comparisons (e.g. >, <, etc.). The effect of the break statement is to transfer control to the
statement immediately following the switch statement.
Flow Diagram:
Example 1:
The following program will read the day number and display the name of that day.
63
COMPUTER PROGRAMMING
Example 2: The following program will accept the letter grade from the user and display based on
the following criteria.
Grade Remark
A Excellent
B Well done
C Well done
D You passed
F try again
Other Invalid grade
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
char grade = 'D';
switch(grade)
{ case 'A' : cout << "Excellent!" <<
endl; break;
case 'B' :
case 'C' : cout << "Well done" <<
endl; break;
case 'D' : cout<<"You passed" <<
endl; break;
case 'F' : cout<<" try again"<<
endl; break;
default :
cout<<"Invalid grade"<< endl;
} cout << "Your grade is " << grade <<
endl; return 0;
}
This would produce the following result:
You passed
64
COMPUTER PROGRAMMING
Your grade is D
Example 3. The following program will receive the operator type from the user and apply the
selected operator o the given operands. if we extend the above statement to also allow x to be used
as a multiplication operator, we will have:
#include <iostream>
int main ()
char operator;
cin>>operator; int
operand1,operand2;
cin>operand1
cin>>operand2;
switch (operator) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case 'x':
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
default:
cout << "unknown operator: " << ch << '\n';
break;
}
}
Because case 'x' has no break statement (in fact no statement at all!), when this case is satisfied, execution
proceeds to the statements of the next case and the multiplication is performed.
65
COMPUTER PROGRAMMING
In selection statement we may want to check additional conditions even if the previous one is
correct or not; so that we have to include additional selection statement inside the other. Such kind
of statement is called selection statement.
Nested selection structures are used when more than one decision must be made before carrying
out a task. Nesting is a programming activity, in which one program block is placed inside other
program block of the same operation type. Nesting processes are mostly used implemented in the
selection control structures.
➢ Nested selections give provisions to specify one condition inside another condition.
➢ Nested selections have many advantages when compared to labels that are used in
programming.
Disadvantages:
➢ When a greater number of conditions are mentioned inside the nested selection, the
code complexity will increase significantly.
➢ It becomes a difficult task for the programmers to find out each programming path
separately if there is more nesting in the program.
Syntax:
if( boolean_expression 1)
66
COMPUTER PROGRAMMING
if(boolean_expression 2)
}
You can nest else if...else in the similar way as you have nested if statement.
Example:
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
// check the boolean condition if(
a == 100 )
{
// if condition is true then check the following
if( b == 200 )
{
// if condition is true then print the following
cout << "Value of a is 100 and b is 200" << endl;
}
} cout << "Exact value of a is : " << a
<< endl; cout << "Exact value of b is : " << b
<< endl; return 0;
}
When the above code is compiled and executed, it produces the following result:
67
COMPUTER PROGRAMMING
Example:- The following program will the percentage values of Chris and Harry compare the
two values.
#include <iostream>
int main () {
return 0;
Output
Enter the percentage of Chris 78
Enter the percentage of Harry 54
68
COMPUTER PROGRAMMING
Syntax:
'A':
// ...
69
COMPUTER PROGRAMMING
Example : In the following program the value if a and b are displayed however in addition to
those two values the text ―this is part of outer switch‖ will also be displayed only if the values of
a is 100 and b is 200.
#include <iostream>
using namespace std;
int main () {
int a = 100;
int b = 200;
switch(a) {
case 100:
cout << "This is part of outer switch" << endl;
switch(b) { case 200: cout <<
"This is part of inner switch" << endl;
brake;
}
brake;
} cout << "Exact value of a is : " << a
<< endl; cout << "Exact value of b is : " <<
b << endl; return 0;
}
The output of the above program is
Exercise
1. Write a C++ program to check whether a given number is even or odd.
70
COMPUTER PROGRAMMING
2. Write a C++ program to accept the height of a person in centimetre and categorize the person according
to their height.
hint
Test Data : 135
Expected Output : The person is Dwarf.
71
COMPUTER PROGRAMMING
return 0;
}
In Loop, the statement needs to be written only once and the loop will be executed 10 times. In
computer programming, a loop is a sequence of instructions that is repeated until a certain
condition is reached.
• An operation is done, such as getting an item of data and changing it, and then some condition
is checked such as whether a counter has reached a prescribed number.
• Counter not Reached: If the counter has not reached the desired number, the next instruction
in the sequence returns to the first instruction in the sequence and repeat it.
• Counter reached: If the condition has been reached, the next instruction ―falls through‖ to
the next sequential instruction or branches outside the loop.
There are several different loop statements; each one is designed for slightly different programming situations.
There are mainly two types of loops:
1. Entry Controlled loops: In this type of loops the test condition is tested before entering the
loop body. For Loop and While Loop are entry controlled loops.
72
COMPUTER PROGRAMMING
2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at the end
of loop body. Therefore, the loop body will execute at least once, irrespective of whether the
test condition is true or false. do – while loop is exit controlled loop.
The while statement (also called while loop) provides a way of repeating a statement while a
condition holds. It is one of the three flavours of iteration in C++. The general form of the while
statement is:
Syntax;
while (expression)
{
statement;//body
First expression (called the loop condition) is evaluated. If the outcome is nonzero then
statement (called the loop body) is executed and the whole process is repeated. Otherwise, the
loop is terminated.
Example: the following program will display the text” hello world” 10 times
// C++ program to illustrate while loop
73
COMPUTER PROGRAMMING
{
// initialization expression
int i = 1;
// test expression
while (i < 6)
{ cout << "Hello
World\n";
// update expression
i++;
}
return 0;
}
For example, suppose we wish to calculate the sum of all numbers from 1 to some integer denoted by
n. This can be expressed as:
i = 1; sum =
0; while (i
<= n)
sum += i;
For n set to 5, the following table provides a trace of the loop by listing the values of the variables involved
and the loop condition.
First 1 5 1 1
Second 2 5 1 3
Third 3 5 1 6
Fourth 4 5 1 10
74
COMPUTER PROGRAMMING
Fifth 5 5 1 15
Sixth 6 5 0
The Do loop is similar to the While loop – it should also be used when you do not know how many
times the loop should be executed. However, with the Do loop the statement is guaranteed to be
executed at least once, as the expression is only checked after the first iteration.
statement;// body
while (expression);
First
statement is executed and then expression is evaluated. If the outcome of the latter is nonzero then
the whole process is repeated. Otherwise, the loop is terminated. The do loop is less frequently
used than the while loop. It is useful for situations where we need the loop body to be executed at
least once, regardless of the loop condition.
75
COMPUTER PROGRAMMING
For example, suppose we wish to repeatedly read a value and print its square, and stop when the value
is zero.
This can be expressed as the following loop:
do { cin
>> n;
cout << n * n << '\n';
} while (n != 0);
For example, examine the following piece of code – can you see what it does?
float i = 1.0;
do {
cout << i << endl;
i /= 2;
} while (i > 0.01);
Unlike the while loop, the do loop is never used in situations where it would have a null body.
Although a do loop with a null body would be equivalent to a similar while loop, the latter is
always preferred for its superior readability.
The for statement (also called for loop) is similar to the while statement, but has two additional
components: an expression which is evaluated only once before everything else, and an
expression which is evaluated once at the end of each iteration.
76
COMPUTER PROGRAMMING
77
COMPUTER PROGRAMMING
➢ expr-1 is used as the loop control (the loop will be executed until this expression
becomes false), and
➢ expr-2 is generally used to update the control variable‘s value. Each time round the
loop, expr-1 is evaluated. If the outcome is nonzero then statement is executed and expr-
2 is evaluated. Otherwise, the loop is terminated
.
In general In for loop, a loop variable is used to control the loop. First initialize this loop
variable to some value, then check whether this variable is less than or greater than counter
value. If statement is true, then loop body is executed and loop variable gets updated . Steps
are repeated till exit condition comes.
• Initialization Expression: In this expression we have to initialize the loop counter to some
value. for example: int i=1;
• Test Expression: In this expression we have to test the condition. If the condition evaluates
to true then we will execute the body of loop and go to update expression otherwise we will
exit from the for loop. For example: i <= 10;
• Update Expression: After executing loop body this expression increments/decrements the
loop variable by some value. for example: i++;
Example: the following program wil display the text “hello world” 10 times
// C++ program to illustrate for loop
#include <iostream>
using namespace std;
int main() { for (int i =
1; i <= 10; i++)
{ cout << "Hello
World\n"; } return 0;
}
78
COMPUTER PROGRAMMING
Example, the following piece of code prints out the numbers from 1 to 10:
for (i = 1; i <= 10; i++)
cout << i << endl;
Here, init-stmnt assigns the value 1 to the variable i, expr-1 (the loop control) checks to see
if the value of i is greater than 10 at the end of each iteration of the loop, and expr-2
increments the value of i after each iteration
The general for loop is equivalent to the following while loop:
expression1; while
(expression2) {
statement;
expression3;
}
The most common use of for loops is for situations where a variable is incremented or
decremented with every iteration of the loop. The following for loop, for example, calculates
the sum of all integers from 1 to n.
sum = 0;
for (i = 1; i <= n; ++i)
sum += i;
This is preferred to the while-loop version we saw earlier. In this example, i is usually called
the loop variable. C++ allows the first expression in a for loop to be a variable definition. In
the above loop, for example, i can be defined inside the loop itself:
int i;
for (i = 1; i <= n; ++i)
sum += i;
79
COMPUTER PROGRAMMING
Any of the three expressions in a for loop may be empty. For example, removing the first and
the third expression gives us something identical to a while loop:
Removing all the expressions gives us an infinite loop. This loop's condition is assumed to
be always true:
for (;;) // infinite loop something;
For loops with multiple loop variables are not unusual. In such cases, the comma operator is
used to separate their expressions:
Because loops are statements, they can appear inside other loops. In other words, loops can
be nested. For example,
produces the product of the set {1,2,3} with itself, giving the output:
(1,1)
(1,2)
(1,3)
(2,1)
(2,2)
(2,3)
(3,1)
(3,2)
(3,3)
80
COMPUTER PROGRAMMING
int i, n, f;
while (cin >> n) {
f = 1;
for (i = 2; i <= n;
i++) f *= i;
cout << f << endl;
}
Here we have a for loop nested inside a while loop. The while loop reads in a sequence of
numbers from the user, terminated by Ctrl-D. Then, for each number, the for loop computes its
factorial.
Nested for loop
// C++ program to display 7 days of 3 weeks
#include <iostream> using
namespace std;
int main() { int weeks = 3,
days_in_week = 7;
for (int i = 1; i <= weeks; ++i)
{ cout << "Week: " << i <<
endl;
for (int j = 1; j <= days_in_week; ++j)
{ cout << " Day:" << j << endl;
}
}
return 0;
}
Output
81
COMPUTER PROGRAMMING
Week: 1
Day:1
Day:2
Day:3
... .. ...
Week: 2
Day:1
Day:2
Day:3
... ... ..
Example 2
// C++ program to display a pattern
// with 5 rows and 3 columns
#include <iostream>
using namespace std;
int main() {
int rows = 5;
int columns = 3;
* * *
* * *
* * *
* * *
* * *
82
COMPUTER PROGRAMMING
In while and do loops, the next iteration commences from the loop condition. In a for loop,
the next iteration commences from the loop‘s third expression. For example, a loop which
repeatedly reads in a number, processes it but ignores negative numbers, and terminates when
the number is zero, may be expressed as:
do { cin >> num; if
(num < 0) continue;
// process num here...
} while (num != 0);
This is equivalent to:
do { cin >>
num; if (num
>= 0) {
// process num here...
}
} while (num != 0);
A variant of this loop which reads in a number exactly n times (rather than until the number
is zero) may be expressed as:
When the continue statement appears inside nested loops, it applies to the loop immediately
enclosing it, and not to the outer loops. For example, in the following set of nested loops, the
continue applies to the for loop, and not the while loop:
83
COMPUTER PROGRAMMING
Here we have assumed that there is a function called Verify which checks a password and
returns true if it is correct, and false otherwise.
Rewriting the loop without a break statement is always possible by using an additional logical
variable (verified) and adding it to the loop condition:
verified = 0;
for (i = 0; i < attempts && !verified;
++i) { cout << "Please enter your
password: "; cin >> password; verified
84
COMPUTER PROGRAMMING
= Verify(password)); if (!verified)
cout << "Incorrect!\n";
}
The break version is arguably simpler and therefore preferred.
where label is an identifier which marks the jump destination of goto. The label should be
followed by a colon and appear before a statement within the same function as the goto
statement itself. For example, the role of the break statement in the for loop in the previous
section can be emulated by a goto:
for (i = 0; i < attempts; ++i) { cout
<< "Please enter your password: ";
cin >> password;
if (Verify(password)) // check password for
correctness
goto out; // drop out of the loop cout
<< "Incorrect!\n";
}
out:
//etc...
Because goto provides a free and unstructured form of jumping (unlike break and continue),
it can be easily misused. Most programmers these days avoid using it altogether in favor of
clear programming. Nevertheless, goto does have some legitimate (though rare) uses.
85
COMPUTER PROGRAMMING
The only function we have discussed so far is main, whose return type is always int. The return
value of main is what the program returns to the operating system when it completes its
execution. Under UNIX, for example, it its conventional to return 0 from main when the
program executes without errors. Otherwise, a non-zero error code is returned. For example:
Summary
Flow control in a program is typically sequential, from one statement to the next, but may
be diverted to other paths by branch statements.
• In c++ we have two main categories of flow control programs. One is selection
statement and the other is loop statement.
• Selection statement is a statement which allow us ot execute set of statements based on
a given criteria.
• We have for types of selection statement, such as if , if else, if else if, switch statement.
• If statement used to specify a set of activities to be executed under only if a given
condition is true.
• If else statement is used to specify a set of two block in which the first block to be
executed is the give condition is true and the other will be executed if the condition is
false.
86
COMPUTER PROGRAMMING
• If else if statement used to specify more than one conditions to be checked in the
program
• Switch statement is a selection statement which includes a number of cases to be
matched with the given expression. The block under the matched case will be executed
otherwise if none of the given cases are not matched each to the expression so that the
final default black will be executed.
• In switch statement default block is optional
• In c++ if we want to execute a given activity for number of times we could implement
such statements by using loop statements.
• Loop statements are statements which allow us to execute a given set of statements
multiple times based on the given condition.
• In c++ we have 3 main loop statements such as for loop , switch statement , and do
while loop statements.
Exercise
1. Write a C++ Program to display the pattern like pyramid using the alphabet.
2. Write a program in C++ to find the number and sum of all integer between 100 and
200 which are divisible by 9.
3. Write a program in C++ to display the n terms of harmonic series and their sum.
1 + 1/2 + 1/3 + 1/4 + 1/5 ... 1/n terms
4. Write a program in C++ to display the pattern like a pyramid using asterisk and
each row contain an odd number of asterisks.
5. Write a program in C++ to display the n terms of odd natural number and their sum
6. Write a program in C++ to convert an octal number into binary
7. Write a program in C++ to convert a decimal number to hexadecimal.
8. Write a program in C++ to print a string in reverse order
9. Write a program in C++ to find LCM of any two numbers using HCF
10. Write a program in C++ to display the such a pattern for n number of rows using a
number which will start with the number 1 and the first and a last number of each
row will be 1
87
COMPUTER PROGRAMMING
Objectives
On completion of this chapter, students should be able to:
❖ Understand and explain the concept of array and string
❖ Understand how to use array and string to solve problems in C++ programming
language
4.1. Introduction
Variables in a program have values associated with them. During program execution these
values are accessed by using the identifier associated with the variable in expressions etc. In
none of the programs written so far have very many variables been used to represent the values
that were required. Thus even though programs have been written that could handle large lists
of numbers it has not been necessary to use a separate identifier for each number in the list.
This is because in all these programs it has never been necessary to keep a note of each number
individually for later processing. For example in summing the numbers in a list only one
variable was used to hold the current entered number which was added to the accumulated sum
and was then overwritten by the next number entered. If that value were required again later in
the program there would be no way of accessing it because the value has now been overwritten
by the later input.
If only a few values were involved a different identifier could be declared for each variable,
but now a loop could not be used to enter the values. Using a loop and assuming that after a
value has been entered and used no further use will be made of it allows the following code to
be written. This code enters six numbers and outputs their sum:
sum = 0.0;
for (i = 0; i < 6; i++)
{ cin
>> x; sum
+= x; }
This of course is easily extended to n values where n can be as large as required. However if it
was required to access the values later the above would not be suitable. It would be possible to
do it as follows by setting up six individual variables: float a, b, c, d, e, f;
and then handling each value individually as follows:
88
COMPUTER PROGRAMMING
To get round this difficulty all high-level programming languages use the concept of a data
structure called an Array.
An array can be thought of as a collection of numbered boxes each containing one data item.
The number associated with the box is the index of the item. To access a particular item the
index of the box associated with the item is used to access the appropriate box. The index must
be an integer and indicates the position of the element in the array. Thus the elements of an
array are ordered by the index.
For example data on the average temperature over the year in Ethiopia for each of the last 100
years could be stored in an array declared as follows:
float annual_temp[100];
89
COMPUTER PROGRAMMING
This declaration will cause the compiler to allocate space for 100 consecutive float variables in
memory. The number of elements in an array must be fixed at compile time. It is best to make
the array size a constant and then, if required, the program can be changed to handle a different
size of array by changing the value of the constant,
Note that the array has not been given a size, the compiler will make it large enough to hold
the number of elements in the list. In this case primes would be allocated space for seven
elements. If the array is given a size then this size must be greater than or equal to the number
of elements in the initialization list. For example:
int primes[10] = {1, 2, 3, 5, 7}; would reserve space for a ten element
array but would only initialize the first five elements.
A set of positive data values (200) are available. It is required to find the average value of these
values and to count the number of values that are more than 10% above the average value.
Since the data values are all positive a negative value can be used as a sentinel to signal the end
of data entry. Obviously this is a problem in which an array must be used since the values must
90
COMPUTER PROGRAMMING
first be entered to find the average and then each value must be compared with this average.
Hence the use of an array to store the entered values for later re-use.
A main() program written from the above algorithmic description is given below:
void main()
{
const int NE = 200; // maximum no of elements in
array float sum = 0.0; // accumulates sum int
count = 0; // number of elements entered int
nogt10 = 0; // counts no greater than 10%
// above average float
x; // holds each no as input
float indata[NE]; // array to hold input
float average; // average value of input
91
COMPUTER PROGRAMMING
// calculate average
average = sum/count;
// Output results
cout << "Number of values input is " << n;
cout << endl
<< "Number more than 10% above average is "
<< nogt10 << endl;
}
Since it was assumed in the specification that there would be less than 200 values the array size
is set at 200. In running the program less than 200 elements may be entered, if n elements where
n < 200 elements are entered then they will occupy the first n places in the array indata. It is
common to set an array size to a value that is the maximum we think will occur in practice,
though often not all this space will be used.
The following program simulates the throwing of a dice by using a random number generator
to generate integers in the range 0 to 5. The user is asked to enter the number of trials and the
program outputs how many times each possible number occurred.
92
COMPUTER PROGRAMMING
An array has been used to hold the six counts. This allows the program to increment the correct
count using one statement inside the loop rather than using a switch statement with six cases
to choose between variables if separate variables had been used for each count. Also it is easy
to change the number of sides on the dice by changing a constant. Because C++ arrays start at
subscript 0 the count for an i occurring on a throw is held in the i-1th element of this count
array. By changing the value of the constant die_sides the program could be used to simulate a
die_sides-sided die without any further change.
#include <iostream.h>
#include <stdlib.h> // time.h and stdlib.h required for
#include <time.h> // random number generation
void main()
{
const int die_sides = 6; // maxr-sided die
int count[die_sides]; // holds count of each
// possible value int no_trials, //
number of trials roll, // random
integer i; // control
variable float sample; // random
fraction 0 .. 1
93
COMPUTER PROGRAMMING
} cout
<< endl;
Given the declaration above of a 100-element array the compiler reserves space for 100
consecutive floating point values and accesses these values using an index/subscript that takes
values from 0 to 99. The first element in an array in C++ always has the index 0, and if the
array has n elements the last element will have the index n-1.
An array element is accessed by writing the identifier of the array followed by the subscript
in square brackets. Thus to set the 15th element of the array above to 1.5 the following
assignment is used:
annual_temp[14] = 1.5;
Note that since the first element is at index 0, then the ith element is at index i-1. Hence in
An array element can be used anywhere an identifier may be used. Here are some examples
assuming the following declarations:
count[i] = count[i] + 5;
or, using the shorthand form of the assignment
count[i] += 5;
Array elements can form part of the condition for an if statement, or indeed, for any other
logical expression:
94
COMPUTER PROGRAMMING
For example, the following example finds the average of the last k entries in the array. k could
either be a variable, or a declared constant. Observe that a change in the value of k will still
calculate the correct average (provided k<=NE).
sum = 0.0;
for (i = NE - k; i < NE; i++)
sum += annual_temp[i]; av2 =
sum / k;
Important - C++ does not check that the subscript that is used to reference an array element
actually lies in the subscript range of the array. Thus C++ will allow the assignment of a value
to annual_temp[200], however the effect of this assignment is unpredictable. For example it
could lead to the program attempting to assign a value to a memory element that is outside the
program's allocated memory space. This would lead to the program being terminated by the
operating system. Alternatively it might actually access a memory location that is within the
allocated memory space of the program and assign a value to that location, changing the value
of the variable in your program which is actually associated with that memory location, or
overwriting the machine code of your program. Similarly reading a value from
annual_temp[200] might access a value that has not been set by the program or might be the
value of another variable. It is the programmer's responsibility to ensure that if an array is
declared with n elements then no attempt is made to reference any element with a subscript
95
COMPUTER PROGRAMMING
outside the range 0 to n-1. Using an index, or subscript, that is out of range is called Subscript
Overflow. Subscript overflow is one of the commonest causes of erroneous results and can
frequently cause very strange and hard to spot errors in programs.
Copying Arrays
Notice the use of a constant to store the array size. This avoids the literal constant '10' appearing
a number times in the code. If the code needs to be edited to use different sized arrays, only the
constant needs to be changed. If the constant is not used, all the '10's would have to be changed
individually - it is easy to miss one out.
An array may have more than one dimension. Each dimension is represented as a subscript in
the array. Therefore a two dimensional array has two subscripts, a three dimensional array has
three subscripts, and so on.
Arrays can have any number of dimensions, although most of the arrays that you create will
likely be of one or two dimensions.
A chess board is a good example of a two-dimensional array. One dimension represents the
eight rows, the other dimension represents the eight columns.
96
COMPUTER PROGRAMMING
Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.
A two-dimensional array can be think as a table, which will have x number of rows and y
number of columns. A 2-dimensional array a, which contains three rows and four columns can
be shown as below −
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a
is the name of the array, and i and j are the subscripts that uniquely identify each element in a.
For example:
Square board[8][8];
The program could also represent the same data with a one dimensional, 64-square array. For
example, it could include the statement
Square board[64];
Such a representation does not correspond as closely to the real-world object as the two
dimensional array, however.
Suppose that when the game begins. The king id located in the fourth position in the first row.
Counting from zero that position corresponds to board[0][3] in the two dimensional array,
assuming that the first subscript corresponds to the row, and the second to the column.
97
COMPUTER PROGRAMMING
steady. Therefore, if the program has an array int theArray[5][3], the first three elements go
int theArray[0]; the next three into theArray[1]; and so forth. The program initializes this
array by writing
Each value should be separated by comma, regardless of whither inner braces are include. The
entire initialization must set must appear within braces, and it must end with a semicolon.
4.3. String
In C++ strings of characters are held as an array of characters, one character held in each
array element. In addition a special null character, represented by `\0', is appended to the end
of the string to indicate the end of the string. Hence if a string has n characters then it requires
an n+1 element array (at least) to store it. Thus the character `a' is stored in a single byte,
whereas the single-character string "a" is stored in two consecutive bytes holding the character
`a' and the null character.
char s1[10];
98
COMPUTER PROGRAMMING
The string variable s1 could hold strings of length up to nine characters since space is needed
for the final null character. Strings can be initialized at the time of declaration just as other
variables are initialized. For example:
s1 |e|x|a|m|p|l|e|\0|
s2 |a|n|o|t|h|e|r| |e|x|a|m|p|l|e|\0|?|?|?|?|
In the first case the array would be allocated space for eight characters, that is space for the
seven characters of the string and the null character. In the second case the string is set by the
declaration to be twenty characters long but only sixteen of these characters are set, i.e. the
fifteen characters of the string and the null character. Note that the length of a string does not
include the terminating null character.
String Input
When the input stream cin is used space characters, newline etc. are used as separators and
terminators. Thus when inputting numeric data cin skips over any leading spaces and
terminates reading a value when it finds a white-space character (space, tab, newline etc.
). This same system is used for the input of strings, hence a string to be input cannot start with
99
COMPUTER PROGRAMMING
leading spaces, also if it has a space character in the middle then input will be terminated on
that space character. The null character will be appended to the end of the string in the character
array by the stream functions. If the string s1 was initialized as in the previous section, then
the statement
|f|i|r|s|t|\0|e|\0|
Note that the last two elements are a relic of the initialization at declaration time. If the string
that is entered is longer than the space available for it in the character array then C++ will just
write over whatever space comes next in memory. This can cause some very strange errors
when some of your other variables reside in that space!
To read a string with several words in it using cin we have to call cin once for each word. For
example to read in a name in the form of a Christian name followed by a surname we might
use code as follows:
char christian[12],
surname[12]; cout << "Enter
name "; cin >> christian; cin
>> surname;
cout << "The name entered was "
<< christian << " "
<< surname;
The name would just be typed by the user as, for example, Ian Aitchison and the output
would then be
The name entered was Ian Aitchison
Enter a string: Law is a bottomless pit.
You entered: Law
Where did the rest of the phrase go?
It turns the insertion operator >> consider a space to be a terminating character.
Thus it will read strings consisting of a single word, but anything typed after a space is thrown
away.
#include<iostream.h> void
main() { const int
max=80; char str[max];
100
COMPUTER PROGRAMMING
cout<<"\n Enter a
string;";
[Link](str,max); // max avoid buffer overflow
cout<<"\n You entered : "<<str;
}
Reading multiple lines
We have solved the problem of reading strings with embedded blanks, but what about strings
with multiple lines? It turns out that the cin::get() function can take a third argument to
help out in this situation.
This argument specifies the character that tells the function to stop reading. The default value
of this argument is the newline('\n')character, but if you call the function with some
other character for this argument, the default will be overridden by the specified character.
In the next example, we call the function with a dollar sign ('$') as the third argument
//reads multiple lines, terminates on '$' character
#include<iostream.h
> void main(){
const int max=80;
char str[max];
cout<<"\n Enter a string:\n";
[Link](str, max, '$'); //terminates with $
cout<<\n You entered:\n"<<str; }
now you can type as many lines of input as you want. The function will continue to
accept characters until you enter the terminated character $ (or untill you exceed the size of the
array. Remember, you must still press Enter key after typing the '$' character .
The strings in the program invites the user to type in a string. What happens if the user enters
a string that is longer than the array used to hold it? There is no built-in mechanism in C++ to
keep a program from inserting array elements outside an array.
However, it is possible to tell the >> operator to limit the number of characters it places in an
array.
101
COMPUTER PROGRAMMING
You can initialize a string to a constant value when you define it. Here's an example'
#include<iostream.h>
void main(){
char str[] = "Welcome to C++ programming language";
cout<<str;
}
if you tried to the string program with strings that contain more than one word , you may
have unpleasant surprise. Copying string the hard way
The best way to understand the true nature of strings is to deal with them character by character
#include<iostream.h>
#include<string.h> //for
strlen() void main() {
const int max=80;
char str1[]='' Oh, Captain, my Captain!"
our fearful trip is done"; char
str2[max];
for(int i=0;
i<strlen(str1);i++)
str2[i]=str1[1]; str2[i]='\0';
cout<<endl; cout<<str2;
}
Copying string the easy way
Ofcourse you don't need to use a for loop to copy a string. As you might have guesses, a
library function will do it for you. You can copy strings using strcpy or strncpy function.
We assign strings by using the string copy function strcpy. The prototype for this function
is in string.h.
strcpy(destination, source);
strcpy copies characters from the location specified by source to the
location specified by destination. It stops copying characters after it copies the terminating
null character.
102
COMPUTER PROGRAMMING
You must make sure that the destination string is large enough to hold all of the characters in
the source string (including the terminating null character).
Example:
#include <iostream.h> #include
<string.h> void main(){
char me[20] = "David";
cout << me << endl;
strcpy(me, "YouAreNotMe");
cout << me << endl ;
return;
}
There is also another function strncpy, is like strcpy, except that it copies only a specified
number of characters.
strncpy(destination, source, int n);
In C++ the + operator cannot normally be used to concatenate string, as it can in some
languages such as BASIC; that is you can't say
The function strcat concatenates (appends) one string to the end of another string.
strcat(destination, source);
o The first character of the source string is copied to the location of the terminating null
character of the destination string. o The destination string must have enough space to hold
both strings and a terminating null character.
103
COMPUTER PROGRAMMING
Example:
#include <iostream.h>
#include <string.h>
void main() {
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strcat(str1, "def");
cout << str1 << endl;
char str2[] =
"xyz"; strcat(str1,
str2); cout << str1
<< endl; str1[4] =
'\0'; cout << str1
<< endl;
}
The function strncat is like strcat except that it copies only a specified number of characters.
strncat(destination, source, int n);
104
COMPUTER PROGRAMMING
Comparing strings
Example:
#include <iostream.h> #include <string.h>
void main() { cout << strcmp("abc",
"def") << endl; cout << strcmp("def",
"abc") << endl; cout << strcmp("abc",
"abc") << endl; cout << strcmp("abc",
"abcdef") << endl; cout <<
strcmp("abc", "ABC") << endl;
}
The function strncmp is like strcmp except that it compares only a specified number of
characters.
strncmp(str1, str2, int n);
strncmp does not compare characters after a terminating null character has been found in one
of the strings.
Example:
#include <iostream.h>
#include <string.h>
void main()
{ cout << strncmp("abc", "def", 2) <<
endl; cout << strncmp("abc", "abcdef", 3) <<
endl; cout << strncmp("abc", "abcdef", 2) <<
endl; cout << strncmp("abc", "abcdef", 5) <<
endl; cout << strncmp("abc", "abcdef", 20)
<< endl;
}
Summary
105
COMPUTER PROGRAMMING
• An array may have more than one dimension. Each dimension is represented as a
subscript in the array. Therefore a two dimensional array has two subscripts, a three
dimensional array has three subscripts, and so on.
• String in C++ is nothing but a sequence of character in which the last character is the
null character ‗\0‘.
• In C++ strings of characters are held as an array of characters, one character held in
each array element.
• A special null character, represented by `\0', is appended to the end of the string to
indicate the end of the string.
Exercise
1. Write an array declaration for the following
A) A list of 100 floating_point voltage
B) A list of 100 integer years
C) A list of 30 characters
D) A list of 32 floating-point velocities
2. Write a program to input the following values into an array named volts: 10.95, 16.32, 8.22,
15.98, 26.22, 13.54, 8.22, 6.45, and 173.86. After the data has been entered, have your
program output the values.
3. Write a program to input eight integer numbers into an array named temp. As each number
is input, add the number into a total. After all numbers are input, display the number and
their average.
4. Determine the output produced by the following program #include <iostream.h> int main()
106
COMPUTER PROGRAMMING
int i,
j,val[3][4]={8,16,9,52,3,15,27,6,14,25,2,10};
5. Write a c++ program to select the values in a four by five array of integers in increasing
order and store the selected values in a single dimensional array named sort. Use the
following values to initialize the array 16, 22, 99, 4, 18, -258, 4, 101, 5, 98, 105, 6, 15, 2,
45, 33, 88, 72, 16.
6. What is the output of the following program?
7. Write a C++ program that takes two words from a user and compares their alphabetical
precedence.
107
COMPUTER PROGRAMMING
5 Reference
1. Walter Savitch, Problem Solving with C++( 6th ed), USA, Addison Wesley,2006
2. Dromey, R.G., How to solve it by computer, UK, Prentice Hall Inc. ,1982
3. GaddisTony, Starting out with C++, USA , Scott/Jones Inc. Publishers, 2001
4. Schildt Herbert, C++ - The Complete Reference(4th ed), USA, McGraw Hill Inc.
2001
5. Lafore, Robert, Object Oriented Programming in C++ (2nd ed),2001
6. Dietel&Dietel, ―C How To Program, Third Edition, Prentice – Hall, 2003
7. Robert Lafore, ―The Waite Group‘s programming Using Turbo C++ Techmedia,
1993
8. John R. Hubrard, ―Fundamentals of Computing with C++,‖ Shuam‘s Outline,
1997
9. Jess Liberry, ―An Introduction to C++ 1995
10. Robert Lafore, ―The Wait Group Object Oriented programming With C++ 1994
108