42
1 300580 Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3

300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

1

300580

Programming

Fundamentals

With C++

Variable Declaration, Evaluation and Assignment

3

Page 2: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

2

Today’s Topics

� Variable declaration

� Assignment to variables

� Typecasting

� Counting

� Mathematical functions

� Keyboard input

� Constant variables

Page 3: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

3

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

Page 4: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

4

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

Page 5: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

5

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

Page 6: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

6

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!

Page 7: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

7

C++ Key Words

� 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

Not to be used as variable names

Page 8: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

8

Examples of Variable Names

� Examples of valid identifiers:

grosspay taxCalc addNumsdegToRad multByTwo salesTax

netPay bessel

� Examples of invalid identifiers:

4ab3 (begins with a number)

e*6 (contains a special character)

while (is a keyword)

Page 9: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

9

Example#include<iostream>using namespace std;int main( ) {char ch; // declares a character variablech = 'a'; // stores the letter a into chcout << "The character stored in ch is "

<< ch << endl;

ch = 'm'; // now stores new letter m into chcout << "The character now stored in ch is "

<< ch << endl;return 0;}

Page 10: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

10

Implication of a Declaration

int total; 4 bytes

Reserve enough room for an integer number

Tells compiler to

“tag” the reserved storage with the name total

Tells compiler to

Physical

storage

Page 11: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

11

Declaration with Initialisation

int total=12;

Reserve enough room for an integer number

4 bytes

Tells compiler to

assign value 12 to the

reserved storage for the variable

12 0 0 0

Tells compiler to

Byte of lower

address

Page 12: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

12

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;

Page 13: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

13

Summary

� A simple C++ program containing declaration statements has the format:

#include <iostream>using namespace std;int main( ){declaration statements;

other statements;

return 0;}

UsualLayout

Page 14: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

14

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

intfloatdouble ??

Page 15: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

15

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

Page 16: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

16

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

Page 17: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

17

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

Page 18: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

18

#include<iostream>using namespace std;

int main( ) {double length, width, area;length = 27.2;width = 13.6;area = length * width;

cout << "Area of given rectangle = "<< area << endl;

return 0;}

This program calculates the area of a rectangle given its length and width.

Area of given rectangle = 369.92

OUTPUT:

Page 19: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

19

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

Page 20: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

20

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

Page 21: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

21

#include<iostream>using namespace std;

int main( ) {int sum;

sum = 25;cout << "The number stored in sum is "

<< sum << endl;

sum = sum + 10;cout << "The number stored in sum is "

<< sum << endl;return 0;}

25

sum

Old value overwritten

25 35

New value is stored

Page 22: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

22

Assignment Variations

� Assignment expressions such assum = sum + 25; can be by using a particular one shortcut operator of the following:

+= -= *= /= %=

� e.g.sum = sum + 10;

can be written assum += 10;

Page 23: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

23

Accumulating

� The following statements add the numbers 96, 70, 85 and 60 in the calculator fashion:

Statement Value in sum

sum = 0; 0sum = sum + 96; 96sum = sum + 70; 166sum = sum + 85; 251

Page 24: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

24

#include<iostream>using namespace std;

int main( ) {int sum;

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

OUTPUT:sum now is 0sum now is 96sum now is 166The final sum is 251

Page 25: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

25

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 expressionvariable = variable + 1; can be replaced by either ++variable; or variable++;

Page 26: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

26

Counting ..

� Examples of counting statements:

i= i + 1;

n = n + 1;

count = count + 1;

j = j + 2;

m = m + 2;

kk = kk + 3;

Page 27: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

27

Counting ...

� Examples of the increment operator:Expression Alternative

i = i + 1 i++ or ++i

n = n + 1 n++ or ++n

count = count + 1 count++

or ++count#include<iostream>using namespace std;int main( ) {int count;count = 1;cout << "count now is "

<< count << endl;

count++;cout << "count now is "

<< count << endl;return 0;}

OUTPUT:

count now is 1

count now is 2

Page 28: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

28

Prefix/Postfix Increment Operator

� sum= ++total + 10;

� total=total+1, sum=total+10;

total = total + 1;total += 1;++total;total++;

tmpHolder= total + 1;total = tmpHolder;

How is it actually done?

� sum= total++ + 10;

� sum=total+10, total=total+1;

Execution order

It’s possible to write C++ programs without

using any of these

operators

Page 29: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

29

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>

Page 30: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

30

Mathematical Library Functions ..

� 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

What will a header

file typically contain?

Page 31: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

31

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.0result

#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;}

Page 32: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

32

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;

Page 33: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

33

Evaluation ofexpr1 op expr2

� For a maths op (+, -, *, /, etc), evaluation is done directly if both expr1 and expr2have 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

Page 34: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

34

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

Page 35: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

35

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 ;

Page 36: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

36

#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

Type in a number: 30Type in another number: 0.0130 times 0.01 is 0.3

Session output

Page 37: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

37

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)

Page 38: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

38

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

Page 39: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

39

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

Page 40: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

40

Placement of Statements …

� As a matter of good programming practice, the order of statements typically should be

preprocessor directivesint main(){

symbolic constantsvariable declarationsother executable statementsreturn value

}

Page 41: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

41

#include<iostream>using namespace std;

int main( ) {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;}

Enter the amount purchased: 3000

The sales tax = 150

The total bill = 3150

OUTPUT

Page 42: 300580 Programming Fundamentals - Western Sydneyzhuhan/... · Programming Fundamentals With C++ Variable Declaration, Evaluation and Assignment 3. 2 Today’s Topics Variable declaration

42

Reading

� Bronson’s 3rd Edition:� Chapter 3, Section 2.4

� Bronson’s 4th 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.