Professional Documents
Culture Documents
PF Lec06 Assignment Operations and Format Manipulators 08-09-2023
PF Lec06 Assignment Operations and Format Manipulators 08-09-2023
Lecture 6
2
Variables
3
Variables
Rules:
• The variable name must begin with a letter or
underscore (_) and can contain only letters,
underscores, or digits. It can’t contain blank
spaces, commas, or special symbols, such as
( ), & , $ # . ! \ ?.
C++ statements:
Important:
Assignment statement has one equal to
sign (=) and one variable name
immediately to the left of = 5
Declaration Statements
• To name a variable and specify the data type that can be stored in it
dataType variableName;
Examples :
int variableName;
int sum;
long datenum;
long int datenum;
float firstnum; (single precision number)
double secnum; (double precision number)
Copyright © 2013 The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 6
Rules for declaration statements
7
Multiple Declarations
• Variables of the same data type can always be grouped together and declared by
using a single declaration statement, which has this common form:
dataType variableList;
• For example, the four separate declarations used in Program 2.7
double grade1;
double grade2;
double total;
double average;
9
Example
#include<iostream>
using namespace std;
int main()
{
double grade1 = 85.5, grade2 = 97.0, total, average;
• variable = expression;
• length = 25;
• width = 17.5;
12
Examples using operators
slope = 3.7;
slope = 6.28; //
sum = 3 + 7;
diff = 15 - 6;
product = .05 * 14.6;
tally = count + 1;
newtotal = 18.3 + total;
taxes = .06 * amount;
totalWeight = factor * weight;
average = sum / items;
slope = (y2 - y1) / (x2 - x1);
Copyright © 2013 The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 13
Example
14
Assignment Expression
• assignment operator
The = symbol
• assignment expression.
expression using this operator e.g. interest = principal * rate
15
Multiple assignments
a = b = c = 25;
This statement is equivalent to
a= (b=(c=25))
Copyright © 2013 The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 16
Coercion
• int temp;
• temp = 25.89;
Value of a?
17
Casts
dataType (expression)
• The dataType is the data type to which the
expression in parentheses is converted. For
example, the following expression
int (a * b)
• converts the value of the expression a * b
to an integer value
Runtime casts & compile
time casts
• static_cast<data-type> (expression)
int main()
{
float a=2.7,b=3.2; cout<<a*b<<endl;
cout<<int(a*b)<<endl;
cout<<static_cast<int>(a*b)<<endl;
cout<< (int(a)*int(b))<<endl;
return 0; } 19