Exercise 3. Data Types and Variables. Daniel Bogado Duffner - n.ethz.ch/~bodaniel. Informatik I für D-MAVT

Ähnliche Dokumente
TIn 1: Feedback Laboratories. Lecture 4 Data transfer. Question: What is the IP? Institut für Embedded Systems. Institut für Embedded Systems

Exercise (Part XI) Anastasia Mochalova, Lehrstuhl für ABWL und Wirtschaftsinformatik, Kath. Universität Eichstätt-Ingolstadt 1

Exercise (Part II) Anastasia Mochalova, Lehrstuhl für ABWL und Wirtschaftsinformatik, Kath. Universität Eichstätt-Ingolstadt 1

p^db=`oj===pìééçêíáåñçêã~íáçå=

Getting started with MillPlus IT V530 Winshape

Mul$media im Netz (Online Mul$media) Wintersemester 2014/15. Übung 02 (Nebenfach)

Mitglied der Leibniz-Gemeinschaft

11: Echtzeitbetriebssystem ucos-ii

HIR Method & Tools for Fit Gap analysis

KURZANLEITUNG. Firmware-Upgrade: Wie geht das eigentlich?

ONLINE LICENCE GENERATOR

WTFJS? EnterJS Matthias Reuter

MATLAB driver for Spectrum boards

p^db=`oj===pìééçêíáåñçêã~íáçå=

Ingenics Project Portal

Grundlagen C und C++ Einheit 03: Grundlagen in C++ Lorenz Schauer Lehrstuhl für Mobile und Verteilte Systeme

Franke & Bornberg award AachenMünchener private annuity insurance schemes top grades

Exercise (Part VIII) Anastasia Mochalova, Lehrstuhl für ABWL und Wirtschaftsinformatik, Kath. Universität Eichstätt-Ingolstadt 1

HiOPC Hirschmann Netzmanagement. Anforderungsformular für eine Lizenz. Order form for a license

CABLE TESTER. Manual DN-14003

Programmentwicklung ohne BlueJ

SELF-STUDY DIARY (or Lerntagebuch) GER102

Instruktionen Mozilla Thunderbird Seite 1

ALL1681 Wireless g Powerline Router Quick Installation Guide

Einsatz einer Dokumentenverwaltungslösung zur Optimierung der unternehmensübergreifenden Kommunikation

FAQ - Häufig gestellte Fragen zur PC Software iks AQUASSOFT FAQ Frequently asked questions regarding the software iks AQUASSOFT

Beispiel 2a Die eigenen ersten Schritte mit dem Gnu-Debugger GDB für Remote-Debugging

Der Adapter Z250I / Z270I lässt sich auf folgenden Betriebssystemen installieren:

NEWSLETTER. FileDirector Version 2.5 Novelties. Filing system designer. Filing system in WinClient

Distributed Computing Group

Wählen Sie das MySQL Symbol und erstellen Sie eine Datenbank und einen dazugehörigen User.

Installationshinweise Z501J / Z501K Adapter IrDa USB Installation hints Z501J / Z501K Adapter IrDa USB

ReadMe zur Installation der BRICKware for Windows, Version ReadMe on Installing BRICKware for Windows, Version 6.1.2

There are 10 weeks this summer vacation the weeks beginning: June 23, June 30, July 7, July 14, July 21, Jul 28, Aug 4, Aug 11, Aug 18, Aug 25

Abteilung Internationales CampusCenter

USB Treiber updaten unter Windows 7/Vista

Standardstufe 6: Interkulturelle kommunikative Kompetenz

Invitation - Benutzerhandbuch. User Manual. User Manual. I. Deutsch Produktübersicht Beschreibung... 2

2 German sentence: write your English translation before looking at p. 3

Aber genau deshalb möchte ich Ihre Aufmehrsamkeit darauf lenken und Sie dazu animieren, der Eventualität durch geeignete Gegenmaßnahmen zu begegnen.

Risiko Datensicherheit End-to-End-Verschlüsselung von Anwendungsdaten. Peter Kirchner Microsoft Deutschland GmbH

Listening Comprehension: Talking about language learning

Einführung Datentypen Verzweigung Schleifen Funktionen Dynamische Datenstrukturen. Java Crashkurs. Kim-Manuel Klein

Algorithms for graph visualization

