© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables and Constants
© Janice Regan, CMPT 128, Jan Tokens Token: smallest individual unit of a program Types of tokens include Reserved words Variables, Constants, Literals Functions Structures and classes Operators We will discuss each of these later
Why variables and constants? Calculate the sum of two numbers First you need the two numbers to add On paper write the numbers down to record them (store them) In a program those two numbers will be put into variables or constants to record them Each variable or constant (Each number) has a name (an identifier) so we can refer to it a value (the number being stored) © Janice Regan, CMPT 128, Sept
3 Constants and Variables Each constant or variable represents a specific item in the problem the program solves and is associated with a memory cell used to hold its value a unique identifier or name a data type The value of a constant does not change during execution of the program The value of a variable may be changed during the execution of a program.
© Janice Regan, CMPT 128, Jan C++ Identifiers Names of program components: Variables, Constants Structures, functions, enumerations, … (more later) IMPORTANT!!!.C++ is case sensitive The following identifiers (names ) are NOT the same Toy toy TOY
© Janice Regan, CMPT 128, Jan Legal C++ Identifiers Must contain only: Letters (upper and lower case) Digits (0-9) The underscore character ( _ ) Identifiers must begin with a letter or an _ Identifiers beginning with an underscore are used for specific purposes and should be avoided in general use
Reserved words In a computer language there are always a number of special words that are used as instructions and definitions in the language. These are called reserved words Reserved words cannot be used as identifiers © Janice Regan, CMPT 128, Sept
© Janice Regan, CMPT 128, Jan Reserved words in C++ A reserved word is a special word that gives the compiler a specific instruction it can understand (summary p489 text) asm, auto, bool, break, case, catch, char, const, class, continue default, delete, do, double, else, enum, explicit, export, extern false, float, for, friend, goto, if, inline, int, long, mutable, throw namespace, new, operator, private, protected, public, register return, short, signed, sizeof, static, struct, switch, template, this true, try, typedef, union, unsigned, using, virtual, void, volatile, while
© Janice Regan, CMPT 128, Jan More About C++ Identifiers Can divide identifiers into two groups Standard Identifiers: Identifiers defined by the compiler that are not parts of the C++ language definition This include identifiers used as names of functions in the standard C++ libraries User (programmer) defined Identifiers: Names the programmer chooses for quantities, functions, etc. used in their own programs
© Janice Regan, CMPT 128, Jan Program - sum two numbers #include using namespace std; int main() { // Declare variables. double number1, number2; double sum; // Initialize variables number2 = 45.7; number1 = 473.9; // Calculate and print the sum. sum = number1 + number2; cout << “The sum is ” << sum << endl; // Return successful termination indicator return 0; } Standard identifiers
© Janice Regan, CMPT 128, Jan Illegal Identifiers Prog#1The # is not a letter digit or _ 1stprogramcannot begin with a digit autocannot be a keyword
© Janice Regan, CMPT 128, Jan Which Are Legal C++ Identifiers? cycle A!star int Score Y-Z Trial#2 This_One $MyProgram FOR 3constant_values “MaxScores” _External_Prog Mary’s StarChart
© Janice Regan, CMPT 128, Jan More About C++ Identifiers An identifier should be descriptive. It makes your code much easier to understand and maintain sideLength is much clearer than sl But keep your names a reasonable length The maximum number of significant characters in an identifier is determined by the operating system and compiler used.
© Janice Regan, CMPT 128, Sept Components of a C++ Program More types of tokens (smallest individual units of a program) include: String Literal Constants or constant labels used in expressions Bob in expression Name = ” Bob”; Literal Constants or fixed numbers used in expressions 3 in expression y = x + 3; Variables and Constants
© Janice Regan, CMPT 128, Sept Constants and Variables Each constant or variable represents a specific item in the problem the program solves and is associated with a memory cell used to hold its value a unique identifier or name a data type The value of a constant does not change during execution of the program The value of a variable may be changed during the execution of a program.
© Janice Regan, CMPT 128, Sept Types of Constants and Variables A Data Type is A set of values plus a set of operations on those values A crucial concept on modern programming The data type of a variable or constant also determines how the variable’s value will be represented in memory Variables of several types can have numerical values Variables of other types have values that are characters, or logical values.
© Janice Regan, CMPT 128, Sept Types with Numerical Values Two classes of numerical values Integer and floating point Integer values are whole numbers No fractional part 1, 12354, 68, -123 C++ Types: int, unsigned int, long int, short int, long unsigned int, …
© Janice Regan, CMPT 128, Sept Types with Numerical Values Two classes of numerical values Integer and floating point Floating point values have a fractional part 987.4, , 0.123, C++ types: float, double, long double Integers and floating point numbers are represented differently inside the computer
© Janice Regan, CMPT 128, Sept Declaring the variables you need A first step in building the body of your main function is the declaration of the variables you will need to execute your algorithm. To declare a variable we need to choose an identifier as the name of the variable. choose what the type of the variable is.
© Janice Regan, CMPT 128, Sept Declaration of Variables Programming style for this course: Declare one variable or constant per statement Declare all variables at the start of the function. Examples: int myintegervalue; double scalefactor; float temperature;
© Janice Regan, CMPT 128, Sept Program - sum two numbers #include using namespace std; int main( ) { // Declare variables. double number1; double number2: double sum; // Initialize variables number2 = 45.7; number1 = 473.9; // Calculate and print the sum. sum = number1 + number2; cout << “The sum is ” << sum << endl; // Return successful termination indicator return 0; }
© Janice Regan, CMPT 128, Sept Initialization of Variables Memory locations associated with variables should have their values defined before the start of program execution. Using uninitialized variables often produces unpredictable results Programming style for this course: Initialize all variables at the start of your executable code Initialize when or just after your variables have been declared
© Janice Regan, CMPT 128, Sept Program - sum two numbers #include using namespace std; int main(void) { // Declare variables. double number1; double number2; double sum; // Initialize variables number2 = 45.7; number1 = 473.9; sum = 0.0; // Calculate and print the sum. sum = number1 + number2; cout << “The sum is ” << sum << endl; // Return successful termination indicator return 0; }
© Janice Regan, CMPT 128, Sept Program - sum two numbers #include using namespace std; int main(void) { // Calculate and print the sum. sum = number1 + number2; cout << “The sum is ” << sum << endl; // Return successful termination indicator return 0; } // Declare and initialize variables. double number1 = 473.9; double number2 = 45.7; double sum=0.0;
© Janice Regan, CMPT 128, Sept Literal Data Literals Examples of literal constants: 2/*Literal constant int*/ 5.75/* Literal constant double*/ Examples of string literal constants "Z"/* String literal constant char array*/ "Hello World"/* String literal constant string*/ Cannot change values during execution Called "literals" because you "literally typed" them in your program! Literals do not have identifiers (names), they are used directly in the C++ code
© Janice Regan, CMPT 128, Sept Program - sum two numbers #include using namespace std; int main(void) { // Declare variables. double number1, number2; double sum; // Initialize variables number2 = 45.7; number1 = 473.9; // Calculate and print the sum. sum = number1 + number2; cout << “The sum is ” << sum << endl; // Return successful termination indicator return 0; } String literal constants literal constants
© Janice Regan, CMPT 128, Sept Named Constants Naming your constants Literal constants are "OK", but provide little meaning e.g., seeing 45.7 in a program, tells nothing about what it represents Use named constants instead Meaningful name to represent data const double FIRST_NUMBER = 45.7; Called a "declared constant" or "named constant" Now use it’s name wherever needed in program Added benefit: changes to value need only be made once
Programming style: summary Descriptive identifiers Declare and initialize all variables at the start of each program (function) Easier to keep track of variables, they will always be available for the whole program (function) You will not have problems with undeclared variables Use named constants, not literal constants Easier to keep track of what the constants mean Easier to keep track of what the constants values are © Janice Regan, CMPT 128, Sept
© Janice Regan, CMPT 128, Sept Components: C, C++ Programs Operators actions used to combine variables and or constants Example = and + in the expression y = x + THREE;
© Janice Regan, CMPT 128, Sept Binary Arithmetic Operators A Binary Operator operates on two arguments + addition -subtraction * multiplication / division % modulus or remainder (only for integers, 5%2=1) Evaluated left to right (C and C++)
© Janice Regan, CMPT 128, Sept Unary Arithmetic Operators in C++ A Unary Operator operates on one argument + positive -negative ++ increment --decrement ~ones complement Evaluated right to (C and C++)
© Janice Regan, CMPT 128, Sept Expressions in C and C++ An expression can be a single variable, or can be a series of variables combined using operators Arithmetic expressions manipulate numeric variables following the rules of algebra The two variables or constants combined using a binary arithmetic operator should have the same type Otherwise conversions are needed (more later)
© Janice Regan, CMPT 128, Sept Precedence of operators in C++ ( ) []. innermost first static_cast (pre) + - ! ~ & *(unary operators) * / % + - = += -= *= /= %= Evaluate 2 and 5 right to left Evaluate 1, 3, and 4 left to right
© Janice Regan, CMPT 128, Sept Expressions: arithmetic operators A + B + C X + C Let A=10, B=5, C=2 + A B X C A B C + + Value of expression
© Janice Regan, CMPT 128, Sept Expressions: arithmetic operators Order of operations is determined by operator precedence rules / before + A + B / C A + X Let A=10, B=5, C=2 + A B X C / A B C / + Value of expression
© Janice Regan, CMPT 128, Sept Importance of order of operations Order of operations is determined by operator precedence rules () before / (A + B) / C X / C Let A=10, B=5, C=2 2 A B C + / + A B X C Value of expression
© Janice Regan, CMPT 128, Sept Expressions: arithmetic operators Types of operands: float vs. integer divide An operator always operates on two operands of the same type A + B / C A + X Let A=23.7, B=55.4, C=1.2 + A B X C / Value of expression A B C / +
© Janice Regan, CMPT 128, Sept Expressions: arithmetic operators Let A=27, B=5, C=2, D=3, E=8 ((A + B) / C) – D % E ( X / C) – D % E Y – D % E Y – Z + A B X C / Y D 3 8 % Z E A B C + % D E / _
© Janice Regan, CMPT 128, Sept Expressions: arithmetic operators Order of operations is determined by operator precedence rules unary -, before /, before + -A + B / C X + B / C X + Y Let A=10, B=5, C=2 + X B Y C / A B C / + - A 10 -
© Janice Regan, CMPT 128, Sept Expressions: arithmetic operators ++A – B pre increment --B + C pre decrement Pre-increment: increment variable then use in expression A * C++ post increment A / C-- post decrement Post increment: use variable in expression then increment the variable
© Janice Regan, CMPT 128, Sept Order of operations is determined by operator precedence rules unary ++ and --, before /, before + ++A + B / --C ++A + B / C (C=1) A + B / C (A=11) A + Z Let A=10, B=5, C=2 Expressions: arithmetic operators + A B C C / A B C / + ++ A Z 5
© Janice Regan, CMPT 128, Sept Order of operations is determined by operator precedence rules unary ++ and --, before /, before + A-- + B / --C A-- + B / C (C=1) A-- + Z A (A=9) Let A=10, B=5, C=2 Expressions: arithmetic operators + B C C / A B C / + -- A Z 5 A A
© Janice Regan, CMPT 128, Sept Q = (++A + B / --C); This is a shorthand way of writing C = C – 1; A = A + 1; Q = (A + B / C); Why use increment / decrement
© Janice Regan, CMPT 128, Sept Q = (A-- + B / --C); This is a shorthand way of writing C = C – 1; Q = (A + B / C); A = A - 1; Why use increment / decrement
© Janice Regan, CMPT 128, Sept Assignment Statements Basic statement used to perform calculations Form: result = expression; Example: A = B + C * D; NOT the same as an = in an equation Each variable is associated with a location in memory Evaluate the expression on the right (B+C*D) Multiply the value in the memory location associated with variable C by the value in the memory location associated with variable D Add the product to the value of the in the memory location associated with variable B The sum is the value of the expression The value of the expression on the right hand side is placed in the memory location associated with variable A
© Janice Regan, CMPT 128, Sept Expressions: arithmetic operators Order of operations is determined by operator precedence rules * before + before = A = B + C * D A = B + X A = Y A=10, B=5, C=2, D=12 + X C B D * A B C * + = D Y A =
© Janice Regan, CMPT 128, Sept Assignment Statements: Form: result = expression; Example: X = X * Y; Each variable is associated with a location in memory Evaluate the expression on the left (X*Y) Multiply the value in the memory location associated with variable X by the value in the memory location associated with variable Y The product is the value of the expression The product is placed in the memory location associated with variable X overwriting the previous value of X
© Janice Regan, CMPT 128, Sept Assignment operators A = B assign value of expression B to variable A, store value of expression B in A A += B add the value of expression B to the value of variable A, store result in A A -= B subtract the value of expression B from the value of variable A, store result in A A *= B multiply the value of variable A by the value of expression B, store result in A A /= B divide the value of variable A by the value of expression B, store result in A