Module 3 Assignment and Formatting Introduction to Programming

  • Slides: 43
Download presentation
Module 3: Assignment and Formatting Introduction to Programming Languages

Module 3: Assignment and Formatting Introduction to Programming Languages

Objectives Upon completion of this module, you will be able to: • Know how

Objectives Upon completion of this module, you will be able to: • Know how to use assignment operator • Know how to use increment and decrement operators • Use type casting for data type conversion • Know how to format numbers • Enumerate and define mathematical library functions

Operators> Assignment operator Operators are mainly keywords, operators in C++ are mostly made of

Operators> Assignment operator Operators are mainly keywords, operators in C++ are mostly made of signs. Once you have declared a variable, you can assign a value to it. Assigning values to simple variables like numbers is very easy and requires only the assignment operator ( = ) Assignment (=) The assignment operator assigns a value to a variable. Example: int a; a = 5; 3

Operators Example: int start. Year; double weight; char initial; start. Year = 2006; weight

Operators Example: int start. Year; double weight; char initial; start. Year = 2006; weight = 1. 0196; initial = ‘C’; Assignment operation can be used as the rvalue (or part of an rvalue) for another assignment operation. For example: a = 2 + (b = 5); is equivalent to: b = 5; a = 2 + b; Introduction to Computer Programming

Operators Although you must always declare a variable before assigning a value to it,

Operators Although you must always declare a variable before assigning a value to it, you can perform both acts in one step: Example: int start. Year = 2006; double weight = 1. 0196; char initial = ‘C’; If multiple variables are to be assigned the same value, you can use this shorthand: Example: int v 1, v 2, v 3; v 1 = v 2 = v 3 = 20;

Operators #include <iostream> using namespace std; int main () { int a, b; a

Operators #include <iostream> using namespace std; int main () { int a, b; a = 10; b = 4; a = b; b = 7; cout << "a: "; cout << a; cout << " b: "; cout << b; return 0; } Introduction to Computer Programming

Operators> Combined /compound operators Each of the arithmetic operators can be combined with the

Operators> Combined /compound operators Each of the arithmetic operators can be combined with the assignment operator (combined operator or compound assignation operators) to perform calculations and assign a value in one step: Example: int a = 10; a += 2; // 12, same as a = a + 2; a -= 3; // 9, same as a = a - 3; a *= 2; // 18, same as a = a * 2; a /= 6; // 3, same as a = a / 6; a %= 2; // 1, same as a = a % 2; Introduction to Computer Programming

Operators>Increment and Decrement Operator

Operators>Increment and Decrement Operator

Operators>Increment and Decrement Operator Related to arithmetic are two special operators, referred to as

Operators>Increment and Decrement Operator Related to arithmetic are two special operators, referred to as increment and decrement. Increment increases the value of a number by 1. Decrement decreases the value of a number by 1. To do either, use the name of a variable followed by two plus signs (++) or two minus (--) signs together.

Operators>Increment and Decrement Operator Example: int my. Var = 10; my. Var++; // 11

Operators>Increment and Decrement Operator Example: int my. Var = 10; my. Var++; // 11 my. Var++; // 12 my. Var--; // 11 Increment operator is simply a shorthand version of: my. Var = my. Var + 1 or my. Var += 1; Decrement operator is simply a shorthand version of: my. Var = my. Var – 1 or Introduction to Computer Programming my. Var -= 1;

Operators>Increment and Decrement Operator A characteristic of this operator is that it can be

Operators>Increment and Decrement Operator A characteristic of this operator is that it can be used both as a prefix (++my. Var) or as a suffix (my. Var++). In simple expressions like: ++my. Var or my. Var++ they have exactly the same meaning. Example: int num = 10; ++num; num++; Introduction to Computer Programming

Operators>Increment and Decrement Operator In other operations in which the result of the increase

Operators>Increment and Decrement Operator In other operations in which the result of the increase or decrease operation is evaluated as another expression they have an important difference in their meaning: In case that the increment operator is used as a prefix (++my. Var) the value is increased before the expression is evaluated In case that it is used as a suffix (my. Var++) the value stored in my. Var is increased after being evaluated Introduction to Computer Programming

Operators>Increment and Decrement Operator Example-1 Example-2 B=3; A=++B; A=B++; // A is 4, B

Operators>Increment and Decrement Operator Example-1 Example-2 B=3; A=++B; A=B++; // A is 4, B is 4 // A is 3, B is 4 Introduction to Computer Programming

