Control Structures: 6/7/2012 Mwangi H. 1
Control Structures: 6/7/2012 Mwangi H. 1
Choosing between different courses of action makes a program much more useful and flexible. Decision making constructs allow for many different logical branches of code to be incorporated into a single program. One of the fundamental properties of a programming language is the ability to repetitively execute a sequence of statements. These looping capabilities enable programmers to develop concise programs containing repetitive processes that could otherwise require an excessive number of statements.
6/7/2012
Mwangi H.
6/7/2012
Mwangi H.
Branching
The if Statement The basic if statement allows program to execute a single statement, or a block of statements enclosed within curly braces, if a given condition returns the value true.
6/7/2012
Mwangi H.
Nested If
The statement that is to be executed when the condition in an if statement is true can also be an if. This arrangement is called a nested if. The condition for the inner if is only tested if the condition for the outer if is true.
6/7/2012
Mwangi H.
if(letter >= 'A') // Test for 'A' or larger if(letter <= 'Z') // Test for 'Z' or smaller { cout << endl << "You entered a capital letter." << endl; return 0; } if(letter >= 'a') // Test for 'a' or larger if(letter <= 'z') // Test for 'z' or smaller { cout << endl << "You entered a small letter." << endl; return 0; }
6/7/2012
Mwangi H.
IF..Else Statement
This version of the if, allows one statement to be executed if the condition returns true, and a different statement to be executed if the condition returns false. Execution then continues with the next statement in sequence. Remember that a block of statements can always replace a single statement, so this also applies to these ifs.
6/7/2012 Mwangi H. 7
if(number%2L) // Test remainder after division by 2 cout << endl // Here if remainder 1 << "Your number is odd." << endl; else cout << endl // Here if remainder 0 << "Your number is even." << endl;
6/7/2012 Mwangi H. 8
Example 2
if(coffee == 'y') if(donuts == 'y') cout << "We have coffee and donuts."; else cout << "We have coffee, but not donuts"; else if(tea == 'y') cout << "We have no coffee, but we have tea, and maybe donuts..."; else cout << "No tea or coffee, but maybe donuts...";
6/7/2012 Mwangi H. 10
Review of operators
three logical operators: && logical AND || logical OR ! logical negation (NOT)
6/7/2012
Mwangi H.
11
Unconditional Branching
The if statement provides you with the flexibility to choose to execute one set of statements or another, depending on a specified condition, so the statement execution sequence is varied depending on the values of the data in the program. The goto statement, in contrast, is a blunt instrument. It enables you to branch to a specified program statement unconditionally. The statement to be branched to must be identified by a statement label, which is an identifier defined according to the same rules as a variable name. This is followed by a colon and placed before the statement requiring labeling. Here is an example of a labeled statement:
6/7/2012 Mwangi H. 14
Example
int main() { int i = 0, sum = 0; const int max = 10; i = 1; loop: sum += i; if(++i <= max) goto loop;
cout << endl << "sum = " << sum << endl << "i = " << i << endl; return 0; }
6/7/2012
Mwangi H.
15
Example
#include <iostream> #include <iomanip> using namespace std; int main() { long i = 0, power = 0; const int max = 10; for(i = 0, power = 1; i <= max; i++, power += power) // Loop statement cout << endl << setw(10) << i << setw(10) << power;
6/7/2012
Mwangi H.
18
int main() { double value = 0.0; // Value entered stored here double sum = 0.0; // Total of values accumulated here int i = 0; // Count of number of values char indicator = 'n'; // Continue or not? for(;;) // Infinite loop { cout << endl << "Enter a value: "; cin >> value; // Read a value ++i; // Increment count sum += value; // Add current input to total cout << endl << "Do you want to enter another value (enter n to end)? "; cin >> indicator; // Read indicator if ((indicator == 'n') || (indicator == 'N')) break; // Exit from loop } cout << endl << "The average of the " << i << " values you entered is " << sum/i << "." << endl; return 0; }
6/7/2012
Mwangi H.
19
6/7/2012
Mwangi H.
20
Example
#include <iostream> using namespace std; int main() { int i = 0, value = 0, product = 1; for(i = 1; i <= 10; i++) { cin >> value; if(value == 0) // If value is zero continue; // skip to next iteration product *= value; }
cout << "Product (ignoring zeros): " << product << endl; return 0;
}
6/7/2012 Mwangi H. 21
while(condition) loop_statement;
6/7/2012 Mwangi H. 22
Individual items in an array are specified by an index value which is simply an integer representing the sequence number of the elements in the array, the first having the sequence number 0, the second 1, and so on upto n-1 where n is the size of the array You can also envisage the index value of an array element as an offset from the first element in an array.
6/7/2012 Mwangi H. 25
Declaring Arrays
Array is declared essentially the same way as other variables with the only difference being that the number of elements in the array is specified between square brackets immediately following the array name. The Syntax is:
Datatype arrayname[size]
long Height[6];
6/7/2012 Mwangi H. 26
Populating an array
An array may be populated explicitly where each array element is initialized to a particular value. This method is quite cumbersome when the array size is big By use of a loop. In this case data is read from an external source, could be a user or a file Using array initializer where array elements are enclosed with curly braces
6/7/2012 Mwangi H. 27
Each character in the string occupies one byte, so together with the null character, a string requires a number of bytes that is one greater than the number of characters contained in the string. char movie_star[12] = "Paul Newman";
6/7/2012
Mwangi H.
29
String Input
The header file iostream contains definitions of a number of functions for reading characters from the keyboard. Eg: getline(), reads a string into a character array. This is typically used with statements such as this:
const int MAX = 80; char name[MAX]; ... cin.getline(name, MAX, '\n');
6/7/2012
Mwangi H.
30
Multidimensional Arrays
The arrays that we have defined so far with one index are referred to as one-dimensional arrays. An array can also have more than one index value, in which case it is called a multidimensional array. Suppose we have a field in which we are growing bean plants in rows of 10, and the field contains 12 such rows (so there are 120 plants in all). We could declare an array to record the weight of beans produced by each plant using the following statement: double beans[12][10];
6/7/2012 Mwangi H. 31
6/7/2012
Mwangi H.
33
What is a Pointer?
Each memory location that you use to store a data value has an address. The address provides the means for PC hardware to reference a particular data item. A pointer is a variable that stores an address of another variable of a particular type. A pointer has a variable name just like any other variable and also has a type which designates what kind of variables its contents refer to. Note that the type of a pointer variable includes the fact that it's a pointer. A variable that is a pointer which can contain addresses of locations in memory containing values of type int, is of type 'pointer to int'.
6/7/2012 Mwangi H. 35
Declaring Pointers
The declaration for a pointer is similar to that of an ordinary variable, except that the pointer name has an asterisk in front of it to indicate that it's a variable which is a pointer. For example, to declare a pointer pnumber that points to a variable of type long, you could use the following statement: long* pnumber;
6/7/2012 Mwangi H. 36
pnumber = &number;
6/7/2012
Mwangi H.
37
Using Pointers
The Indirection Operator The indirection operator, *, is used with a pointer to access the contents of the variable to which it points. The name 'indirection operator' stems from the fact that the data is accessed indirectly. It is also called the de-reference operator, and the process of accessing the data in the variable pointed to by a pointer is termed de-referencing the pointer.
6/7/2012 Mwangi H. 38