0% found this document useful (0 votes)
58 views

Control Structures: 6/7/2012 Mwangi H. 1

This document discusses control structures in programming, including branching/selection statements like if/else and switch, as well as looping statements like for, while, and do-while loops. It provides syntax examples and explanations of how these control structures work, what they are used for, and how they allow for decision making and repetitive execution in programs. Examples are given for each type of control structure to illustrate their usage.

Uploaded by

Chemutai Joyce
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Control Structures: 6/7/2012 Mwangi H. 1

This document discusses control structures in programming, including branching/selection statements like if/else and switch, as well as looping statements like for, while, and do-while loops. It provides syntax examples and explanations of how these control structures work, what they are used for, and how they allow for decision making and repetitive execution in programs. Examples are given for each type of control structure to illustrate their usage.

Uploaded by

Chemutai Joyce
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 39

Control Structures

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.

Control Structure contd


In summary control structures are categorized into:
Sequential-Program statements are executed in the order they appear in the program Branching/selection Iteration/looping

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.

The syntax of the Simple if is IF CONDITION {


STATEMENT BLOCK } The condition to be tested appears in parentheses immediately following the keyword, if.
6/7/2012 Mwangi H. 4

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

Nested if-else Statements


If-else statements can be nested within ifs, ifs within if-else statements, and if-else statements within if-else statements. if(coffee == 'y') if(donuts == 'y') cout << "We have coffee and donuts."; else cout << "We have coffee, but not donuts";
6/7/2012 Mwangi H. 9

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

The Conditional Operator


The conditional operator is sometimes called the ternary operator because it involves three operands. c = a>b ? a : b;
if(a>b) c = a; else c = b;
6/7/2012 Mwangi H. 12

Selection- The switch


The switch statement enables you to select from multiple choices based on a set of fixed values for a given expression. In the switch statement, the selection is determined by the value of an expression that you specify. You define the possible switch positions by one or more case values, a particular one being selected if the value of the switch expression is the same as the particular case value. There is one case value for each possible choice in the switch - the case values must be distinct
6/7/2012 Mwangi H. 13

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;

// Add current value of i to sum

// Go back to loop until i = 11

cout << endl << "sum = " << sum << endl << "i = " << i << endl; return 0; }

6/7/2012

Mwangi H.

15

Repeating a Block of Statements


The ability to repeat a group of statements is fundamental to most applications. A loop executes a sequence of statements until a particular condition is true (or false). Loops are implemented in programming using:
For Loop Dowhile loop While loop
6/7/2012 Mwangi H. 16

The For Loop


The general form of the for loop is: for (initializing_expression; test_expression; increment_expression) loop_statement; Of course, loop_statement can be a block between braces.
6/7/2012 Mwangi H. 17

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;

cout << endl; return 0;


}

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

The continue Statement


There is another statement, besides break, that is used to affect the operation of a loop: the continue statement. This is written simply as: continue;

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

The while Loop


Where the for loop is primarily used to repeat a statement or a block for a prescribed number of iterations, the while loop will continue as long as a specified condition is true. The general form of the while loop is:

while(condition) loop_statement;
6/7/2012 Mwangi H. 22

The do-while Loop


The do-while loop is similar to the while loop in that the loop continues as long as the specified loop condition remains true. The main difference is that the condition is checked at the end of the loop-in the case of the while loop and the for loop, the condition is checked at the beginning of the loop. Thus, the do-while loop statement is always executed at least once. The general form of the do-while loop is: do { loop_statements; }while(condition);
6/7/2012 Mwangi H. 23

Arrays, Pointers and References


An array is block of memory locations, each of which can store an item of data of the same data type, and which are all referenced through the same variable name. The employee names in a payroll program could be stored in one array, the pay for each employee in another, and the tax due for each employee could be stored in a third array.
6/7/2012 Mwangi H. 24

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

Character Arrays and String Handling


An array of type char is called a character array and is generally used to store a character string. A character string is a sequence of characters with a special character appended to indicate the end of the string. The string terminating character is defined by the escape sequence '\0', and is sometimes referred to as a null character, being a byte with all bits as zero.
6/7/2012 Mwangi H. 28

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

Initializing Multidimensional Arrays


To initialize a multidimensional array, you use an extension of the method used for a one-dimensional array. For example, you can initialize a two-dimensional array, data, with the following declaration:
long data[2][4] = { { 1, 2, 3, 5 }, { 7, 11, 13, 17 } };
6/7/2012 Mwangi H. 32

Storing multiple strings


char stars[6][80] = { "Robert Redford", "Hopalong Cassidy", "Lassie", "Slim Pickens", "Boris Karloff", "Oliver Hardy"

6/7/2012

Mwangi H.

33

Indirect data Access-Pointers


The variables that we have dealt with so far provide you with the ability to name a memory location in which you can store data of a particular type. The contents of a variable are either entered from an external source, such as the keyboard, or calculated from other values that are entered. There is another kind of variable in C++ which does not store data that you normally enter or calculate, but greatly extends the power and flexibility of your programs. This kind of variable is called a pointer.
6/7/2012 Mwangi H. 34

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

The Address-Of Operator


How can we obtain the address of a variable? The address-of operator, &. is a unary operator which obtains the address of a variable. It's also called the reference operator. To set up the pointer that we have just declared, we could write this assignment statement:

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

Why Use Pointers?


To operate on data stored in an array, which often executes faster than if you use array notation. Secondly, in functions to extensively enable access to large blocks of data, such as arrays within a function, that are defined outside. Thirdly and most importantly, to allocate space for variables dynamically, that is, during program execution.
6/7/2012 Mwangi H. 39

You might also like