Chapter –Three
Decision statement
Decision something that represents a branching point in a solution
Outcomes are often dependent on initial conditions
Without decision statements (or other dynamic control structures), programs are
static
Static programs do exactly the same things each time they are executed
Dynamic programs do not
Boolean Based on values those are either true or false
True and False values are often represented by 1’s and 0’s, respectively
AUB
1. Expression is True if A and B are both true
A Ù B A AND B
2. Expression is True if A and B are both true
A V B A or B
Expression is true if either A or B is true
LOOPS
Loop is a control structure that allows for a sequence of steps to be
repeated a certain number of times. This sequence of steps is called the
body of the loop.
There are three basic loop structures in programming:
For
While
Do While Repeat
A While loop: - is a control structure where the body is repeated as long as the
condition is true.
1
While loop format:-
While (expression) statement and its function are simply to repeat statement while
expressions true.
For example, we are going to make a program to count down using a while loop:
// custom countdown using while
#include <iostream.h>
int main ()
int n; cout << "Enter the starting number > ";
cin >> n;
while (n>0)
{ cout << n << ", "; --n; }
cout << "FIRE!";
return 0; }
output is Enter the starting number > 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
The do-while loop.
Do-while loop Format:
Do statement while (condition);
Its functionality is exactly the same as the while loop except that condition the do-
while is evaluated after the execution of statement instead of before, granting at
least one execution of statement even if condition is never fulfilled. For example,
the following program echoes any number you enter until you enter 0.
Example
//
#include <iostream.h>
int main ()
{ unsigned long n;
do {
2
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n"; }
while (n != 0);
return 0;
Out put is Enter number (0 to end):
12345 You entered: 12345
Enter number (0 to end):
160277 You entered: 160277 Enter number (0 to end): 0 You entered: 0
The do-while loop is usually used when the condition that has to determine its end
is determined within the loop statement, like in the previous case, where the user
input within the block of instructions is what determines the end of the loop. If you
never enter the 0 value in the previous example the loop will never end.
The For loop.
Its format is:
For (initialization; condition; increase) statement;
And its main function is to repeat statement while condition remains true, like the
while loop. But in addition, for provides places to specify an initialization
instruction and an increase instruction. So this loop is specially designed to
perform a repetitive action with a counter.
It works the following way:
1, initialization is executed. Generally it is an initial value setting for a counter
variable. This is executed only once. 2, condition is checked, if it is true the loop
continues, otherwise the loop finishes and statement is skipped. 3, statement is
executed. As usual, it can be either a single instruction or a block of instructions
enclosed within curly brackets { }. 4, finally, whatever is specified in the increase
field is executed and the loop gets back to step 2.
Here is an example of countdown using a for loop.
Example
3
// countdown using a for loop
#include <iostream.h>
int main ()
{ for (int n=10; n>0; n--) {
cout << n << ", "; }
cout << "FIRE!";
return 0;
Output is 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
The initialization and increase fields are optional. They can be avoided but not the
semicolon signs among them. For example we could write: for (;n<10;) if we want
to specify no initialization and no increase; or for (;n<10;n++) if we want to
include an increase field but not an initialization.
Optionally, using the comma operator (,) we can specify more than one instruction
in any of the fields included in a for loop, like in initialization, for example. The
comma operator (,) is an instruction separator, it serves to separate more than one
instruction where only one instruction is generally expected. For example, suppose
that we wanted to initialize more than one variable in our loop:
ARRAYS
ARRAY: are a series of elements (variables) of the same type placed
consecutively in memory that can be individually referenced by adding an
index to a unique name. That means that, for example, we can store 5
values of type int without having to declare 5 different variables each with a
different identifier. Instead, using an array we can store 5 different values of
the same type, int for example, with a unique identifier.
For example, an array to contain 5 integer values of type int could be
represented this way:
Int = [5]
4
0 1 2 3 4
where each blank panel represents an element of the array, that in this case
are integer values of type int. These are numbered from 0 to 4 since in
arrays the first index is always 0, independently of its length.
Like any other variable, an array must be declared before it is used. A
typical declaration for an array in C++ is:
Type name [elements]; where type is a valid object type (int, float...), name
is a valid variable identifier and the elements field, that is enclosed within
brackets [], specifies how many of these elements the array contains.
Therefore, to declare billy as shown above it is as simple as the following
sentence:
Int [5];
NOTE: The elements field within brackets [] when declaring an array must be a
constant value, since arrays are blocks of static memory of a given size and the
compiler must be able to determine exactly how much memory it must assign to
the array before any instruction is considered.
Initializing arrays.
When declaring an array of local scope (within a function), if we do not
specify otherwise, it will not be initialized, so its content is undetermined
until we store some values in it.
If we declare a global array (outside any function) its content will be
initialized with all its elements filled with zeros. Thus, if in the global scope
we declare:
Example of single Dimensional Array int [5]= {12, 2, 10, 40, 15};
This means
0 1 2 3 4
12 2 10 40 15
Single Dimensional Array : single elements in the array that we
initialized within curly brackets { } must match the length in elements that
we declared for the array enclosed within square brackets [ ]. For example,
in the example of the array we have declared that it had 5 elements and in
5
the list of initial values within curly brackets { } we have set 5 different
values, one for each element. Because this can be considered useless
repetition, C++ includes the possibility of leaving the brackets empty [ ]
and the size of the Array will be defined by the number of values included
between curly brackets { }:
Multi-dimensional Array: Multidimensional arrays can be described as
arrays of arrays. For example, a Dimensional array can be imagined as a
dimensional table of a uniform concrete data type.
Int [3] [5]; Rember that array indices always begin by 0.
Multidimensional arrays are not limited to two indices (two dimensions).
They can contain as many indices as needed, although it is rare to have to
represent more than 3 dimensions. Just consider the amount of memory that
an array with many indices may need. For example: char century [100][365]
[24][60][60]; assigns a char for each second contained in a century, that is
more than 3 billion chars! This would consume about 3000 megabytes of
RAM memory if we could declare it. Multidimensional arrays are nothing
more than an abstraction, since we can obtain the same results with a
simple array just by putting a factor between its indices:
Strings of character
In all programs seen until now, we have used only numerical variables, used
to express numbers exclusively. But in addition to numerical variables there
also exist strings of characters, that allow us to represent successions of
characters, like words, sentences, names, texts, et cetera. Until now we
have only used them as constants, but we have never considered variables
able to contain them. In C++ there is no specific elemental variable type to
store strings of characters. In order to fulfill this feature we can use arrays
of type char, which are successions of char elements. Remember that this
data type (char) is the one used to store a single character, for that reason
arrays of them are generally used to make strings of single characters.
For example, the following array (or string of characters):
char jenny [20];
Can store a string up to 20 characters long
6
For example, jenny could store at some moment in a program either the
string of characters "Hello" or the string . Therefore, since the array of
characters can store shorter strings than its total length, a convention has
been reached to end the valid content of a string with a null character,
whose constant can be written 0 or '\0'.
We could represent jenny (an array of 8 elements of type char) storing the
strings of characters "Hello" and "yes”
H e l l O \0 Y e s \0
Assigning values to strings
Since the lvalue of an assignation can only be an element of an array and
not the entire array, it would be valid to assign a string of characters to an
array of char using a method like this:
mystring[0] = 'H';
mystring[1] = 'e';
mystring[2] = 'L';
mystring[3] = 'L';
mystring[4] = 'o';
mystring[5] = '\0';
Pointer
Pointer: We have already seen how variables are memory cells that we can
access by an identifier. But these variables are stored in concrete places of
the computer memory. For our programs, the computer memory is only a
succession of 1 byte cells (the minimum size for a datum), each one with a
unique address.
A good simile for the computer memory can be a street in a city. On a street
all houses are consecutively numbered with an unique identifier so if we
talk about 27th of Sesame Street we will be able to find that place without
trouble, since there must be only one house with that number and, in
addition, we know that the house will be between houses 26 and 28.
7
In the same way in which houses in a street are numbered, the operating
system organizes the memory with unique and consecutive numbers, so if
we talk about location 1776 in the memory, we know that there is only one
location with that address and also that is between addresses 1775 and
1777.
Address (dereference) operator (&).
At the moment in which we declare a variable it must be stored in a
concrete location in this succession of cells (the memory). We generally do
not decide where the variable is to be placed - fortunately that is something
automatically done by the compiler and the operating system at runtime,
but once the operating system has assigned an address there are some
cases in which we may be interested in knowing where the variable is
stored.
This can be done by preceding the variable identifier by an ampersand sign
(&), which literally means "address of". For example:
ted = &andy;
would assign to variable ted the address of variable andy, since when
preceding the name of the variable andy with the ampersand (&) character
we are no longer talking about the content of the variable, but about its
address in memory.
We are going to suppose that andy has been placed in the memory address
1776 and that we write the following:
andy = 25; fred = andy; ted = &andy;
Reference operator (*)
Using a pointer we can directly access the value stored in the variable
pointed by it just by preceding the pointer identifier with the reference
operator asterisk (*), that can be literally translated to "value pointed by".
Operator of Address & :It is used as a variable prefix and can be
translated as "address of", thus: &variable1 can be read as "address of
variable1"
Operator of reference (*) : It indicates that what has to be evaluated is
the content pointed by the expression considered as an address. It can be
8
translated by "value pointed by". * my pointer can be read as "value pointed
by my pointer"
9
10