Sei sulla pagina 1di 38

Week 3

Assignment, Formatting and Interactive Input

CS001P Programming Fundamentals 1

7/2/2015

Assignment Operations
Assignment Statement: assigns the value of the expression on
the right side of the = to the variable on the left side of the =
The symbol "=" is known as the assignment operator. The meaning of "=" in programming
is different from Mathematics. It denotes assignment instead of equality.

Example:
Assignment operation to calculate an Employees raise.

raise = currentPay * raiseRate


Note: You cannot use an assignment statement to assign a value to a named
constant, because the contents of a named constant cannot be changed while a
program is running.

CS001P Programming Fundamentals 1

7/2/2015

Assignment Statement (cont)


Another assignment statement using same variable will overwrite the
previous value with the new value.

Only one variable can be on the left side of an assignment statement.

CS001P Programming Fundamentals 1

7/2/2015

Assignment Statement (cont)


Right side of an assignment statement may contain any expression
that can be evaluated to a value.
Examples:

newtotal = 18.3 + total;


taxes = .06*amount;
average = sum / items;

Only one variable can be on the left side of an assignment


statement.
CS001P Programming Fundamentals 1

7/2/2015

Assignment Statement (cont)


Additional assignment operators provide short cuts: +=, -=, *=, /=, %=

Example:
sum = sum + 10;
is equivalent to: sum += 10;
price *= rate +1;
is equivalent to:
price = price * (rate + 1);

CS001P Programming Fundamentals 1

7/2/2015

Assignment Statement (cont)


Accumulation statement: has the effect of accumulating, or
totaling.
Syntax:
variable = variable + newValue;

CS001P Programming Fundamentals 1

7/2/2015

Type Casting
Implicit Type-Conversion vs. Explicit Type-Casting
Converting a value from one type to another type is called type
casting (or type conversion).
There are two kinds of type casting:

1. Implicit type-conversion performed by the compiler


automatically
2. Explicit type-casting via an unary type-casting operator in
the form of
(new-type)operand and or new-type(operand).

CS001P Programming Fundamentals 1

7/2/2015

Implicit (Automatic) Type Conversion


When you assign a value of a fundamental (built-in) type to a variable
of another fundamental type, C++ automatically converts the value to
the receiving type, if the two types are compatible.
For example:
If you assign an int value to a double variable, the compiler automatically
casts the int value to a double and assigns it to the double variable.
If you assign a double value of to an int variable, the compiler automatically
casts the double value to an int value and assigns it to the int variable. The
fractional part would be truncated and lost. Some compilers issue a
warning/error possible loss in precision; others do not.

C++ will not perform automatic type conversion, if the two types are
not compatible.
CS001P Programming Fundamentals 1

7/2/2015

Implicit Type Conversion Example

CS001P Programming Fundamentals 1

7/2/2015

Explicit Type-Casting
Explicitly perform type-casting via the so called unary type-casting
operator in the form of (new-type)operand or new-type(operand).
The type-casting operator takes one operand in the particular type,
and returns an equivalent value in the new type.

CS001P Programming Fundamentals 1

7/2/2015

10

Explicit Type-Casting Example

CS001P Programming Fundamentals 1

7/2/2015

11

Operator static-cast<type>
C++ introduces a new operator called static_cast<type> to perform
type conversion (because the regular cast mentioned earlier is too lax
and could produce expected results).
static_cast signals an error if conversion fails.
Example:

CS001P Programming Fundamentals 1

7/2/2015

12

Increment/Decrement Operators
Increment Operator ++: unary operator for the special case
when a variable is increased by 1.
Prefix Increment operator appears before the variable.
Example: ++i

Postfix Increment operator appears after the variable.


Example: i++

CS001P Programming Fundamentals 1

7/2/2015

13

Increment/Decrement Operators (cont)


Example:
k =
is equivalent to
n = n + 1;
k = n;
Example:
k =
increment
is equivalent to
k = n;
n = n + 1;

++n; //prefix increment


//increment n first
//assign ns value to k
n++; //postfix

//assign ns value to k
//and then increment n
CS001P Programming Fundamentals 1

7/2/2015
14

Increment/Decrement Operators (cont)


Decrement operator --: unary operator for the special case when a
variable is decreased by 1

Prefix decrement operator appears before the variable


Example:

--i;

Postfix decrement operator appears after the variable


Example:

i--;

CS001P Programming Fundamentals 1

7/2/2015
15

Increment/Decrement Operators Example

CS001P Programming Fundamentals 1

7/2/2015

16

Formatting Numbers for Program Output


Proper output formatting contributes to
ease of use and user satisfaction.
cout with stream manipulators can control
output formatting

CS001P Programming Fundamentals 1

7/2/2015

