lecture 2 variables
TRANSCRIPT
Intro to Programming with C++ / Programming Using C++
CSD 106 / ICT 120
Comments
• Used to document parts of the program• Intended for persons reading the source code of
the program:– Indicate the purpose of the program– Describe the use of variables– Explain complex sections of code
• Are ignored by the compiler
Single-Line Comments
Begin with // through to the end of line:float adjacent = 2.5;// adjacent in cm
float opposite = 3.5; // opposite in cm
float hypotenuse; // hypotenuse that will be calculated
Multi-Line Comments
• Begin with /*, end with */• Can span multiple lines:
/* this is a multi-line comment*/
• Can begin and end on the same line:int volume; /* calculated volume */
Data Type
• Fundamental Data Type– Fundamental data types are basic types implemented
directly by the language that represent the basic storage units supported natively by most systems.
– C++ supports three simple data types• integer• floating point • character
numeric
Data Type
• Integer– Is a whole number, either positive or negative– Does not include decimal points– Cannot be written with commas, dollar signs, or any
symbols other than a leading + or -.– An integer variable is declared with the keyword int
Data Type
Data Type Size Range
int 4bytes -2147483648 to 2147483647
unsigned int 4bytes 0 to 4294967295
signed int 4bytes -2147483648 to 2147483647
short int 2bytes -32768 to 32767
unsigned short int 2bytes 0 to +65,535
long int 4bytes -2,147,483,647 to 2,147,483,647
Unsigned long int 4 bytes 0 to 4,294,967,295
Integer
Data Type
• Floating-Point– Real or Floating-Point Numbers• Numbers that include decimal points• A floating point variable is declared with the keyword float
or double and long double. long double uses more memory space than double. Likewise double occupies more space than float.
Floating-Point Data Types
Data Type
• Character– character may hold any single symbol in the ASCII
character set. – It contains letters of the alphabet, digits, space,
punctuation mark, arithmetic symbol, or other special symbol.
– Character value is always expressed in single quotes ‘’– A character variable is declared with the keyword
char
The char Data Type
• Used to hold characters or very small integer values
• Usually 1 byte of memory• Numeric value of character from the character
set is stored in memory:
CODE:char letter;letter = 'C';
MEMORY:letter
67
The Wider character Data Type
• Usually more than 1 byte of memory• A wider character variable is declared with the
keyword wchar_t
The C++ string Class• Special data type supports working with strings• Include the string header file – #include <string>
• Define a string variable type called a string object using the keyword string – For example:
string address, occupation;• Can receive values with assignment operator:• Can be displayed via cout
cout << address << " " << occupation;
The string class
Variables
• Variable names correspond to locations in the computer’s memory.
• It must be defined before it can be used.• It include letters, numbers and underscores, but must begin
with a letter (a-z or A-Z) or underscore(_).• No spaces or other special characters are allowed within a C++
variable name.• Examples of valid names
Gender cumGPA Total_Cost _emailAddress
Variable Names
• A variable name should represent the purpose of the variable. For example:
costOfItem
The purpose of this variable is to hold the cost of item.
Variables
• Variable– Note: C++ is case-sensitive as such a variable name
such as tax, Tax and TAX are different variable names– Good programming practice: use all lowercase letters
for variable names or else capitalize only the first letter of each new word after the first word, eg firstSemesterGPA (camel case)
– C++ keywords cannot be used as a variable name.
Variables
• Variable– Variable declaration is a C++ statement, all C++
statements must end with a semi-colon (;)– Explicitly stating the value of a variable is called
assignment. • It is achieved with the assignment operator =
– Assigning a value to a variable upon creation is often referred to as initializing the variable.
Variables
• Variable– Declaring, initializing, and assigning values to
variablesfloat tax_rate;float amount = 525.45;float tax_Amount;
tax_rate = 0.15;
tax_Amount = tax_rate * amount ;
Variables
• Variable– The const Qualifier• A variable that does not change in a program should be
declared as a constant• The keyword used to declare a variable constant is const• It is ideal to use all uppercase letters for a constant name• General Syntax
const dataType VARIABLE_NAME;
Scope
• The scope of a variable: the part of the program in which the variable can be accessed
• A variable cannot be used before it is defined
Variable Out of Scope
C++ Binary Arithmetic Operators
• C++ provides Five (5) simple arithmetic operators for creating arithmetic expressions
• Each of these arithmetic operators is a binary operator– Each takes two operands, one on each side of the
operator
C++ Binary Arithmetic Operators
C++ Binary Arithmetic Operators
• Addition, subtraction, multiplication, or division of any two integers results in an integer.
• If either or both of the operands in addition, subtraction, multiplication or division is a floating – point number, then the result is also a floating point number.
• Division (/ )• Integer division truncates remainder
• Modulus (%)– Modulus operator returns remainder
•
9 / 2 evaluates to 4
9 % 2 evaluates to 1
C++ Binary Arithmetic Operators
• Parentheses for Grouping Sub-expressions– Parentheses are used in C++ expressions to group
sub-expressions• Same manner as in algebraic expressions
– Example• b * ( d + e )
– Multiple b times the quantity d + e
C++ Shortcut Arithmetic Operators
• The following operators are valid shortcut arithmetic operators:+=-=*=/=
• The assignment operator (=) always appears second.
• You must not insert a space between the operators
C++ Shortcut Arithmetic Operators
Assignment operator
Sample expression
Explanation Assigns
Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;
+= c += 7 c = c + 7 10 to c
-= d -= 4 d = d - 4 1 to d
*= e *= 5 e = e * 5 20 to e
/= f /= 3 f = f / 3 2 to f
%= g %= 9 g = g % 9 3 to g
C++ Binary Arithmetic Operators
• Rules of Operator Precedence
Operator(s) Operation(s) Order of evaluation (precedence)
( ) Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.
*
/
%
Multiplication
Division
Modulus
Evaluated second. If there are several, they are evaluated left to right.
+ -
Addition
Subtraction Evaluated last. If there are several, they are evaluated left to right.
C++ Binary Arithmetic Operators
• Example: Rules of Operator Precedence
C++ Unary Operators
• Unary operators are those operators that require only one operand.
• The prefix and postfix increment and decrement operators are examples of unary operators
++count
count++
--num
num--
Prefix increment
Postfix increment
Prefix decrement
Postfix decrement
C++ Unary Operators
• Prefix operator, the mathematical operation takes place before the expression is evaluated.
• Postfix operator, the mathematical operation takes place after the expression is evaluated.
int num = 6;result = ++num;cout << result; // result is 7cout << num; // num is 7
int num = 6;result = num++;cout << result; // result is 6cout << num; // num is 7
Mathematical Expressions
• An expression is a programming statement that has a value.
• An expression usually consists of an operator and its operands
• Can create complex expressions using multiple mathematical operators
• An expression can be a literal, a variable, or a mathematical combination of constants and variables
• Can be used in assignment, cout, other statements:area = 2 * PI * radius;cout << "border is: " << 2*(l+w);
Associativity of Operators
• - (unary negation) associates right to left• *, /, %, +, - associate left to right• parentheses ( ) can be used to override the order of
operations: 4 + 4 * 4 – 4 =
(4 + 4) * 4 – 4 =
4 + 4 * (4 – 4) =
(4 + 4) * (4 – 4) =
?
?
?
?
Evaluating Boolean Expressions
• Boolean Expression– Evaluates as true or false
• C++ employs six relational binary operators.Standard algebraic equality or relational operator
C++ equality or relational operator
Sample C++ condition
Meaning of C++ condition
Relational operators
> x > y x is greater than y
< x < y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y
Equality operators
= == x == y x is equal to y
≠ != x != y x is not equal to y
Tips
A syntax error will occur if any of the operators ==, !=, >= and <= appears with spaces between its pair of symbols.
Reversing the order of the pair of symbols in any of the operators !=, >= and <= (by writing them as =!, => and =<, respectively) is normally a syntax error. In some cases, writing != as =! will not be a syntax error, but almost certainly will be a logic error that has an effect at execution time
Converting Algebraic expressions to Programming Statements
• In algebra it is not always necessary to use an operator for multiplication.
• C++, however, requires an operator for any mathematical operation.
• In converting some algebraic expressions to C++, you may have to insert parentheses that do not appear in the algebraic expression
Converting Algebraic expressions to Programming Statements
Converting Algebraic expressions to Programming Statements
Exponents in C++
• Standard library function pow()– Calculates an exponent– Example• xy = pow( x, y )
– Calculates the value of x raised to the yth power
– Requires header file <cmath>• <cmath>
– Contains function prototypes for math library functions