Download presentation
Presentation is loading. Please wait.
1
CS 1400 Chapter 3: sections 2 - 5
2
Variable initialization Variables may be initialized when declared –Form; type name = initial_value; –Example: int sum = 0; float interest_rate = 0.56;
3
Type conversions Rankings: –long double(highest) –double –float –unsigned long –long –unsigned int –int –short(lowest)
4
Rules Rule #1 –char, short, unsigned short are all considered as int Rule #2 –When a mixed-type arithmetic operation is encountered, the lower ranked value is promoted to the higher ranking value. Rule #3 –When a value is assigned to a variable, it is converted to that variable type.
5
Overflow / Underflow Assigning a too large or too small value to a variable results in incorrect values. An error message may not be generated!
6
Assignment Statements Assignment statements evaluate a math expression and assign the value to a variable form: variable = expression ; Examples; cost = hours * rate; sale = amount * taxrate – discount; age = 21;
7
Math library functions The math library is a selection of useful pre- written functions that can be automatically included into your program Example – the exponent or power function; #include int main() {int temp; temp = 5; answer = pow(temp, 2); cout << answer;// outputs 5 2 or 25
8
Examples… AlgebraC++ z = 4xyz = 4*x*y; a = 3x + 2 4y - 1 a = (3*x+2) / (4*y-1); c = (a)(b)c = a * b; t = x 5 t = x*x*x*x*x; or t = pow(x,5); c = a 2 + b 2 c = a*a + b*b;
9
Mathematical expressions… operators are evaluated by precedence parentheses can be used for grouping to explicitly state precedence all operations must be expressed – there are no implied operators
10
Manual type conversions… Type casting allows you to manually force a value to be converted to a type –Form: static_cast (value ) –Example: int sum, count; float average; cin >> sum >> count; average = static_cast (sum) / count; cout >> “average is: “ << average << endl;
11
Side note… There is an older form of type casting average = float (sum) / count; has the same meaning as average = static_cast (sum) / count;
12
Review… int a, b; float x, y; … b = 5 / a + 2 * x; y = x / 2 + 5 * a; if a and x are… then b and c will be… 2, 3.5 7, 10.2 10, 0.5
13
Examples… Write a program to convert a change amount into coins. Write a program to calculate the average age of 5 students, rounded to the nearest whole number. Write a program to provide the third side of a right triangle.
14
Summary Topics covered –variable initialization –type conversion rules –overflow and underflow –math library –math expressions –type casting
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.