Program Sample: #include <iostream> using namespace std; int main() { int n 1, n

Program Sample: #include <iostream> using namespace std; int main() { int n 1, n 2; n 1=n 2=1; cout << “At first, n 1 is “ << n 1 << “ and n 2 is “ << n 2 << “n”; n 2 = n 1++; cout << “After n 2=n 1++, n 1 is “ << n 1 << “ and n 2 is “ << n 2 << “n”; n 2 = n 1 --; cout << “After n 2=n 1 --, n 1 is “ << n 1 << “ and n 2 is “ << n 2 << “nn”; n 1=n 2=1; cout << “Now, n 1 is “ << n 1 << “ and n 2 is “ << n 2 << “n”; n 2 = ++n 1; cout << “After n 2= ++n 1, n 1 is “ << n 1 << “ and n 2 is “ << n 2 << “n”; n 2 =-- n 1; cout << “After n 2=--n 1, n 1 is “ << n 1 << “ and n 2 is “ << n 2 << “nn”; cout << “Press Enter to continue. n”; cin. get(); return 0; } Introduction to Computer Programming

Type Casting • Previously, you learned that the value of a variable is stored

Type Casting • Previously, you learned that the value of a variable is stored as a sequence of bits, and the data type of the variable tells the compiler how to translate those bits into meaningful values. Often it is the case that data needs to be converted from one type to another type. This is called type conversion.

Type Casting • Two Kinds of Type Conversion: • 1. ) Implicit conversion also

Type Casting • Two Kinds of Type Conversion: • 1. ) Implicit conversion also called coercion. • 2. ) Explicit conversion also called type casting Introduction to Computer Programming

Implicit conversion • Implicit type conversion is done automatically by the compiler whenever data

Implicit conversion • Implicit type conversion is done automatically by the compiler whenever data from different types is intermixed. When a value from one type is assigned to another type, the compiler implicitly converts the value into a value of the new type. Introduction to Computer Programming

Common examples are when you have multiple types in an expression or calculation or

Common examples are when you have multiple types in an expression or calculation or when assigning data of one type to a variable of another type: Example: int var 1 = 0; float var 2 = 8. 2; var 1 = var 2; // var 1 equals 8 var 2 = var 1; // var 2 equals 8. 00000

When evaluating expressions, the compiler breaks each expression down into individual sub expressions. Typically,

When evaluating expressions, the compiler breaks each expression down into individual sub expressions. Typically, these sub expressions involve a unary or binary operator and some operands. Most binary operators require their operands to be of the same type. If operands of mixed types are used, the compiler will convert one operand to agree with the other.

To do this, it uses a hierarchy of data types: Long double (highest) Double

To do this, it uses a hierarchy of data types: Long double (highest) Double Float Unsigned long int Long int Unsigned int Int (lowest)

Explicit Conversion • Casting represents a request by the programmer to do an explicit

Explicit Conversion • Casting represents a request by the programmer to do an explicit type conversion. • Two ways to forcibly cast a value: • (type) Variable. Or. Value; // C format • Type (variable. Or. Value); // C++ format Introduction to Computer Programming

Explicit Conversion Example-1 int n. Value 1 = 10; int n. Value 2 =

Explicit Conversion Example-1 int n. Value 1 = 10; int n. Value 2 = 4; float f. Value = float(n. Value 1) / n. Value 2; In the above example, we use a float cast to tell the compiler to promote n. Value 1 to a floating point value. Because n. Value 1 is a floating point value, n. Value 2 will then be promoted to a floating point value as well, and the division will be done using floating point division instead of integer division! Introduction to Computer Programming

Explicit Conversion • Example-2: • float my. Var = 12. 594; • cout <<

Explicit Conversion • Example-2: • float my. Var = 12. 594; • cout << int (my. Var); • From the preceding example, type conversion inevitably changes the value of the data in the process. Specifically, it changes the returned value, not the original value, so in the preceding example, 12 is printed, but my. Var is still equal to 12. 594;

Explicit Conversion Program Sample: #include <iostream> using namespace std; int main() { // declare

Explicit Conversion Program Sample: #include <iostream> using namespace std; int main() { // declare the variables to be used int miles = 192; float multiplier = 1. 609344; float kilometers; //calculate the kilometers = miles * multiplier; // Print the results cout << miles << “ miles is approximately “ << int(kilometers + 0. 5) << “ kilometers. n”; cout << “Press enter to continuen”; // let the reader know what to do next cin. get() // wait for the user to press enter return 0; // return the value 0 to indicate no problems }

