Basic Programming
Basic Programming
Chapter One
In order to solve a given problem, computers must be given the correct instruction about how
they can solve it. The terms computer programs, software programs, or just programs are
the instructions that tells the computer what to do. Computer requires programs to function,
and a computer programs does nothing unless its instructions are executed by a CPU.
Computer programming (often shortened to programming or coding) is the process of
writing, testing, debugging/troubleshooting, and maintaining the source code of computer
programs. Writing computer programs means writing instructions, that will make the
computer follow and run a program based on those instructions. Each instruction is relatively
simple, yet because of the computer's speed, it is able to run millions of instructions in a
second. A computer program usually consists of two elements:
Data – characteristics
Code – action
Computer programs (also known as source code) is often written by professionals known as
Computer Programmers (simply programmers). Source code is written in one of
programming languages. A programming language is an artificial language that can be used
to control the behavior 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
1
Fundamentals of Programming 2
Low-level languages
Computers only understand one language and that is binary language or the language of 1s
and 0s. Binary language is also known as machine language, one of low-level languages. In
the initial years of computer programming, all the instructions were given in binary form.
Although the computer easily understood these programs, it proved too difficult for a normal
human being to remember all the instructions in the form of 0s and 1s. Therefore, computers
remained mystery to a common person until other languages such as assembly language was
developed, which were easier to learn and understand.
2
Fundamentals of Programming 3
Using assembly language instructions, you can write the equation to calculate the weekly
wages as follows:
3
Fundamentals of Programming 4
LOAD rate
MULT hours
STOR wages
High-level languages
Although programming in assembly language is not as difficult and error prone as stringing
together ones and zeros, it is slow and cumbersome. In addition it is hardware specific. The
lack of portability between different computers led to the development of high-level
languages—so called because they permitted a programmer to ignore many low-level details
of the computer's hardware. Further, it was recognized that the closer the syntax, rules, and
mnemonics of the programming language could be to "natural language" the less likely it
became that the programmer would inadvertently introduce errors (called "bugs") into the
program. High-level languages are more English-like and, therefore, make it easier for
programmers to "think" in the programming language. High-level languages also require
translation to machine language before execution. This translation is accomplished by either a
compiler or an interpreter.
Interpreters are more interactive than compilers. FORTRAN (FORmula TRANslator), BASIC
(Bingers All Purpose Symbolic Instruction Code), PASCAL, C, C++, Java are some examples
of high-level languages.
4
Fundamentals of Programming 5
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.
5
Fundamentals of Programming 6
6
Fundamentals of Programming 7
Before a program is written, the programmer must clearly understand what data are to be
used, the desired result, and the procedure to be used to produce the result. The procedure, or
solution, selected is referred to as an algorithm. An algorithm is defined as a step-by-step
sequence of instructions that must terminate and describe how the data is to be processed to
produce the desired outputs. Simply, algorithm is a sequence of instructions. Algorithms are a
fundamental part of computing. There are three commonly used tools to help to document
program logic (the algorithm). These are flowcharts, structured chart, and Pseudocode. We
will use the three methods here. Generally, flowcharts work well for small problems but
Pseudocode is used for larger problems.
1.3.1 Pseudocode
Pseudocode (derived from pseudo and code) is a compact and informal high-level description
of a computer algorithm that uses the structural conventions of programming languages, but
typically omits detailes such as subroutines, variables declarations and system-specific syntax.
The programming language is augmented with natural language descriptions of the details,
where convenient, or with compact mathematical notation. The purpose of using pseudocode
is that it may be easier for humans to read than conventional programming languages, and that
it may be a compact and environment-independent generic description of the key principles of
an algorithm. No standard for pseudocode syntax exists, as a program in pseudocode is not an
executable program. As the name suggests, pseudocode generally does not actually obey the
synatx rules of any particular language; there is no systematic standard form, although any
particular writer will generally borrow the appearance of a particular language.
The programming process is a complicated one. You must first understand the program
specifications, of course, Then you need to organize your thoughts and create the program.
This is a difficult task when the program is not trivial (i.e. easy). You must break the main
tasks that must be accomplished into smaller ones in order to be able to eventually write fully
developed code. Writing pseudocode will save you time later during the construction &
testing phase of a program's development.
Example:
7
Fundamentals of Programming 8
Write a program that obtains two integer numbers from the user. It will print
out the sum of those numbers.
Pseudocode:
CelsusToFarh
(main func)
1.3.3 Flowchart
A flowchart (also spelled flow-chart and flow chart) is a schematic representation of an
algorithm or a process . The advantage of flowchart is it doesn’t depend on any particular
programming language, so that it can used, to translate an algorithm to more than one
programming language. Flowchart uses different symbols (geometrical shapes) to represent
different processes. The following table shows some of the common symbols.
Example 1: - Draw flow chart of an algorithm to add two numbers and display their result.
Algorithm description
Read the rules of the two numbers (A and B)
Add A and B
Assign the sum of A and B to C
Display the result ( c)
9
Fundamentals of Programming 10
Read A, B
C= A+B
Print C
End
Example 2: Write an algorithm description and draw a flow chart to check a number is
negative or not.
Algorithm description.
1/ Read a number x
2/ If x is less than zero write a message negative
else write a message not negative
10
Fundamentals of Programming 11
Initialization: - Setting of variables of the computation to their initial values and setting the
counter for determining to exit from the loop.
Computation: - Processing
Test: - Every loop must have some way of exiting from it or else the program would endlessly
remain in a loop.
Increment: - Re-initialization of the loop for the next loop.
Example 3: - Write the algorithmic description and draw a flow chart to find the following
sum.
Sum = 1+2+3+…. + 50
Algorithmic description
1. Initialize sum too and counter to 1
1.1.If the counter is less than or equal to 50
1.2.Else
• Exit
2. Write sum
The Systems Development Life Cycle (SDLC) is a conceptual model used in project
11
Fundamentals of Programming 12
management that describes the stages involved in a computer system development project
from an initial feasibility study through maintenance of the completed application. The phases
of SDLC is discussed below briefly.
The first step is to identify a need for the new system. This will include determining whether
a business problem or opportunity exists, conducting a feasibility study to determine if the
proposed solution is cost effective, and developing a project plan.
This process may involve end users who come up with an idea for improving their work or
may only involve IS people. Ideally, the process occurs in tandem with a review of the
organization's strategic plan to ensure that IT is being used to help the organization achieve its
strategic objectives. Management may need to approve concept ideas before any money is
budgeted for its development.
A preliminary analysis, determining the nature and scope of the problems to be solved is
carried out. Possible solutions are proposed, describing the cost and benefits. Finally, a
preliminary plan for decision making is produced.
The process of developing a large information system can be very costly, and the
investigation stage may require a preliminary study called a feasibility study, which includes
e.g. the following components:
a. Organisational Feasibility
How well the proposed system supports the strategic objectives of the organization.
b. Economic Feasibility
Cost savings
Increased revenue
Decreased investment
Increased profits
12
Fundamentals of Programming 13
c. Technical Feasibility
d. Operational Feasibility
End users must be involved in this process to ensure that the new system will function
adequately and meets their needs and expectations.
The created system design, but must reviewed by users to ensure the design meets users'
needs.
13
Fundamentals of Programming 14
1.4.5 Implementation
The real code is written here. Systems implementation is the construction of the new system
and its delivery into production or day-to-day operation.The key to understanding the
implementation phase is to realize that there is a lot more to be done than programming.
Implementation requires programming, but it also requires database creation and population,
and network installation and testing. You also need to make sure the people are taken care of
with effective training and documentation. Finally, if you expect your development skills to
improve over time, you need to conduct a review of the lessons learned.
1.4.8 Maintenance
What happens during the rest of the software's life: changes, correction, additions, moves to a
different computing platform and more. This, the least glamorous and perhaps most important
step of all, goes on seemingly forever.
14
Fundamentals of Programming 15
Chapter 2
2. C++ Basics
The C++ programming languages can be thought of as the C programming language with
classes (and other modern features added). The C programming language was developed by
Dennis Ritchie of AT&T Bell Laboratories in the 1970s. It was first used for writing and
maintaining the UNIX operating system. (Up until that time, UNIX systems programs were
written either in assembly language or in a language called B, a language developed by Ken
Thompson, the originator of UNIX.) The C language is peculiar because it is a high-level
language with many of the features of a low-level language. C is somewhere in between the
two extremes of a very high-level language and a low-level language, and therein lies both its
strengths and its weaknesses. Like (low-level) assembly language, C language programs can
directly manipulate the computer’s memory. On the other hand, C has the features of a high-
level language, which makes it easier to read and write than assembly language. This makes C
an excellent choice for writing systems programs, but for other programs (and in some sense
even for systems programs) C is not as easy to understand as other languages; also, it does not
have as many automatic checks as some other high-level languages. To overcome these and
other shortcomings of C, Bjarne Stroustrup of AT&T Bell Laboratories developed C++ in the
early 1980s. Stroustrup designed C++ to be a better C. Most of C is a subset of C++, and so
most C programs are also C++ programs. (The reverse is not true; many C++ programs are
definitely not C programs.) Unlike C, C++ has facilities for classes and so can be used for
object-oriented programming.
15
Fundamentals of Programming 16
16
Fundamentals of Programming 17
with a library of useful functions (or procedures) and classes that you can include in your
program. A function is a block of code that performs a service, such as adding two numbers or
printing to the screen. A class is a collection of data and related functions.
Summary
The steps to create an executable file are
17
Fundamentals of Programming 18
The preprocessor runs before your compiler each time the compiler is invoked. The
preprocessor translates any line that begins with a pound symbol (#) into a special command,
getting your code file ready for the compiler.
Line 3 begins the actual program with a function named main(). Every C++ program has a
main() function. In general, a function is a block of code that performs one or more actions.
Usually functions are invoked or called by other functions, but main() is special. When your
program starts, main() is called automatically.
main(), like all functions, must state what kind of value it will return. The return value type
for main() in HELLO.CPP is int, which means that this function will return an integer value.
All functions begin with an opening brace ({) and end with a closing brace (}). The braces for
the main() function are on lines 4 and 7. Everything between the opening and closing braces
is considered a part of the function.
The meat and potatoes of this program is on line 5. The object cout is used to print a message
to the screen. cout is used in C++ to print strings and values to the screen. A string is just a set
of characters.
Here's how cout is used: type the word cout, followed by the output redirection operator (<<).
Whatever follows the output redirection operator is written to the screen. If you want a string
of characters written, be sure to enclose them in double quotes ("), as shown on line 5. A text
string is a series of printable characters.
The final two characters, \n, tell cout to put a new line after the words Hello World! All
ANSI-compliant programs declare main() to return an int. This value is "returned" to the
operating system when your program completes. Some programmers signal an error by
returning the value 1.
The main() function ends on line 7 with the closing brace.
18
Fundamentals of Programming 19
+ - * /
. ; ? ,
<= != == >=
The first row includes mathematical symbols for addition, subtraction, multiplication and
division. The second row consists of punctuation marks taken from English grammar. Note
that the comma is also a special symbol. In C++, commas are used to separate items in a list.
Semicolons are used to end a C++ statement. Note that the blank, which is not shown above,
is also a special symbol. You create a blank symbol by pressing the space bar (only once) on
the keyboard. The third row consists of tokens made of two characters that are regarded as a
single symbol. No character can come between the two characters in the token, not even a
blank.
2.3.2 Keywords (reserved words)
Reserved/Key words have a unique meaning within a C++ program. These symbols, the
reserved words, must not be used for any other purposes. All reserved words are in lower-case
letters. The following are some of the reserved words of C++.
asm auto bool break case catch
const_cast class const char continue default
dynamic_cast do double delete else enum
explicit extern false float for friend
goto if inline int long mutable
namespace new operator private protected public
reinterpret_cast register return short signed sizeof
static_cast static struct switch template this
throw true try typedef typeid typename
19
Fundamentals of Programming 20
Notice that main is not a reserved word. However, this is a fairly technical distinction, and for
practical purposes you are advised to treat main, cin, and cout as if they were reserved as well.
2.3.3. Identifiers
An identifier is name associated with a function or data object and used to refer to that
function or data object. An identifier must:
Start with a letter or underscore
Consist only of letters, the digits 0-9, or the underscore symbol _
Not be a reserved word
For the purposes of C++ identifiers, the underscore symbol, _, is considered to be a letter. Its
use as the first character in an identifier is not recommended though, because many library
functions in C++ use such identifiers. Similarly, the use of two consecutive underscore
symbols, _ _, is forbidden.
The following are valid identifiers
Length days_in_year DataSet1 Profit95
Int _Pressure first_one first_1
Although using _Pressure is not recommended.
The following are invalid:
2.3.4 Literals
Literals are constant values which can be a number, a character of a string. For example the
number 129.005, the character ‘A’ and the string “hello world” are all literals. There is no
identifier that identifies them.
2.3.5 Comments
A comment is a piece of descriptive text which explains some aspect of a program. Program
comments are totally ignored by the compiler and are only intended for human readers. C++
provides two types of comment delimiters:
Anything after // (until the end of the line on which it appears) is considered a
comment.
Anything enclosed by the pair /* and */ is considered a comment.
Variable Declaration
Declaring a variable means defining (creating) a variable. You create or define a variable by
stating its type, followed by one or more spaces, followed by the variable name and a
semicolon. The variable name can be virtually any combination of letters, but cannot contain
spaces and the first character must be a letter or an underscore. Variable names cannot also be
the same as keywords used by C++. Legal variable names include x, J23qrsnf, and myAge.
Good variable names tell you what the variables are for; using good names makes it easier to
21
Fundamentals of Programming 22
understand the flow of your program. The following statement defines an integer variable
called myAge:
int myAge;
IMPORTANT- Variables must be declared before used!
As a general programming practice, avoid such horrific names as J23qrsnf, and restrict single-
letter variable names (such as x or i) to variables that are used only very briefly. Try to use
expressive names such as myAge or howMany.
A point worth mentioning again here is that C++ is case-sensitive. In other words, uppercase
and lowercase letters are considered to be different. A variable named age is different from
Age, which is different from AGE.
Creating More Than One Variable at a Time
You can create more than one variable of the same type in one statement by writing the type
and then the variable names, separated by commas. For example:
int myAge, myWeight; // two int variables
long area, width, length; // three longs
As you can see, myAge and myWeight are each declared as integer variables. The second line
declares three individual long variables named area, width, and length. However keep in mind
that you cannot mix types in one definition statement.
Assigning Values to Your Variables
You assign a value to a variable by using the assignment operator (=). Thus, you would assign
5 to Width by writing
int Width;
Width = 5;
You can combine these steps and initialize Width when you define it by writing
int Width = 5;
Initialization looks very much like assignment, and with integer variables, the difference is
minor. The essential difference is that initialization takes place at the moment you create the
variable.
Just as you can define more than one variable at a time, you can initialize more than one
variable at creation. For example:
// create two int variables and initialize them
22
Fundamentals of Programming 23
23
Fundamentals of Programming 24
17: }
Output: Width:5
Length: 10
Area: 50
Line 2 includes the required include statement for the iostream's library so that cout will work.
Line 4 begins the program.
On line 6, Width is defined as an unsigned short integer, and its value is initialized to 5.
Another unsigned short integer, Length, is also defined, but it is not initialized. On line 7, the
value 10 is assigned to Length.
On line 11, an unsigned short integer, Area, is defined, and it is initialized with the value
obtained by multiplying Width times Length. On lines 13-15, the values of the variables are
printed to the screen. Note that the special word endl creates a new line.
2.5.2 Wrapping around integer values
The fact that unsigned long integers have a limit to the values they can hold is only rarely a
problem, but what happens if you do run out of room? When an unsigned integer reaches its
maximum value, it wraps around and starts over, much as a car odometer might. The
following example shows what happens if you try to put too large a value into a short integer.
Example: A demonstration of putting too large a value in a variable
1: #include <iostream.h>
2: int main()
3: {
4: unsigned short int smallNumber;
5: smallNumber = 65535;
6: cout << "small number:" << smallNumber << endl;
7: smallNumber++;
8: cout << "small number:" << smallNumber << endl;
9: smallNumber++;
10: cout << "small number:" << smallNumber << endl;
11: return 0;
12: }
Output: small number:65535
25
Fundamentals of Programming 26
small number:0
small number:1
A signed integer is different from an unsigned integer, in that half of the values you can
represent are negative. Instead of picturing a traditional car odometer, you might picture one
that rotates up for positive numbers and down for negative numbers. One mile from 0 is either
1 or -1. When you run out of positive numbers, you run right into the largest negative
numbers and then count back down to 0. The whole idea here is putting a number that is
above the range of the variable can create unpredictable problem.
Example: A demonstration of adding too large a number to a signed integer.
1: #include <iostream.h>
2: int main()
3: {
4: short int smallNumber;
5: smallNumber = 32767;
6: cout << "small number:" << smallNumber << endl;
7: smallNumber++;
8: cout << "small number:" << smallNumber << endl;
9: smallNumber++;
10: cout << "small number:" << smallNumber << endl;
11: return 0;
12: }
Output: small number:32767
small number:-32768
small number:-32767
IMPORTANT – To any variable, do not assign a value that is beyond its range!
2.5.3. Characters
Character variables (type char) are typically 1 byte, enough to hold 256 values. A char can be
interpreted as a small number (0-255) or as a member of the ASCII set. ASCII stands for the
American Standard Code for Information Interchange. The ASCII character set and its ISO
26
Fundamentals of Programming 27
(International Standards Organization) equivalent are a way to encode all the letters,
numerals, and punctuation marks.
In the ASCII code, the lowercase letter "a" is assigned the value 97. All the lower- and
uppercase letters, all the numerals, and all the punctuation marks are assigned values between
1 and 128. Another 128 marks and symbols are reserved for use by the computer maker,
although the IBM extended character set has become something of a standard.
There is another data type for storing characters which is wide character type, the wchar_t
(wide character type) type comprises at least 2 bytes (16 bits) and is thus capable of storing
modern Unicode characters. Unicode is a 16-bit code also used in Windows NT and
containing codes for approximately 35,000 characters in 24 languages.
2.5.4. Characters and Numbers
When you put a character, for example, `a', into a char variable, what is really there is just a
number between 0 and 255. The compiler knows, however, how to translate back and forth
between characters (represented by a single quotation mark and then a letter, numeral, or
punctuation mark, followed by a closing single quotation mark) and one of the ASCII values.
The value/letter relationship is arbitrary; there is no particular reason that the lowercase "a" is
assigned the value 97. As long as everyone (your keyboard, compiler, and screen) agrees,
there is no problem. It is important to realize, however, that there is a big difference between
the value 5 and the character `5'. The latter is actually valued at 53, much as the letter `a' is
valued at 97.
Floating-Point Types
Numbers with a fraction part are indicated by a decimal point in C++ and are referred to as
floating-point numbers. In contrast to integers, floating-point numbers must be stored to a
preset accuracy. The following three types are available for calculations involving floating-
point numbers:
Float-----------------for simple accuracy
Double---------------for double accuracy
Long double---------for high accuracy
The value range and accuracy of a type are derived from the amount of memory
allocated and the internal representation of the type.
Accuracy is expressed in decimal places. This means that “six decimal places” allows
27
Fundamentals of Programming 28
a programmer to store two floating-point numbers that differ within the first six
decimal places as separate numbers. In reverse, there is no guarantee that the figures
12.3456 and 12.34561 will be distinguished when working to a accuracy of six decimal
places. And remember, it is not a question of the position of the decimal point, but
merely of the numerical sequence.
2.6. Operators
C++ provides operators for composing arithmetic, relational, logical, bitwise, and conditional
expressions. It also provides operators which produce useful side-effects, such as assignment,
increment, and decrement. We will look at each category of operators in turn. We will also
discuss the precedence rules which govern the order of operator evaluation in a multi-operator
expression.
2.6.1. Assignment Operators
The assignment operator is used for storing a value at some memory location (typically
denoted by a variable). Its left operand should be an lvalue, and its right operand may be an
arbitrary expression. The latter is evaluated and the outcome is stored in the location denoted
by the lvalue. An lvalue (standing for left value) is anything that denotes a memory location in
which a value may be stored. The only kind of lvalue we have seen so far is a variable. Other
kinds of lvalues (based on pointers and references) will be described later. The assignment
operator has a number of variants, obtained by combining it with the arithmetic and bitwise
operators.
Operator Example Equivalent To
= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n - 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25
%= n %= 25 n = n % 25
&= n &= 0xF2F2 n = n & 0xF2F2
|= n |= 0xF2F2 n = n | 0xF2F2
^= n ^= 0xF2F2 n = n ^ 0xF2F2
28
Fundamentals of Programming 29
An assignment operation is itself an expression whose value is the value stored in its left
operand. An assignment operation can therefore be used as the right operand of another
assignment operation. Any number of assignments can be concatenated in this fashion to form
one expression. For example:
int m, n, p;
m = n = p = 100; // means: n = (m = (p = 100));
m = (n = p = 100) + 2; // means: m = (n = (p = 100)) + 2;
This is equally applicable to other forms of assignment. For example:
m = 100;
m += n = p = 10; // means: m = m + (n = p = 10);
Unintended integer divisions are a common source of programming errors. To obtain a real
division when both operands are integers, you should cast one of the operands to be real:
Int cost = 100;
Int volume = 80;
double unitPrice = cost / (double) volume; // gives 1.25
The remainder operator (%) expects integers for both of its operands. It returns the remainder
of integer-dividing the operands. For example 13%3 is calculated by integer dividing 13 by 3
to give an outcome of 4 and a remainder of 1; the result is therefore 1.
It is possible for the outcome of an arithmetic operation to be too large for storing in a
designated variable. This situation is called an overflow. The outcome of an overflow is
machine-dependent and therefore undefined. For example:
unsigned char k = 10 * 92; // overflow: 920 > 255
It is illegal to divide a number by zero. This results in a run-time division-by-zero failure,
which typically causes the program to terminate.
There are also a number of predefined library functions, which perform arithmetic operations.
As with input & output statements, if you want to use these you must put a #include statement
at the start of your program. Some of the more common library functions are summarized
below.
30
Fundamentals of Programming 31
Note that the <= and >= operators are only supported in the form shown. In particular, =< and
=> are both invalid and do not mean anything.
The operands of a relational operator must evaluate to a number. Characters are valid
operands since they are represented by numeric values. For example (assuming ASCII
coding):
'A' < 'F' // gives 1 (is like 65 < 70)
The relational operators should not be used for comparing strings, because this will result in
the string addresses being compared, not the string contents. For example, the expression
"HELLO" < "BYE" causes the address of "HELLO" to be compared to the address of "BYE".
As these addresses are determined by the compiler (in a machine-dependent manner), the
outcome may be 0 or 1, and is therefore undefined. C++ provides library functions (e.g.,
strcmp) for the lexicographic comparison of string.
31
Fundamentals of Programming 32
Logical negation is a unary operator, which negates the logical value of its single operand. If
its operand is nonzero it produces 0, and if it is 0 it produces 1.
Logical and produces 0 if one or both of its operands evaluate to 0. Otherwise, it produces1.
Logical or produces 0 if both of its operands evaluate to 0. Otherwise, it produces 1.
Note that here we talk of zero and nonzero operands (not zero and 1). In general, any nonzero
value can be used to represent the logical true, whereas only zero represents the logical false.
The following are, therefore, all valid logical expressions:
!20 // gives 0
10 && 5 // gives 1
10 || 5.5 // gives 1
10 && 0 // gives 0
C++ does not have a built-in boolean type. It is customary to use the type int for this purpose
instead. For example:
int sorted = 0; // false
int balanced = 1; // true
C++ provides six bitwise operators for manipulating the individual bits in an integer quantity.
These are summarized in the table below.
32
Fundamentals of Programming 33
Bitwise operators expect their operands to be integer quantities and treat them as bit
sequences. Bitwise negation is a unary operator which reverses the bits in its operands.
Bitwise and compares the corresponding bits of its operands and produces a 1 when both bits
are 1, and 0 otherwise. Bitwise or compares the corresponding bits of its operands and
produces a 0 when both bits are 0, and 1 otherwise. Bitwise exclusive or compares the
corresponding bits of its operands and produces a 0 when both bits are 1 or both bits are 0,
and 1 otherwise.
Bitwise left shift operator and bitwise right shift operator both take a bit sequence as their left
operand and a positive integer quantity n as their right operand. The former produces a bit
sequence equal to the left operand but which has been shifted n bit positions to the left. The
latter produces a bit sequence equal to the left operand but which has been shifted n bit
positions to the right. Vacated bits at either end are set to 0.
The auto increment (++) and auto decrement (--) operators provide a convenient way of,
respectively, adding and subtracting 1 from a numeric variable. These are summarized in the
following table. The examples assume the following variable definition:
int k = 5;
33
Fundamentals of Programming 34
Both operators can be used in prefix and postfix form. The difference is significant. When
used in prefix form, the operator is first applied and the outcome is then used in the
expression. When used in the postfix form, the expression is evaluated first and then the
operator applied. Both operators may be applied to integer as well as real variables, although
in practice real variables are rarely useful in this form.
The amount of memory needed to store an object of a certain type can be ascertained
sizeof(name)
Yields the size of an object in bytes, and the parameter name indicates the object type or the
object itself. For example, sizeof(int) represents a value of 2 or 4 depending on the machine.
In contrast, sizeof(float) will always equal 4.
Following is the example, which will produce correct size of various data types on
your computer.
1. #include<iostream.h>
2. int main()
3. {
4. cout << "Size of char : " << sizeof(char) << endl;
5. cout << "Size of int : " << sizeof(int) <<endl;
6. cout << "Size of short int : " << sizeof(short int) << endl;
7. cout << "Size of long int : " << sizeof(long int) << endl;
8. cout << "Size of float : " << sizeof(float) << endl;
9. cout << "Size of double : " << sizeof(double) << endl;
10. cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
11. return 0;
12. }
When the above code is compiled and executed, it produces the following result which
34
Fundamentals of Programming 35
Output:
Size of char : 1
Size of int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4
35
Fundamentals of Programming 36
As shown by these examples, the built-in type identifiers can be used as type operators. Type
operators are unary (i.e., take one operand) and appear inside brackets to the left of their
operand. This is called explicit type conversion. When the type name is just one word, an
alternate notation may be used in which the brackets appear around the operand:
In some cases, C++ also performs implicit type conversion. This happens when values of
different types are mixed in an expression. For example:
36
Fundamentals of Programming 37
37
Fundamentals of Programming 38
#include <iostream.h>
int main (void)
{
int workDays = 5;
float workHours = 7.5;
float payRate, weeklyPay;
Analysis
This line outputs the prompt ‘What is the hourly pay rate? ’ to seek user input.
This line reads the input value typed by the user and copies it to payRate. The input operator
>> takes an input stream as its left operand (cin is the standard C++ input stream which
corresponds to data entered via the keyboard) and a variable (to which the input data is
copied) as its right operand.
When run, the program will produce the following output (user input appears in bold):
38
Fundamentals of Programming 39
Both << and >> return their left operand as their result, enabling multiple input or multiple
output operations to be combined into one statement. This is illustrated by example below
which now allows the input of both the daily work hours and the hourly pay rate.
Example
#include <iostream.h>
cout << "What are the work hours and the hourly pay rate? ";
cin >> workHours >> payRate;
39
Fundamentals of Programming 40
This line is the result of combining lines 10-12 from example 2.1. It outputs "Weekly Pay = ",
followed by the value of weeklyPay, followed by a newline character. This statement is
equivalent to:
((cout << "Weekly Pay = ") << weeklyPay) << '\n';
Because the result of << is its left operand, (cout << "Weekly Pay = ") evaluates to cout
which is then used as the left operand of the next << operator, etc.
When run, the program will produce the following output:
What are the work hours and the hourly pay rate? 7.5 33.55
Weekly Pay = 1258.125
2.9.2. Null statement
Syntax:
;
Description: Do nothing
2.9.3. The block statement
Syntax:
{
[<Declarations>].
<List of statements/statement block>.
}
Any place you can put a single statement, you can put a compound statement, also called a
block. A block begins with an opening brace ({) and ends with a closing brace (}). Although
every statement in the block must end with a semicolon, the block itself does not end with a
semicolon. For example
{
temp = a;
a = b;
b = temp;
}
This block of code acts as one statement and swaps the values in the variables a and b.
40
Fundamentals of Programming 41
Chapter 3
Control statement
3.1. Introduction
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.
Like many other procedural languages, C++ provides different forms of statements for
different purposes. Declaration statements are used for defining variables. Assignment-
like statements are used for simple, algebraic computations. Branching statements are
used for specifying alternate paths of execution, depending on the outcome of a logical
condition. Loop statements are used for specifying computations, which need to be
repeated until a certain logical condition is satisfied. Flow control statements are used
41
Fundamentals of Programming 42
to divert the execution path to another part of the program. We will discuss these in
turn.
if(expression)
statement;
First expression is evaluated. If the outcome is nonzero (true) then statement is
executed. Otherwise, nothing happens.
For example, when dividing two values, we may want to check that the
denominator is nonzero:
if (count != 0)
average = sum / count;
To make multiple statements dependent on the same condition, we can use a
compound statement:
if (balance > 0) {
interest = balance *
creditRate; balance +=
interest;
}
if (expression)
statement1;
else
42
Fundamentals of Programming 43
statement2;
For example:
if (balance > 0) {
interest = balance * creditRate;
balance += interest;
} else {
interest = balance * debitRate;
balance += interest;
}
Given the similarity between the two alternative parts, the whole statement can be simplified
to:
if (balance > 0)
interest = balance * creditRate;
else
interest = balance * debitRate;
balance += interest;
Or just:
43
Fundamentals of Programming 44
For example:
if (callHour > 6) {
if (callDuration <= 5)
else
} else
charge = flatFee;
kind = lowerLetter;
else
kind = special;
}
}
44
Fundamentals of Programming 45
The switch statement provides a way of choosing between a set of alternatives, based
on the value of an expression. The general form of the switch statement is:
switch (expression) {
case constant1:
statements;
...
case constantn:
statements;
default:
statements;
}
First expression (called the switch tag) is evaluated, and the outcome is compared to each
of the numeric constants (called case labels), in the order they appear, until a match is
found. The statements following the matching case are then executed. Note the plural:
each case may be followed by zero or more statements (not just one statement).
Execution continues until either a break statement is encountered or all intervening
statements until the end of the switch statement are executed. The final default case is
optional and is exercised if none of the earlier cases provide a match.
For example, suppose we have parsed a binary arithmetic operation into its three
components and stored these in variables operator, operand1, and operand2. The
following switch statement performs the operation and stores the result in result.
switch (operator) {
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
45
Fundamentals of Programming 46
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.
It should be obvious that any switch statement can also be written as multiple if-else
statements. The above statement, for example, may be written as:
if (operator == '+')
result = operand1 + operand2;
else if (operator == '-')
result = operand1 - operand2;
46
Fundamentals of Programming 47
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:
while (expression)
{
statement;
}
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.
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;
}
47
Fundamentals of Programming 48
For n set to 5, Table 2.9 provides a trace of the loop by listing the values of the variables
involved and the loop condition.
It is not unusual for a while loop to have an empty body (i.e., a null statement).
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. The general form of
the for statement is:
First expression1 is evaluated. Each time round the loop, expression2 is evaluated. If
Otherwise, the loop is terminated. The general for loop is equivalent to the following while
loop:
48
Fundamentals of Programming I
expression1;
while
(expre
ssion2
){
statem
ent;
expres
sion3;
}
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:
Contrary to what may appear, the scope for i is not the body of the loop, but
the loop itself. Scope-wise, the above is equivalent to:
int i;
Page 49
Fundamentals of Programming I
for (i = 1; i
<= n; ++i)
sum += i;
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:
(1,1)
(1,2)
(1,3)
(2,1)
(2,2)
Page 50
Fundamentals of Programming I
(2,3)
(3,1)
(3,2)
(3,3)
The do statement (also called do loop) is similar to the while statement, except
that its body is executed first and then the loop condition is examined. The
general form of the do statement is:
do
statement;
while (expression);
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. 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);
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.
Page 51
Fundamentals of Programming I
The continue statement terminates the current iteration of a loop and instead
jumps to the next iteration. It applies to the loop immediately enclosing the
continue statement. It is an error to use the continue statement outside a loop.
In a 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);
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:
for (i = 0; i <
n; ++i) {
cin >>
num;
if (num < 0) continue; // causes a jump to: ++i
// process num here...
}
Page 52
Fundamentals of Programming I
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:
while (more) {
for (i = 0; i <
n; ++i) { cin
>> num;
if (num < 0) continue; // causes a jump to: ++i
// process num here...
}
//etc...
}
3.4.2. The ‘break’ Statement
A break statement may appear inside a loop (while, do, or for) or a switch
statement. It causes a jump out of these constructs, and hence terminates them.
Like the continue statement, a break statement only applies to the loop or switch
immediately enclosing it. It is an error to use the break statement outside a
loop or a switch.
For example, suppose we wish to read in a user password, but would like to
allow the user a limited number of attempts:
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.
Page 53
Fundamentals of Programming I
verified = 0;
for (i = 0; i < attempts &&
!verified; ++i) { cout <<
"Please enter your password:
"; cin >> password;
verified =
Verify(password));
if (!verified)
cout << "Incorrect!\n";
}
The goto statement provides the lowest-level of jumping. It has the general form:
goto label;
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:
Because goto provides a free and unstructured form of jumping (unlike break
and continue), it can be easily misused. Most programmers these days avoid
Page 54
Fundamentals of Programming I
The return statement enables a function to return a value to its caller. It has
the general form:
return expression;
where expression denotes the value returned by the function. The type of this
value should match the return type of the function. For a function whose return
type is void, expression should be empty:
return;
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’s
conventional to return 0 from main when the program executes without errors.
Otherwise, a non-zero error code is returned. For example:
When a function has a non-void return value (as in the above example), failing to
return a value will result in a compiler warning. The actual return value will be
undefined in this case (i.e., it will be whatever value which happens to be in its
corresponding memory location at the time).
Page 55