XV1100K(C)/XV1100SK(C)

XV1100K(C)/XV1100SK(C)

Titelbild1 ANSYS. Customer Portal LogIn

XV1100K(C)/XV1100SK(C)

!!! UNBEDINGT BEACHTEN!!!

RailMaster New Version 7.00.p26.01 /

Notice: All mentioned inventors have to sign the Report of Invention (see page 3)!!!

NVR Mobile Viewer for iphone/ipad/ipod Touch

Prediction Market, 28th July 2012 Information and Instructions. Prognosemärkte Lehrstuhl für Betriebswirtschaftslehre insbes.

Symbio system requirements. Version 5.1

1. General information Login Home Current applications... 3

How-To-Do. Hardware Configuration of the CC03 via SIMATIC Manager from Siemens

Beschreibung. Process Description: Sartorius Bestellnummer / Order No.:

How to access licensed products from providers who are already operating productively in. General Information Shibboleth login...

Geometrie und Bedeutung: Kap 5

JobScheduler - Job Execution and Scheduling System Software Open Source

After sales product list After Sales Geräteliste

Einführung in die C++ Programmierung für Ingenieure

Frequently asked Questions for Kaercher Citrix (apps.kaercher.com)

IDS Lizenzierung für IDS und HDR. Primärserver IDS Lizenz HDR Lizenz

KOBIL SecOVID Token III Manual

DOWNLOAD. Englisch in Bewegung. Spiele für den Englischunterricht. Britta Buschmann. Downloadauszug aus dem Originaltitel:

ROOT Tutorial für D. Liko

German Section 33 - Print activities

WAS IST DER KOMPARATIV: = The comparative

Hello world. Sebastian Dyroff. 21. September 2009

USB-Stick (USB-Stick größer 4G. Es ist eine größere Partition notwendig als die eines 4GB Rohlings, der mit NTFS formatiert wurde)

XV1100K(C)/XV1100SK(C)

Lehrstuhl für Allgemeine BWL Strategisches und Internationales Management Prof. Dr. Mike Geppert Carl-Zeiß-Str Jena

Restschmutzanalyse Residual Dirt Analysis

Algorithms & Datastructures Midterm Test 1

Die Datenmanipulationssprache SQL


August Macke Abschied, 1914 Museum Ludwig, Köln

Exercise (Part I) Anastasia Mochalova, Lehrstuhl für ABWL und Wirtschaftsinformatik, Kath. Universität Eichstätt-Ingolstadt 1

Effizienz im Vor-Ort-Service

Klausur Verteilte Systeme

The Single Point Entry Computer for the Dry End

Advanced Availability Transfer Transfer absences from HR to PPM

Employment and Salary Verification in the Internet (PA-PA-US)

Database Management. Prof. Dr. Oliver Günther und Steffan Baron Sommersemester 2002 (I)

Anhang A - Weitere Bibliotheken. Die Bibliothek Mail_02.lib ermöglicht das Versenden von s mit dem Ethernet-Controller

DAT Newsletter Nr. 48 (07/2014)

Customer-specific software for autonomous driving and driver assistance (ADAS)

Nachdem Sie die Datei (z.b. t330usbflashupdate.exe) heruntergeladen haben, führen Sie bitte einen Doppelklick mit der linken Maustaste darauf aus:

Anleitung zur Schnellinstallation TFM-560X YO.13

Installation und Start der Software AQ2sp Installation and Start of the software AQ2sp

E-License - Product Activation E-License - Produktaktivierung

SERVICESÄTZE O&K WARTUNGSSÄTZE. Lieferumfang Im Wartungssatz enthalten sind alle Filter alle Dichtungen alle O-Ringe für die anstehende Wartung.

If you have any issue logging in, please Contact us Haben Sie Probleme bei der Anmeldung, kontaktieren Sie uns bitte 1

USBASIC SAFETY IN NUMBERS

"What's in the news? - or: why Angela Merkel is not significant

FOR ENGLISCH VERSION PLEASE SCROLL FORWARD SOME PAGES. THANK YOU!

Es gibt zwei verschiedene Arten, wie Programme auf dem Rechner ausgeführt werden:

Funktionen Häufig müssen bestimmte Operationen in einem Programm mehrmals ausgeführt werden. Schlechte Lösung: Gute Lösung:

Transkript:

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