FORMATTING NUMBERS By default, C++ will print out floating-point numbers using six (6) digits

FORMATTING NUMBERS By default, C++ will print out floating-point numbers using six (6) digits (for example, two to the left of the decimal and four to the right). By using cout, you can adjust this behavior. One option is to use the precision function to establish the maximum number of digits to display:

FORMATTING NUMBERS Example: cout. precision(4); cout << 2. 3459; // 2. 346 cout. precision(3);

FORMATTING NUMBERS Example: cout. precision(4); cout << 2. 3459; // 2. 346 cout. precision(3); cout << 30. 7164; // 30. 7

FORMATTING NUMBERS Program Sample: #include <iostream> using namespce std; int main() { unsigned short

FORMATTING NUMBERS Program Sample: #include <iostream> using namespce std; int main() { unsigned short quantity; float price, taxrate, cost; quantity = 3; price = 19. 95; taxrate = 0. 05; cout << “Widget Cost Calculatorn”; cout << “The cost of purchasing “ << quantity << “widgets(s) at a price of $ “ << price << “, with tax, comes to $ “;

FORMATTING NUMBERS cost = (quantity * price) + ((quantity * price) * taxrate); cout.

FORMATTING NUMBERS cost = (quantity * price) + ((quantity * price) * taxrate); cout. setf(ios: : fixed); cout. setf(ios: : showpoint); cout. precision(2); cout << cost << “n”; cout << “Press Enter to Continue…n”; cin. get(); return 0; }

FORMATTING NUMBERS Along with formatting the precision, you can also dictate how many spaces

FORMATTING NUMBERS Along with formatting the precision, you can also dictate how many spaces are used to print a variable’s value using setw(). Example: setw(5); cout << “-“ << 1 << “-“; The result will be: -_ _ 1 - (with four spaces before the 1). The spaces are known as padding.

FORMATTING NUMBERS To change the default padding, use cout. fill() Example: cout. fill(‘*’); setw(5);

FORMATTING NUMBERS To change the default padding, use cout. fill() Example: cout. fill(‘*’); setw(5); cout << 1. 0; // The result will be **1. 0

MATHEMATICAL LIBRARY FUNCTIONS cmath (math. h) The cmath header file is the Standard C

MATHEMATICAL LIBRARY FUNCTIONS cmath (math. h) The cmath header file is the Standard C library for mathematical operations. Technically, the file being included is called math. h since this is a C file. To include it in C++, you prepend the file name with a lowercase C: #include <cmath>

MATHEMATICAL LIBRARY FUNCTIONS The cmath declares a set of functions to compute common mathematical

MATHEMATICAL LIBRARY FUNCTIONS The cmath declares a set of functions to compute common mathematical operations and transformations. Trigonometric Functions: cos Compute cosine (function) sin Compute sine (function) tan Compute tangent (function) acos Compute arc cosine (function) asin Compute arc sine (function) atan Compute arc tangent (function) atan 2 Compute arc tangent with two parameters (function)

MATHEMATICAL LIBRARY FUNCTIONS Hyperbolic Functions: cosh Compute hyperbolic cosine (function) sinh Compute hyperbolic sine

MATHEMATICAL LIBRARY FUNCTIONS Hyperbolic Functions: cosh Compute hyperbolic cosine (function) sinh Compute hyperbolic sine (function) tanh Compute hyperbolic tangent (function) Power Functions pow Raise to power (function) sqrt Compute square root (function)

MATHEMATICAL LIBRARY FUNCTIONS Exponential and Logarithmic Functions exp Compute exponential function (function) frexp Get

MATHEMATICAL LIBRARY FUNCTIONS Exponential and Logarithmic Functions exp Compute exponential function (function) frexp Get significand exponent (function) ldexp Generate number from significand exponent (function) log Compute natural logarithm (function) log 10 Compute common logarithm (function) modf Break into fractional and integral parts (function)

MATHEMATICAL LIBRARY FUNCTIONS Rounding, Absolute Value and Remainder Functions ceil Round up value (function)

MATHEMATICAL LIBRARY FUNCTIONS Rounding, Absolute Value and Remainder Functions ceil Round up value (function) abs Absolute value (function) fabs Compute absolute value (function) floor Round down value (function) fmod Compute remainder of division (function)

MATHEMATICAL LIBRARY FUNCTIONS Trigonometric Functions – Program Samples /* cos and sin example */

