Download C++ Programming: Variables, Data Types, and Basic Control Structures (Lecture 2) and more Slides Computational and Statistical Data Analysis in PDF only on Docsity!
Computing and Statistical Data Analysis
Lecture 2
Variables, types: int, float, double, bool , ...
Assignments, expressions
Simple i/o; cin and cout.
Basic control structures: if, else
Loops: while, do-while, for, ...
C++ building blocks
All of the words in a C++ program are either:
Reserved words: cannot be changed, e.g.,
if, else, int, double, for, while, class, ...
Library identifiers: default meanings usually not
changed, e.g., cout, sqrt (square root), ...
Programmer-supplied identifiers:
e.g. variables created by the programmer,
x, y, probeTemperature, photonEnergy, ...
Valid identifier must begin with a letter or underscore (“ _ ”) , and
can consist of letters, digits, and underscores.
Try to use meaningful variable names; suggest lowerCamelCase.
Declaring variables
All variables must be declared before use.
Usually declare just before 1st use.
Examples
int main(){ int numPhotons; // Use int to count things double photonEnergy; // Use double for reals bool goodEvent; // Use bool for true or false int minNum, maxNum; // More than one on line int n = 17; // Can initialize value double x = 37.2; // when variable declared. char yesOrNo = ‘y’; // Value of char in ‘ ‘ ... }
Assignment of values to variables
Declaring a variable establishes its name; value is undefined
(unless done together with declaration).
Value is assigned using = (the assignment operator):!
int main(){ bool aOK = true; // true, false predefined constants double x, y, z; x = 3.7; y = 5.2; z = x + y; cout << "z = " << z << endl; z = z + 2.8; // N.B. not like usual equation cout << "now z = " << z << endl; ... }
Enumerations
Sometimes we want to assign numerical values to words, e.g.,
January = 1, February = 2, etc.
Use an ‘enumeration’ with keyword enum
enum { RED, GREEN, BLUE };
is shorthand for
! const int RED = 0; const int GREEN = 1; const int BLUE = 2;
Enumeration starts by default with zero; can override:
enum { RED = 1, GREEN = 3, BLUE = 7 }
(If not assigned explicitly, value is one greater than previous.)
Expressions
C++ has obvious(?) notation for mathematical expressions:
operation symbol
addition +
subtraction -
multiplication *
division /
modulus %
Note division of int values is truncated:
int n, m; n = 5; m = 3; int ratio = n/m; // ratio has value of 1
Modulus gives remainder of integer division:
int nModM = n%m; // nModM has value 2
Boolean expressions and operators
Boolean expressions are either true or false, e.g.,
int n, m; n = 5; m = 3; bool b = n < m; // value of b is false
C++ notation for boolean expressions:
greater than > greater than or equals >= less than < less than or equals <= equals == not equals !=
Can be combined with && (“and”), || (“or”) and! (“not”), e.g.,
(n < m) && (n != 0) (false) (n%m >= 5) || !(n == m) (true)
not =
Precedence of operations not obvious; if in doubt use parentheses.!
Shorthand assignment statements
full statement shorthand equivalent
n = n + m n += m n = n - m n -= m n = n * m n *= m n = n / m n /= m n = n % m n %= m
full statement shorthand equivalent
n = n + 1 n++ ( or ++n )!
n = n - 1 n-- ( or --n )
Special case of increment or decrement by one:
++ or -- before variable means first increment (or decrement),
then carry out other operations in the statement (more later).
if and else
Simple flow control is done with if and else:!
! if ( boolean test expression ){ Statements executed if test expression true }
or
! if ( expression1 ){ Statements executed if expression1 true } else if ( expression2 ) { Statements executed if expression1 false and expression2 true } else { Statements executed if both expression1 and expression2 false }
more on if and else
Note indentation and placement of curly braces:!
! if ( x > y ){ x = 0.5*x; }
Some people prefer
! if ( x > y ) { x = 0.5*x; }
If only a single statement is to be executed, you can omit the
curly braces -- this is usually a bad idea:
if ( x > y ) x = 0.5*x;
“while” loops
A while loop allows a set of statements to be repeated as long as
a particular condition is true:
while( boolean expression ){ // statements to be executed as long as // boolean expression is true } while (x < xMax){ x += y; ... }
For this to be useful, the boolean expression must be updated
upon each pass through the loop:
Possible that statements never executed, or that loop is infinite.
“do-while” loops
A do-while loop is similar to a while loop, but always executes
at least once, then continues as long as the specified condition is
true.
do { // statements to be executed first time // through loop and then as long as // boolean expression is true } while ( boolean expression )
Can be useful if first pass needed to initialize the boolean
expression.
Examples of loops
int sum = 0; for (int i = 1; i<=n; i++){ sum += i; } cout << "sum of integers from 1 to " << n << " is " << sum << endl;
A do-while loop:
int n; bool gotValidInput = false; do { cout << "Enter a positive integer" << endl; cin >> n; gotValidInput = n > 0; } while ( !gotValidInput );
A for loop:
Nested loops
// loop over pixels in an image for (int row=1; row<=nRows; row++){ for (int column=1; column<=nColumns; column++){ int b = imageBrightness(row, column); ... } // loop over columns ends here } // loop over rows ends here
Loops (as well as if-else structures, etc.) can be nested, i.e.,
you can put one inside another:
We can put any kind of loop into any other kind, e.g., while
loops inside for loops, vice versa, etc.