Introduction to C++ Lecture Set 2 Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 1
More Arithmetic Operators More Arithmetic Operators In the first session the basic arithmetic operators were introduced. In addition to these, C++ contains a number of other operators which are, in effect, shorthand for common combinations of the basic operators. Copy Assignment Operators Because statements such as: a = a + b; are very common there exists a shorthand. a += b; Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 2
More Arithmetic Operators Similar Copy Assignment Operators exist for subtraction, multiplication, division and modulus. -= *= /= %= For example, the code a = 2; a*= 2; will result in a containing the value 4. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 3
More Arithmetic Operators Pre- and Post- increment/decrement Operators c++; is shorthand for c=c+1; However, this operator comes in two flavours: ++c; c++; Called the pre-increment and post-increment operators respectively. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 4
More Arithmetic Operators Consider the code fragment: c = 1; a = ++c; This illustrates the pre-increment operator which means "Add 1 to c and assign result to a". This will result in both a and c containing the value 2. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 5
More Arithmetic Operators This should be compared with: c = 1; a = c++; Which illustrates the post-increment operator which means "Assign c to a then add 1 to c". In this case c will contain the value 2 but a the value 1. There are also corresponding pre- and post-decrement operators -- Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 6
More about iostreams More about iostreams Previously we introduced the output stream cout which which we have used to print simple text and expressions to the console. e.g. int i=10;... cout << "i = " << i << endl; The iostreams package defined in <iostream> provides the functionality for simple input of data as well as output. In fact 3 streams are defined: cin cout cerr standard input stream standard output stream standard error (output) stream Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 7
More about iostreams For all of the built-in types (int, double, char etc.) operators << and >> are defined to allow output and input to these standard streams. e.g. in the program readint.cpp the lines: int i; cout << "Enter an integer" << endl; cin >> i; cout << "i= " << i << endl; write the character string "Enter an integer" to the standard output stream then reads the value of i from the standard input. Finally the string "i= ", followed by the value of i is written to the standard output. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 8
More about iostreams Formatted Output These streams may be manipulated to allow fine control over the format of output. In general this is complicated and a full description is beyond the scope of this course. ( Those who are brave can read Stroustrup chapter 21 ). Here we discuss a few of the most useful features. The output format used for floating point numbers is changed through the special state manipulation functions: cout.setf( ios::scientific, ios::floatfield ); cout.setf( ios::fixed, ios::floatfield ); sets the format to scientific form e.g. 1.234e+03 sets the format to fixed point format cout.setf( std::_ios_fmtflags(0), ios::floatfield ); resets the format to the default (general) format Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 9
More about iostreams The precision used when formatting floating point numbers (only) is controlled by the precision() (member) function. e.g. cout.precision(8); Sets the precision to 8 figures (or for the scientific or fixed formats 8 decimal places). The default precision is 6. This remains continuously in force until the precision() function is called again. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 10
More about iostreams The width() function specifies the minimum number of characters to be used for the NEXT output operation ONLY. This is demonstrated by the example iwidth.cpp int i=12; cout<<i<<endl; cout.width(4); cout<<i<<endl; cout.width(8); cout<<i<<endl; will print something like: 12 12 12 In the second output statement 12 is preceded by 2 spaces in a field of 4 characters giving the output. In the third output statement 12 is preceded by 6 spaces in a field of 8 characters giving the output. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 11
The If Statement In order to write any but the most trivial program there needs be some mechanism to allow the conditional execution of a block of code. In C++ this facility is provided by the if statement. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 12
The If Statement In its simplest form we require the conditional execution of only one statement: if( logical_expression ) a_single_statement ; e.g. if ( x > 5 ) cout << " x is greater than 5 " << endl; If (and only if) the logical_expression is evaluated to be logically TRUE then the following statement is evaluated. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 13
If statement In the more general case, where there are several statements to conditionally execute, we surround the block of code with curlies {} if( logical_expression ) {......... } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 14
Introduction to C++ The Relational Operators In order to form a logical_expression there is a special set of operators which allow the comparison of two variables (or expressions): There are 6 operators: == is equal to!= is NOT equal to > is greater than >= is greater or equal to < is less than <= is less than or equal to DO NOT confuse the equality operator, ==, with the assignment operator, =. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 15
If statement An expression formed using a relational operator always evaluates to be logical TRUE or FALSE. Some examples of the use of relational operators in the if statement: if ( i == 10 ) cout << " i is 10! " << endl ; if ( (x*x + y*y) > 5 ) { cout << " x-squared + y-squared is greater than 5 " << endl; } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 16
Logical operators The Logical Operators It is often useful to combine several conditions in a single logical expression. To do this there are 3 logical operators : && Logical AND Logical OR! Logical NOT Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 17
logical operators These operators obey the rules of Boolean Algebra. If A and B are logical expressions then the results of these operators are according to this truth table A B A B A&&B!A T T T T F T F T F F F T T F T F F F F T Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 18
If statement The combination of logical operators and the relational operators allows one to build up complex logical expressions, e.g. if ( ( x > 5 ) && ( x < 10 ) ) { cout << " x is between 5 and 10 " << endl; } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 19
The Nature of truth in C++ The Nature of Truth in C++ In C++ an expression which evaluates to 0 is equivalent to logically FALSE whilst ANY other value is logically TRUE. Thus in the expression: if (1) cout << " This is silly " << endl; Will always execute the output statement. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 20
if...else Often one wants to choose between execution of two or more blocks of code, depending on the results of logical expressions. To make a simple choice between two options one can use a if... else construct Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 21
if...else The general block form looks like: if(logical_expression ) {... } else {... } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 22
if..else if More complex constructs can be built using nested if statements, or the logically equivalent if... else if construct: if(logical_expression ) {... } else if ( another_logical_expression ) {... } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 23
if..else if..else Here is an example, similar to inttest.cpp, showing how to choose between the three cases: i=0, i<0 and i>0 : if ( i == 0) { cout << " i is 0 " << endl; } else if ( i < 0 ) { cout << " i is less than 0 " << endl; } else { cout << " i is greater than 0 " << endl; } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 24
while loops Loops: The while Statement A very common programming task involves the evaluation of an expression several times with different variable values. Rather than tediously typing in many lines of repetitive code it is convenient to introduce the idea of a loop construct. The while( ) Statement is the simplest way of allowing repetition of some code...a loop in the program. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 25
while loops Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 26
while loops It takes the general block form: while ( logical_expression ){... } Examples of some logical_expressions are: I < 10 i less than 10 J > 20 j greater than 20 k == j k equal to j Don't confuse the equality operator with assignment. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 27
while loops While the logical_expression is True then the series of statements within the curlies are evaluated until the logical_expression is False The following code fragment calculates adds up the numbers between 1 and 10 int sum = 0; int k = 0; while ( k < 10 ) { k = k + 1; sum = sum + k; } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 28
do...while loops do...while blocks The do...while statement is a variation of the while statement in which a block of statements is evaluated at least once before a logical test is made: Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 29
do...while loops The example above may be rewritten using do...while: int sum = 0, k = 0; do { k = k + 1; sum = sum + k; } while( k < 10 ); A complete version of this program is available Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 30
For loops More General Loops: The for Statement C++ has a very general and flexible way of forming loops using the for statement. It may be thought of a generalized while loop. Usually S1 and S3 are used to initialize and update a counter variable. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 31
For loops The following code fragment demonstrates its use: (S1) (E1) (S3) for ( int i = 0; i < 20; i++) { }... This code defines a loop, the loop variable i, which takes in turn the values 0,1,2,...19, for each value of i the block of code enclosed by the curlies is evaluated. The block of code is therefore executed 20 times A general for construct always has 3 statements. These are Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 32
For loops N.B. A variable such as i, is said to be declared within the scope of the for loop ONLY. You can not access it from OUTSIDE the loop (though you can declare another variable with the same name). This is also true if you declare a variable within the for loop's curlies. The following sumsqs2.cpp calculates the sum-of-squares between 1 and 10: int sum=0; for(int i=1; i<=10; i++){ sum+=i*i; cout << " Sum of squares, i= " << i << " Sum = " << sum <<endl; } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 33
For loops You should generally use an integer variable as the for loop counter to ensure the loop is evaluated the correct number of times. For example, because of possible rounding errors its difficult to be certain, how many times the following loop is evaluated: double delta=1.0/3.0; for(double x=2; x<=5; x+=delta ){... } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 34
For loops To avoid such problems you should use an integer loop counter and derive the floating value from it. So the above bad example could be rewritten as so: or double delta=1.0/3.0; for(int i=0; i<=15; i++ ){ double x = 2.0 + i*delta;... } double delta=1.0/3.0; double x=2.0; for(int i=0; i<=15; i++ ){... x+=delta; } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 35
Introduction to C++ Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 36