COMP 103 L4 Intro ExprOp
COMP 103 L4 Intro ExprOp
Programming
DANIEL OBUOBI, DCSIT,CU
C++ EXPRESSIONS & STATEMENTS
Quote
• “Real Programmers always get Halloween
and Christmas mixed up:
Oct31 == Dec25 ”
Expressions and Statements
• A program is a set of commands executed in
sequence.
• The power in a program comes from its
capability to execute one or another set of
commands, based on whether a particular
condition is true or false.
Statements
• In C++ a statement controls the sequence of execution,
evaluates an expression, or does nothing (the null
statement).
• All C++ statements end with a semicolon, even the null
statement, which is just the semicolon and nothing else.
• One of the most common statements is the following
assignment statement:
x = a + b;
• Unlike in algebra, this statement does not mean that x
equals a+b.
• This is read, "Assign the value of the sum of a and b to x,"
or "Assign to x, a+b."
Blocks and Compound Statements
• Any place you can put a single statement, you can put a
compound statement, also called a block. A block begins with an
opening brace ({) and ends with a closing brace (}). Although
every statement in the block must end with a semicolon, the
block itself does not end with a semicolon. For example
{
temp = a;
a = b;
b = temp;
}
• DO use a closing brace any time you have an opening brace.
• DO end your statements with a semicolon.
Expressions
• Anything that evaluates to a value is an expression
in C++.
• An expression is said to return a value.
– Thus, 3+2; returns the value 5 and so is an expression.
• All expressions are statements.
• Here are three examples:
3.2 // returns the value 3.2
PI // float const that returns the value
3.14
SecondsPerMinute // int const that returns 60
The complicated expression
• x = a + b;
– not only adds a and b and assigns the result to x, but
returns the value of that assignment (the value of x) as well.
• Thus, this statement is also an expression.
• Because it is an expression, it can be on the right side
of an assignment operator:
• y = x = a + b;
• This line is evaluated in the following order:
– Add a to b.
– Assign the result of the expression a + b to x.
– Assign the result of the assignment expression x = a + b to y.
Operators
• An operator is a symbol that causes the
compiler to take an action. Operators act on
operands, and in C++ all operands are
expressions. In C++ there are several different
categories of operators. Two of these
categories are
• Assignment operators.
• Mathematical operators.
Assignment Operator
• The assignment operator (=) causes the operand
on the left side of the assignment operator to have
its value changed to the value on the right side of
the assignment operator.
• The expression x = a + b;
– assigns the value that is the result of adding a and b to
the operand x.
• An operand that legally can be on the left side of
an assignment operator is called an lvalue.
• That which can be on the right side is called an
rvalue.
Example lvalue and rvalue
• Constants are r-values. They cannot be l-values. Thus,
you can write
x = 35; // ok
but you can't legally write
35 = x; // error, not an lvalue!
• An lvalue is an operand that can be on the left side of an
expression.
• An rvalue is an operand that can be on the right side of
an expression.
• All l-values are r-values, but not all r-values are l-values.
– An example of an rvalue that is not an lvalue is a literal.
– Thus, you can write x = 5;, but you cannot write 5 = x;.
Mathematical Operators
• There are five mathematical operators:
addition (+), subtraction (-), multiplication (*),
division (/), and modulus (%).
• Addition and subtraction work as you would
expect.
• Subtraction with unsigned integers can lead to
surprising results, if the result is a negative
number (variable overflow).
Demo – try it
1: // demonstrates subtraction and
2: // integer overflow
3: #include <iostream.h>
4:
5: int main()
6: {
7: unsigned int difference;
8: unsigned int bigNumber = 100;
9: unsigned int smallNumber = 50;
10: difference = bigNumber - smallNumber;
11: cout << "Difference is: " << difference;
12: difference = smallNumber - bigNumber;
13: cout << "\nNow difference is: " << difference <<endl;
14: return 0;
15: }
Output: Difference is: 50
Now difference is: 4294967246
Simple arithmetic
• Addition : ‘ + ’ : var3 = var1 + var2;
• Subtraction : ‘ - ’ : var3 = var1 - var2;
• Multiplication : ‘ * ’ : var3 = var1 * var2;
• Division : ‘ / ’ : var3 = var1 / var2;
– if ‘var3’ is an integer then result is truncated
• Modulus : ‘ % ’ : var3 = var1 % var2;
– returns the remainder of the division
– 20 % 3 == 2 10 % 2 == 0
Integer Division and Modulus
• Integer division is somewhat different from
everyday division.
• When you divide 21 by 4, the result is a real number
(a number with a fraction).
– Integers don't have fractions, and so the "remainder" is
lopped off.
– The answer is therefore 5.
• To get the remainder, you take 21 modulus 4 (21 %
4) and the result is 1.
• The modulus operator tells you the remainder after
an integer division.
Combining the Assignment and
Mathematical Operators
• In C++, you can put the same variable on both sides of the
assignment operator, and thus the preceding becomes
myAge = myAge + 2;
• Even simpler to write, but perhaps a bit harder to read is
myAge += 2;
• This operator is pronounced "plus-equals."
• The statement would be read "myAge plus-equals two."
– If myAge had the value 4 to start, it would have 6 after this
statement.
• There are self-assigned subtraction (-=), division (/=),
multiplication (*=), and modulus (%=) operators as well.
Increment and Decrement
• The most common value to add (or subtract) and then
reassign into a variable is 1.
• In C++, increasing a value by 1 is called incrementing,
and decreasing by 1 is called decrementing.
• There are special operators to perform these actions.
• The increment operator (++) increases the value of
the variable by 1, and the decrement operator (--)
decreases it by 1.
• Thus, C++; // Start with C and increment it.
• This is equivalent to C = C + 1; or C +=1;
Prefix and Postfix
• Both the increment operator (++) and the decrement
operator(--) come in two varieties: prefix and postfix.
• The prefix variety is written before the variable name (+
+myAge); the postfix variety is written after (myAge++).
• In a simple statement, it doesn't much matter which
you use, but in a complex statement, when you are
incrementing (or decrementing) a variable and then
assigning the result to another variable, it matters very
much.
• The prefix operator is evaluated before the assignment,
the postfix is evaluated after.
Semantic of prefix and postfix
• The semantics of prefix is this:
– Increment the value and then fetch it.
• The semantics of postfix is different:
– Fetch the value and then increment the original.
• Example: int a = ++x;
– If x=5, the compiler will increment x (making it 6) and
then fetch that value and assign it to a. Thus, a = 6 and x
= 6.
• if int b = x++;
– the compiler will fetch the value in x (6) and assign it to
b, and then increment x. Thus, b = 6, but x = 7
Precedence
• In the complex statement x = 5 + 3 * 8;
which is performed first, the addition or the
multiplication?
• If the addition is performed first, the answer is 8 * 8,
or 64. If the multiplication is performed first, the
answer is 5 + 24, or 29.
• Every operator has a precedence value, " Multiplication
has higher precedence than addition, and thus the
value of the expression is 29.
• Some operators, such as assignment, are evaluated in
right-to-left order!
The Nature of Truth
• In C++, zero is considered false, and all other
values are considered true, although true is
usually represented by 1.
• Thus, if an expression is false, it is equal to
zero, and if an expression is equal to zero, it is
false.
• If a statement is true, all you know is that it is
nonzero, and any nonzero statement is true.
Relational Operators
• The relational operators are used to determine whether two
numbers are equal, or if one is greater or less than the other.
• Every relational statement evaluates to either 1 (TRUE) or 0
(FALSE).
• For myAge=30 and yourAge=40 , the expression
– myAge == yourAge; // is the value in myAge the same as in
yourAge?
– This expression evaluates to 0, or false, because the variables are
not equal.
• The expression
myAge > yourAge; // is myAge greater than
yourAge?
– evaluates to 0 or false.
Logical Operators
• The Logical Operators.
Operator Symbol Example
AND && expr1 && expr2
OR || expr1 || expr2
NOT ! !expression
• A logical AND statement evaluates two expressions,
and if both expressions are true, the logical AND
statement is true as well.
• A logical OR statement evaluates two expressions. If
either one is true, the expression is true.
• A logical NOT statement evaluates true if the
expression being tested is false.
Conditionals
• Currently all code is executed when the program is run
• Conditionals allow us to specify the conditions under
which an instruction should be executed
• if (condition)
statement;
• If multiple statements need to be executed then:
• if (condition)
{
multiple statements;
}
Conditions
• Equal ==
• Not Equal !=
• Greater Than >
• Less Than <
• Greater Than or Equal >=
• Less Than or Equal <=
• if (var1==var2)
{
cout << “The variables are equal\n”;
}
Conditionals program
#include <iostream.h>
int main()
{
short int UserNum;
cout << “Please enter a positive number\n”;
cin >> UserNum;
if (UserNum < 0 )
cout << “That number wasn’t positive!\n”;
return 0;
}
Else Statement
• if (condition) then run statement
• else run alternative statement
• if (condition)
{
statements
}
else
{
alternative statements
}
Conditionals program 2
#include <iostream.h>
int main()
{
short int UserNum;
cout << “Please enter a positive number\n”;
cin >> UserNum;
if (UserNum < 0 )
cout << “That number wasn’t positive!\n”;
else
cout << “Thankyou\n”;
return 0;
}
While Loops
• Allows an action to repeated ad infinitum
• while (condition) {
statements
}
• while (numvar > 0) {
cout << numvar << endl;
numvar = numvar – 1;
}
• Ensure condition changes, so infinite loop is
avoided
EXAMPLE
#include <iostream.h>
int main()
{
short int UserNum;
cout << “Please enter a number\n”;
cin >> UserNum;
while (UserNum > 0 ) {
cout << UserNum << endl;
UserNum = UserNum – 1;
}
return 0;
}
For Loops
• Simple way of repeating an action multiple times
• Useful when we know how many times to iterate
– ‘10’ , ‘numvar’
• Create a counter variable
• for (initial counter; end counter; change counter)
{
statements
}
EXAMPLE
#include <iostream.h>
int main()
{
short int UserNum;
cout << “Please enter a number\n”;
cin >> UserNum;
for (UserNum; UserNum > 0; UserNum = UserNum-1 ) {
cout << UserNum << endl;
}
return 0;
}
Better use for while loops
• Better use is for loops with indeterminate
termination point
• short int UserNum = -1;
while (UserNum < 0) {
cout << “Please enter a positive number\n”;
cin >> UserNum;
}
Complex conditionals
• if (condition 1) {
}
else
if (condition 2) {
}
else if (condition 3) {
}
else {
}
Switch Statements
• Easier to understand than complex conditionals
• Only useful for certain scenarios
• Depending on value of variable, different set of code executed
• switch (variable) {
case value1: statement1;
statement2;
break;
case value2: statement1;
break;
default: statement1;
break;
}
EXAMPLE
#include <iostream.h>
int main()
{
short int UserNum;
cout << “Please enter either 1,2 or 3\n”;
cin >> UserNum;
switch (UserNum) {
case 1: cout << “You win\n”;
break;
case 2: cout << “You lose\n”;
break;
case 3: cout << “Sorry!\n”;
break;
default: cout << “You can’t count\n”;
break;
}
return 0;
}
CHECKLIST
• HOW MANY PROGRAMS HAVE YOU WRITTEN
TO DATE?
• HOW MANY PROGRAMS HAVE YOU COMPILED
TO DATE?
• HOW MANY PROGRAMS HAVE YOU DEBUG TO
DATE?
• HOW MANY PROGRAMS HAVE YOU GOT
WORKING CORRECTLY TO DATE?
• GET HELP BUT DO IT YOURSELF MORE