Exercise 3 Data Types and Variables Daniel Bogado Duffner - bodaniel@student.ethz.ch n.ethz.ch/~bodaniel Informatik I für D-MAVT
Agenda Quiz Feedback Übung 2/Recap Variables Declaration and assignment Naming rules Type conversion Operators and arithmetic operations cin, cout Functions and scopes 2
1. Wie heisst der Befehl der Dateien und Unterverzeichnisse des aktuellen Verzeichnis anzeigt? 2. Wie navigiert man in ein Unterverzeichnis? 3. Wie navigiert man ins Verzeichnis oberhalb? 4. Was macht ein Compiler? Quiz 1. ls 2. cd name 3. cd.. 4. Ein Compiler wandelt eine Programmiersprache über Assembler Code zu Maschinencode um 3
Quiz 1. Welche 2 Befehle sollten zu Beginn fast jedes Programmes stehen? 2. Wie liest man einen Wert über die Konsole ein? 3. Welche Möglichkeiten gibt es für einen Zeilenumbruch bei cout? 4. Was sollte am Ende der main function immer stehen? 1. #include <iostream> und using namespace std; 2. cin >> x; 3. << «\n»; und << endl; 4. return 0; 4
Float zahlen bei Rechnung 9/5 Feedback Übung 2 Wichtig! Immer zuerst speichern, dann kompilieren, dann ausführen! 5
Data Types C++ has 5 built-in basic datatypes: Data type Function Memory* int Saves integer numbers 2 Bytes float Saves real numbers 4 Bytes double bool Saves real numbers with higher precision than float Saves logical values (true/false, or 1/0) 8 Bytes 1 Byte char Saves characters 1 Byte * Memory size may vary depending on the architecture and implementation 6
Char and Bool In C++ werden Characters als Integers abgespeichert Jedem Character wird eine Zahl in ASCII Code zugewiesen 'M' wird beispielsweise als 77 abgelegt -> Somit können arithmetische Operatoren (+,-,*,/,%) angewandt werden 7
Memory is binary: Data Types Large numbers need many bits: Overflow: int i = MAX_INT; i++; 16 bits = 2 Bytes // Highest possible value // Overflow! Lowest negative value! 8
Declaration and Assignment Declaration of a variable <type> <name>; <type> <name> = <number/variable/expr.>; For example: int My_First_Variable; declares an integer variable with the name My_First_Variable. 9
Declaration of a variable <type> <name>; <type> <name> = <number/variable/expr.>; For example: int My_First_Variable; declares an integer variable with the name My_First_Variable. Also possible Declaration and Assignment <type> <name>,<name2>,<name3>; <type> <name>=<name2>= <number/variable/expr.>; 10
Declaration and Assignment More examples: double My_Second_Variable; My_Second_Variable = 5.994; This declares a variable and assigns a value to it one line later. The same thing can also be done like this: double My_Second_Variable = 5.994; thus declaring and assigning in one step. 11
Specify a modifier to the variable type (optional): Specifier long short unsigned const Specifiers <specifier> <type> <name>; Function Variable gets double the memory Variable gets half the memory Variable will not be able to have a sign (only positive values can be stored), thus is able to store a larger range of numbers Variable value cannot be changed Example: unsigned int ui; 12
Deklarierung und Initialisierung Deklarierung: double variable; Initialisierung: variable= 2; Deklarierung und Initialisierung in einem: double variable=3; Welcher Typ ist grösser? 1. float vs int, 2. double vs float 3. bool vs char? 1. float 2. double 3. keines, gleich gross 13
Variable names may only contain Alphabetic characters Numeric digits Underscores (_) Naming Rules 14
The first character cannot be a numeric digit. You cannot use C++ reserved words. main, int, for, Naming Rules Names should not begin with underscores. Uppercase characters are distinct from lowercase characters. number Number NUMBER number 15
Naming Rules Examples int firstname; int Firstname; int leet1337; int 1337leet; int what_a_great_name; int var!; int _thisvar; // Valid // Valid, variable differs from firstname // Valid // Not valid, begins with a number // Valid // Not valid, contains an illegal character // Valid, but shouldn t be used (starts with _) 16
Arithmetic Operations There are 5 types of arithmetic operators: plus (+), minus (-), times (*), divide (/), Modulo (%) Modulo returns the remainder of a division. For example: 5 % 3; // Result is 2, because 3 goes // into 5 once, with a rest of 2 21 % 5; // Result is 1 17
Arithmetic Operations Arithmetic operations are evaluated as follows: Brackets before operators Division, multiplication and Modulo before minus and plus If two arguments have the same precedence level, expression is evaluated left-to-right Für die Unterscheidung einfach die Tabelle in der FS benutzen 18
Arithmetic Operations 19
Examples: Arithmetic Operations 5 * 4 + 1; // 21 5 * (4 + 1); // 25 2 * 3 + 3 * 4 / 2; // 12 9 % 4 + 1; // 2 9 % (4 + 1); // 4 5 * 3 % 4 * 2; // 6 5 * (3 % 4) * 2; // 30 20
Other operators also exist Assignment Operators int x,y; x = y; x *= y; // x = x * y; x /= y; x += y; x -= y; x %= y; y = x++; // y = x; x = x + 1; y = ++x; // x = x + 1; y = x; y = x--; // y = x; x = x 1; y = --x; // x = x - 1; y = x; 21
Discussed next week: Comparisons int x,y; bool a,b; a == b, x == y, a!= b, x!= y x > y, x < y, x >= y, x <= y Discussed next week: Logical operators!a, a && b, a b a b, a & b, a ^ b Operators 22
Type Conversion Consider the following code: float ft_var = 5.453; int it_var = ft_var; The variable it_var cannot save a real number. What happens when this code is executed? The value which will be assigned to it_var will be converted. 23
The assigned value will be converted to the type of the variable to which it is assigned to. In our example Type Conversion float ft_var = 5.453; int it_var = ft_var; this means that the value 5.453 will be converted to an integer. C++ does this by truncating fractional parts (it_var is 5). 24
Type Conversion Assignments: Whenever a numerical value is assigned to a variable of another type, the value will be converted to the type of the receiving variable. 25
Type Conversion Conversion in expression: A second type of the conversion of variables is the conversion in arithmetic expressions, in which several types of variables are included. float 5.453f * 3 * 9.86 int double 26
Rule of thumb: C++ converts into the more general of the two types. Thus in our example: Type Conversion 5.453f(float) * 3(int) * 9.86(double) = 16.359(float) * 9.86(double) = 161.29974(double) 27
Type Conversion A special note: division of int variables. The resulting type is still an integer value. Rational parts of the result will be truncated. 5 / 2 == 2 // The.5 is truncated 1 / 2 == 0 // Same here 28
Type Conversion Even more examples: 13.0f * 4 = 52.0 7.0 * (3 / 7) = 0.0 20 / (10 / 6) = 20 20 / (10.0 / 6) = 12 Float Double Int Double int f=3.5; int x=true; int k=false; short k=23445678 //f=3 //x=1 //k=0 //k=-16210 29
cin & cout cin and cout are your way to talk to the user. With these objects you can print messages to the console. For example: the program Hello, world! But you can also print variables. You can even read in variables! 30
Enable use of cin and cout by: #include <iostream>; using namespace std; Use them with the shift operators (<< and >>): cout << using cout ; // print to screen int i; cin >> i; cin & cout // reading 31
cout Order is important: cout << using cout ; // valid cout >> using cout ; // invalid using cout >> cout; // invalid Concatenation is valid: cout << pri << nting ; // valid 32
Use of variables and numbers is also valid: cout << var: << i << num: << 3; Note the difference: cout << i ; cout << i; cout 33
New line: cout << line1\nline2 ; cout << line1 ; cout << line2 ; cout cout << line1 << \n ; cout << line2 ; // 2 lines // just 1 line! // ok cout << line1 << endl << line2 ; 34
cin Usage: int i; cin >> i; Can also concatenate: int a,b; cin >> a >> b: 35
Converts to relevant types: int a; cin >> a; cin // waits for user input; if // user inputs a string, then // a = 0 36
cin Parses by spaces and new line, but waits for new line: int a,b,c; cin >> a; cin >> b; cin >> c; // waits for user input; if user // input is 65 73 and Enter, // then a = 65; // b = 73 without waiting // waits for user input again 37
Structure of a Function return type function name argument type argument int main ( int argc, char* argv[] ) { cout << Hello, World! << endl; return 0; } return value argument list function body 38
Structure of a Function function name: name of the function function body: statements to be executed argument: variable whose value is passed into the function body from the outside argument type: type of the argument return value: value that is passed to the outside after function call return type: type of the return value (void if there is no return value) 39
Advantages: readability Functions int main() { cout << Please enter two integers: "; int a,b; cin >> a >> b; int res = (a + b) * (a + b); cout << The result is: " << res << endl; return 0; } 40
Functions: Readability int square_of_sum(int i1, int i2) { int r = i1 + i2; return r*r; } int main() { cout << Please enter two integers: "; int a,b; cin >> a >> b; int res = square_of_sum(a,b); cout << The result is: " << res << endl; return 0; } 41
Functions: Code re-use int square_of_sum(int i1, int i2) { int r = i1 + i2; return r*r; } int main() { cout << Please enter four integers: "; int a,b,c,d; cin >> a >> b >> c >> d; int res1 = square_of_sum(a,b); int res2 = square_of_sum(c,d); cout << the results are: " << res1 <<, << res2 << endl; return 0; } 42
Functions: Arguments, Return Values int square_of_sum(int i1, int i2) res1 = square_of_sum( a, b); Arguments and return values are both optional void print_message() { cout << This is also a function! << endl; } 43
Functions: Arguments, Return Values int square_of_sum(int i1, int i2) res1 = square_of_sum( a, b); Invocation of a function must have () print_message(); Declaration must be before invocation 44
Scope is the validity/visibility of a variable int nonsense(int input) { return input * x; } int main() { int x = 3; if (x == 3) { int y = 15; } int z = nonsense(y); cout << z << endl; return 0; } Scope 45
int nonsense(int input) { return input * x; } int main() { int x = 3; if (x == 3) { int y = 15; } Scope x is not visible here; only visible inside «main» function y is not valid outside { }; we cannot use y as an argument for function «nonsense». } int z = nonsense(y); cout << z << endl; return 0; Scope of x 46
Practice data types and type conversions Practice function calls and scopes Write a small program with a function call (means) Hand in: Exercise 3 Solutions to questions 1, 3, 4 Source code for means program Aufgabe 1,3 und 4 kommen so oder sehr ähnlich garantiert in der Prüfung! 47
Ist die Zuweisung erlaubt und wenn ja welchen Wert ergibt es? Beispiel: double d; Zeile xy: float f=d Exercise 3.1 Lösung: (a) double --> float: Bits werden abgeschnitten. Ergibt falsche Werte für grosse Zahlen! 48
Aufgabe 3.2 Exercise 3.2 und 3.3 UNIX «man» und «hilfe» Funktion verwenden und kennenlernen in Terminal Aufgabe 3.3 Typenumwandlung Welchen Wert haben die Variablen nach 4 Zeilen Befehle Was wird am Ende über cout ausgegeben? 49
Exercise 3.4 und 3.5 Aufgabe 3.4 Wie funktioniert eine Funktion und welcher Wert wird zurückgegeben? In welchem Bereich sind Variablen gültig und sichtbar/bekannt Aufgabe 3.5 Schreibt eine Funktion, welche den Durschnitt ausrechnet Nicht innerhalb von main, sondern eigene Funktion erstellen Syntax siehe Übungsslides 50