300580 Programming Fundamentals 3 With C++ Variable Declaration, Evaluation and Assignment 1
Today s Topics Variable declaration Assignment to variables Typecasting Counting Mathematical functions Keyboard input Constant variables 2
Variables Symbolic names used in place of memory addresses Symbolic names are called variables These variables refer to memory locations The value stored in the variable can be changed Simplifies programming effort 3
Variable Declarations All variables must be declared before being used Declaration tells the data type of a variable so that a compiler can Allocate suitable memory space for the variable Check for program syntax errors in terms of data type compatibility 4
Declaration Statement Names a variable, specifies its data type General form: datatype variablename; e.g. int sum; declares sum as variable which stores an integer value Declaration statements can be placed anywhere in function Typically grouped together and placed immediately after the function s opening brace 5
Identifier Naming Conventions A variable in C++ must begin with a letter or underscore must consist of letters, digits, or underscore can be of any length cannot be a C++ reserved word (see next slide) use meaningful names, e.g. incometax start all (variable, function) names with lowercase letter C++ is case sensitive! 6
C++ Key Words Not to be used as variable names char, int, short, long, float, double, enum, void, signed, unsigned, const if, else, switch, case, default, while, for, do, break, continue, goto sizeof, return, typedef, auto, static new, delete, struct, union, class, private, public, protected, friend More, see Table 1.1 in textbook 7
Examples of Variable Names Examples of valid identifiers: grosspay taxcalc addnums degtorad multbytwo salestax netpay bessel Examples of invalid identifiers: 4ab3 (begins with a number) e*6 (contains a special character) while (is a keyword) 8
Example #include<iostream> using namespace std; int main( ) { char ch; // declares a character variable ch = 'a'; // stores the letter a into ch cout << "The character stored in ch is " << ch << endl; ch = 'm'; // now stores new letter m into ch cout << "The character now stored in ch is " << ch << endl; return 0; } 9
Implication of a Declaration Tells compiler to Reserve enough room for an integer number int total; 4 Physical storage bytes Tells compiler to tag the reserved storage with the name total 10
Declaration with Initialisation Tells compiler to int total=12; Byte of lower address Reserve enough room for an integer number 12 0 0 0 4 bytes Tells compiler to assign value 12 to the reserved storage for the variable 11
Declaration of Multiple Variables Variables with the same data type can be grouped together and declared in one statement format: datatype variablelist ; e.g. double grade, total, average; Initialization: using a declaration statement to store a value in a variable Good programming practice is to declare each initialized variable on a line by itself e.g. double grade2 = 93.5; 12
Summary A simple C++ program containing declaration statements has the format: #include <iostream> using namespace std; int main( ) { declaration statements; other statements; Usual Layout } return 0; 13
Your Turn Write a C++ program in which a variable salary is declared in a proper type. Initialise the variable to the value $76,543.21 and display it to the screen. #include<iostream> using namespace std; int main( ) { double salary=76543.21; cout << salary; return 0; } int float double?? 14
Assignment Operators. Basic Assignment Operator: format: variable = expression; computes value of expression on right of "=" sign, assigns it to variable on left side of "=" If not initialized in a declaration statement, a variable should be assigned a value before being used in any computation Variables can only store 1 value at a time Subsequent assignment statements will overwrite the previously assigned values 15
Assignment Operators.. Operand to right of = sign can be A constant A variable A valid C++ expression Operand to left of = sign must be a variable If the operand on the right side is an expression, all variables in expression must have a value in order to get a valid result from the assignment 16
Assignment Operators... Expression: combination of constants and variables that can be evaluated Assignment examples sum = 3 + 7; diff = 15 6; product =.05 * 14.6; tally = count + 1; newtotal = 18.3 + total; average = sum / items; slope = (y2 y1) / (x2 x1); 17
#include<iostream> using namespace std; int main( ) { double length, width, area; length = 27.2; width = 13.6; area = length * width; This program calculates the area of a rectangle given its length and width. cout << "Area of given rectangle = " << area << endl; return 0; } OUTPUT: Area of given rectangle = 369.92 18
Coercion Value on right side of a C++ expression is converted to data type of variable on the left side of the assignment operator = Example: If temp is an integer variable, the assignment temp = 25.89; causes integer value 25 to be stored in integer variable temp 19
Assignment Variations sum = 2*sum + 1; is a valid C++ expression value of 2*sum+1 is stored in variable sum not a valid algebra equation lvalue: any valid quantity on left side of assignment operator rvalue: any valid quantity on right side of assignment operator A number can only be an rvalue A variable can appear on either side of an assignment expression 20
#include<iostream> using namespace std; int main( ) { int sum; Old value overwritten 25 35 sum = 25; cout << "The number stored in sum is " << sum << endl; sum New value is stored sum = sum + 10; cout << "The number stored in sum is " << sum << endl; return 0; } 21
Assignment Variations Assignment expressions such as sum = sum + 25; can be by using a particular one shortcut operator of the following: += -= *= /= %= e.g. sum = sum + 10; can be written as sum += 10; 22
Accumulating The following statements add the numbers 96, 70, 85 and 60 in the calculator fashion: Statement Value in sum sum = 0; 0 sum = sum + 96; 96 sum = sum + 70; 166 sum = sum + 85; 251 23
#include<iostream> using namespace std; int main( ) { int sum; OUTPUT: sum now is 0 sum now is 96 sum now is 166 The final sum is 251 sum = 0; cout << "sum now is " << sum << endl; sum = sum + 96; cout << "sum now is " << sum << endl; sum = sum + 70; cout << "sum now is " << sum << endl; sum = sum + 85; cout << "The final sum is " << sum << endl; return 0; } 24
Counting. Has the form: variable = variable + fixednumber; Each time statement is executed, value of variable is increased by a fixed amount Increment/Decrement Operator (++)/(--) Unary operator for special case when variable is increased or decreased by 1 Using the increment operator, the expression variable = variable + 1; can be replaced by either ++variable; or variable++; 25
Counting.. Examples of counting statements: i= i + 1; n = n + 1; count = count + 1; j = j + 2; m = m + 2; kk = kk + 3; 26
Counting... OUTPUT: count now is 1 count now is 2 Examples of the increment operator: Expression i = i + 1 n = n + 1 count = count + 1 #include<iostream> using namespace std; int main( ) { int count; count = 1; cout << "count now is " << count << endl; Alternative i++ or ++i n++ or ++n count++ or ++count count++; cout << "count now is " << count << endl; return 0; } 27
Prefix/Postfix Increment Operator How is it actually done? It s possible to write C++ programs without using any of these operators total = total + 1; total += 1; ++total; total++; tmpholder= total + 1; total = tmpholder; sum= total++ + 10; sum=total+10, total=total+1; sum= ++total + 10; total=total+1, sum=total+10; Execution order 28
Mathematical Library Functions. Standard preprogrammed functions that can be included in a program e.g sqrt(number) calculates the square root of number Many mathematical functions are available in C++, see Table 3.1 To access these functions in a program, the header file cmath must be used: #include <cmath> 29
Mathematical Library Functions.. What will a header file typically contain? Why including the header file? Before using a C++ mathematical function the programmer must know: Name of the desired mathematical function What the function does Type of data required by the function Data type of the result returned by the function 30
Mathematical Library Functions... Some Maths Functions: abs(x): absolute value of x pow(x, y): x raised to the y power sqrt(x): square root of x Examples: abs(-.302) gives 7.302 pow(2.0, 5.0) gives 32.0 #include<iostream> #include<cmath> using namespace std; int main( ) { double x = 3.1416; double root; root = sqrt(x); cout << "Square root of Pi=" << root << endl; return 0; } result 31
Typecasting: Explicit vs Auto (new type) variable (new type) (expression) char c='a'; int i=(int) c; unsigned long m=(unsigned long) c; m=1234567890; c=char(m); char c='a'; int i= c; unsigned long m= c; m=1234567890; c= m; m= char(m)* 1234; m= m * 1234; 32
Evaluation of expr1 op expr2 For a maths op (+, -, *, /, etc), evaluation is done directly if both expr1 and expr2 have the same data type (meaningful for the op) Otherwise, the less richer type of the operants is promoted (typecast) to the other richer type first before the evaluation The resulting type of the evaluation is thus the richest type of the both operands 33
Interactive Keyboard Input If a program only executes once, data can be included directly in the program If data changes, program must be rewritten Capability is needed to enter different data cin object: used to enter data while a program is executing Example: cin >> num1; Statement stops program execution and accepts data from the keyboard 34
Interactive Keyboard Input cin, like cout, is contained in a C++ library prototyped by the header file iostream Must include the header file via e.g. #include <iostream> How to read values into variables from keyboard ( standard input device ): cin >> varname; cin >> var1 >> var2 >>... >> varn ; 35
#include<iostream> using namespace std; int main( ) { double num1, num2, product; cout << "Type in a number: "; cin >> num1; cout << "Type in another number: "; cin >> num2; product = num1 * num 2; cout << num1 << " times " << num2 << " is " << product << endl; return 0; } // simplest IO Session output Type in a number: 30 Type in another number: 0.01 30 times 0.01 is 0.3 36
What will Happen during the Execution? Program first prints out a message (a prompt), telling the person at the terminal what to do Next statement, cin, pauses computer waits for user to type a value user signals the end of data entry by pressing ENTER key entered value stored in variable to the right of extraction symbol (>>) Computer comes out of pause and goes to next statement (e.g. cout statement) 37
Symbolic Constants. Magic Numbers: literal data used in a program. e.g. π = 3.1416 Constants can be assigned symbolic names const float PI = 3.1416f; const double SALESTAX = 0.05; Must be declared before use Data of const type can not be modified compiler to ensure this, a measure against programming bugs 38
Symbolic Constants.. const: qualifier specifies that the declared identifier cannot be changed A const identifier can be used in any C++ statement in place of number it represents circum = 2 * PI * radius; amount = SALESTAX * purchase; const identifiers commonly referred to as: symbolic constants named constants 39
Placement of Statements As a matter of good programming practice, the order of statements typically should be preprocessor directives int main() { symbolic constants variable declarations other executable statements return value } 40
OUTPUT #include<iostream> using namespace std; int main( ) Enter the amount purchased: 3000 The sales tax = 150 The total bill = 3150 { const double SALESTAX = 0.05; double amount, taxes, total; cout << "\nenter the amount purchased: "; cin >> amount; taxes = SALESTAX * amount; total = amount + taxes; cout << "The sales tax = " << taxes << endl; cout << "The total bill = " << total << endl; return 0; } 41
Reading Bronson s 3 rd Edition: Chapter 3, Section 2.4 Bronson s 4 th Edition: Chapter 3 Robertson s Chapters 1, 2 (secondary) Secondary, here and later on, refers to desirable reading material, which is of less priority than the other (primary) reading material. 42