Lecture 2 variables

40
Intro to Programming with C+ + / Programming Using C++ CSD 106 / ICT 120

Transcript of Lecture 2 variables

Page 1: Lecture 2 variables

Intro to Programming with C++ / Programming Using C++

CSD 106 / ICT 120

Page 2: Lecture 2 variables

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

Page 3: Lecture 2 variables

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

Page 4: Lecture 2 variables

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 */

Page 5: Lecture 2 variables

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

Page 6: Lecture 2 variables

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

Page 7: Lecture 2 variables

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

Page 8: Lecture 2 variables

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.

Page 9: Lecture 2 variables

Floating-Point Data Types

Page 10: Lecture 2 variables

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

Page 11: Lecture 2 variables

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

Page 12: Lecture 2 variables

The Wider character Data Type

• Usually more than 1 byte of memory• A wider character variable is declared with the

keyword wchar_t

Page 13: Lecture 2 variables

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;

Page 14: Lecture 2 variables

The string class

Page 15: Lecture 2 variables

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

Page 16: Lecture 2 variables

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.

Page 17: Lecture 2 variables

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.

Page 18: Lecture 2 variables

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.

Page 19: Lecture 2 variables

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 ;

Page 20: Lecture 2 variables

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;

Page 21: Lecture 2 variables

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

Page 22: Lecture 2 variables

Variable Out of Scope

Page 23: Lecture 2 variables

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

Page 24: Lecture 2 variables

C++ Binary Arithmetic Operators

Page 25: Lecture 2 variables

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

Page 26: Lecture 2 variables

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

Page 27: Lecture 2 variables

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

Page 28: Lecture 2 variables

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

Page 29: Lecture 2 variables

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.

Page 30: Lecture 2 variables

C++ Binary Arithmetic Operators

• Example: Rules of Operator Precedence

Page 31: Lecture 2 variables

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

Page 32: Lecture 2 variables

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

Page 33: Lecture 2 variables

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);

Page 34: Lecture 2 variables

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) =

?

?

?

?

Page 35: Lecture 2 variables

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

Page 36: Lecture 2 variables

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

Page 37: Lecture 2 variables

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

Page 38: Lecture 2 variables

Converting Algebraic expressions to Programming Statements

Page 39: Lecture 2 variables

Converting Algebraic expressions to Programming Statements

Page 40: Lecture 2 variables

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