17

Formatting Numbers for Program Output (cont)

CS001P Programming Fundamentals 1

7/2/2015

18

Formatting Numbers for Program Output (cont)


The field width manipulator must be included for each value
in the data stream sent to cout.
Other manipulators remain in effect until they are changed.
<iomanip> header file must be included to use
manipulators requiring arguments.

CS001P Programming Fundamentals 1

7/2/2015

19

Formatting Numbers for Program Output (cont)


Formatting floating-point numbers requires three field-width
manipulators to
Set the total width of the display
Force a decimal place
Set the number of significant digits after the decimal point

Example:

produces this output:

CS001P Programming Fundamentals 1

7/2/2015

20

Formatting Numbers for Program Output (cont)


setprecision: sets the number of digits after the decimal
point if a decimal point has been explicitly forced; otherwise,
it sets the total number of displayed digits.
If the field width is too small, cout ignores the setw
manipulator setting and allocates enough space for printing.
If setprecision setting is too small, the fractional part of the
value is rounded to the specified number of decimal places.
CS001P Programming Fundamentals 1

7/2/2015

21

Formatting Numbers for Program Output (cont)


If setprecision value is too large, the fractional value is
displayed with its current size.
setfill(char fill-char): set the filled character for padding to the
field width.
fixed/scientific (for floating-point numbers): use fixednotation (e.g. 12.34) or scientific notation (e.g. 1.23e+006).

CS001P Programming Fundamentals 1

7/2/2015

22

Formatting Numbers for Program Output Example

CS001P Programming Fundamentals 1

7/2/2015

23

Using Mathematical Library Functions


C++ has preprogrammed mathematical functions that can be included
in a program.
You must include the cmath header file:
#include <cmath>

Math functions require one or more arguments as input, but will


return only one value
All functions are overloaded, and can be used with integer and real
arguments

CS001P Programming Fundamentals 1

7/2/2015

24

Using Mathematical Library Function (cont)


Table 3.5 Common C++ Functions

CS001P Programming Fundamentals 1

7/2/2015

25

Using Mathematical Library Function (cont)

CS001P Programming Fundamentals 1

7/2/2015

26

Using Mathematical Library Function (cont)


To use a math function, give its name and pass the input
arguments within parentheses.
Expressions that can be evaluated to a value can be passed as
arguments.

CS001P Programming Fundamentals 1

7/2/2015

27

Mathematical Library Function Example

CS001P Programming Fundamentals 1

7/2/2015

28

Using Mathematical Library Function (cont)


Function calls can be nested
Example: sqrt(sin(abs(theta)))

Cast operator: a unary operator that forces the data to the


desired data type.
Compile-time cast
Syntax: dataType (expression)
Example: int(a+b)

CS001P Programming Fundamentals 1

7/2/2015

29

Using Mathematical Library Function (cont)


Run-time cast: the requested conversion is checked at run
time and applied if valid.
Syntax:
staticCast<data-type>(expression)
Example:
staticCast<int>(a*b)

CS001P Programming Fundamentals 1

7/2/2015

30

Program Input Using the cin Object


cin Object: allows data entry to a running program
Use of the cin object causes the program to wait for input
from the keyboard
When keyboard entry is complete, the program resumes
execution, using the entered data
An output statement preceding the cin object statement
provides a prompt to the user

CS001P Programming Fundamentals 1

7/2/2015

31

Program Input Using the cin Object (cont)

CS001P Programming Fundamentals 1

7/2/2015

32

Program Input Using the cin Object (cont)


cin can accept multiple input values to be stored in different
variables
Multiple numeric input values must be separated by spaces
Example:
cin >> num1 >> num2
with keyboard entry: 0.052 245.79

CS001P Programming Fundamentals 1

7/2/2015

33

Program Input Using the cin Object (cont)

CS001P Programming Fundamentals 1

7/2/2015

34

Program Input Using the cin Object (cont)


User-input validation: the process of ensuring that
data entered by the user matches the expected data
type.
Robust program: one that detects and handles
incorrect user entry.

CS001P Programming Fundamentals 1

7/2/2015

35

Symbolic Constant
Symbolic constant: a constant value that is declared
with an identifier using the const keyword

A constants value may not be changed


Example:
const int MAXNUM = 100;

Good programming places statements in appropriate


order

CS001P Programming Fundamentals 1

7/2/2015

36

Symbolic Constant (cont)


Proper placement of statements:
preprocessor directives
int main()
{
symbolic constants
main function declarations
other executable statements
return value

CS001P Programming Fundamentals 1

7/2/2015

37

Resource Link
https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp1_Basi
cs.html

CS001P Programming Fundamentals 1

7/2/2015
38

Potrebbero piacerti anche