MATHEMATICAL LIBRARY FUNCTIONS Trigonometric Functions – Program Samples /* cos and sin example */ #include <iostream> #include <cmath> #define PI 3. 14159265 using namespace std; Output: The cosine of 60. 000000 degrees is 0. 500000. The sine of 30. 000000 degrees is 0. 500000. int main () { double param, result; param = 60. 0; result = cos (param*PI/180); cout << “The cosine of “ << param << “ degrees is “ << result << “n“; param = 30. 0; result = sin (param*PI/180); cout << The sine of “ << param << “ degress is “ << result << “n”; return 0; }

MATHEMATICAL LIBRARY FUNCTIONS /* tan and acos example */ #include <iostream> #include <cmath> #define

MATHEMATICAL LIBRARY FUNCTIONS /* tan and acos example */ #include <iostream> #include <cmath> #define PI 3. 14159265 using namespace std; Output: The tangent of 45. 000000 degrees is 1. 000000 The arc cosine of 0. 500000 is 60. 000000 degrees int main () { double param, result; param = 45. 0; result = tan (param*PI/180); cout << "The tangent of “ << param << “ degrees is “ << result << “n”; param = 0. 5; result = acos (param) * 180. 0 / PI; cout << "The arc cosine of “ << param << “ degrees is “ << result << “n”; return 0; }

MATHEMATICAL LIBRARY FUNCTIONS /* asin and atan example */ #include <iostream> #include <cmath> #define

MATHEMATICAL LIBRARY FUNCTIONS /* asin and atan example */ #include <iostream> #include <cmath> #define PI 3. 14159265 using namespace std; Output: The arc sine of 0. 500000 is 30. 000000 degrees The arc tangent of 1. 000000 is 45. 000000 degrees int main () { double param, result; param = 0. 5; result = asin (param) * 180. 0 / PI; cout << "The arc sine of “ << param << “ degrees is “ << result << “n”; param = 1. 0; result = atan (param) * 180 / PI; cout << "The arc tangent of “ << param << “ degrees is “ << result << “n”; return 0; }

MATHEMATICAL LIBRARY FUNCTIONS /* atan 2 example */ #include <iostream> #include <cmath> #define PI

MATHEMATICAL LIBRARY FUNCTIONS /* atan 2 example */ #include <iostream> #include <cmath> #define PI 3. 14159265 using namespace std; int main () { double x, y, result; x = -10. 0; y = 10. 0; result = atan 2 (y, x) * 180 / PI; cout << “The arc tangent for (x=“ << x << “ , y=“ << y << “ is “ << result << “n”; return 0; } Output: The arc tangent for (x=-10. 000000, y=10. 000000) is 135. 000000 degrees

MATHEMATICAL LIBRARY FUNCTIONS /* cosh and sinh example */ #include <iostream> #include <cmath> #define

MATHEMATICAL LIBRARY FUNCTIONS /* cosh and sinh example */ #include <iostream> #include <cmath> #define PI 3. 14159265 using namespace std; Output: The hyperbolic cosine of 0. 693147 is 1. 250000 The hyperbolic sine of 0. 693147 is 0. 750000 int main () { double param, result; param = log(2. 0); result = cosh (param); cout << “The hyperbolic cosine of “ << param << “ is “ << result << “n“; param = log(2. 0); result = sinh (param); cout << “The hyperbolic sine of “ << param << “ is “ << result << “n“; return 0; }

MATHEMATICAL LIBRARY FUNCTIONS /* tanh example */ #include <iostream> #include <cmath> #define PI 3.

MATHEMATICAL LIBRARY FUNCTIONS /* tanh example */ #include <iostream> #include <cmath> #define PI 3. 14159265 using namespace std; Output: The hyperbolic tangent of 0. 693147 is 0. 600000 int main () { double param, result; param = log(2. 0); result = tanh (param); cout << “The hyperbolic tangent of “ << param << “ is “ << result << “n“; return 0; }

MATHEMATICAL LIBRARY FUNCTIONS /* exp and frexp example */ #include <iostream> #include <cmath> using

MATHEMATICAL LIBRARY FUNCTIONS /* exp and frexp example */ #include <iostream> #include <cmath> using namespace std; The exponential value of 5. 000000 is 148. 413159 0. 500000 * 2^4 = 8. 000000 int main () { double param, result; int n; param = 5. 0; result = exp (param); cout << “The exponential value of “ << param << “ is “ << result << “n“; param = 8. 0; result = frexp (param , &n); cout << result << “ * 2^ “ << n << “ = “ << param << “n”; return 0; }

End of Module 3

End of Module 3