Download presentation
Presentation is loading. Please wait.
1
Exercise 6 – Compound Types und Kontrollfluss
Informatik I / D-ITET Informatik I / D-ITET Exercise 6 – Compound Types und Kontrollfluss 1
2
Agenda Structures Unions Enumerations Loops (for, while, do while)
3
Structures Structures are user-defined Types Variable declaration:
Type definition: Variable declaration: Accessing member variables: struct MyNewDataType { member_type1 member1; member_type2 member2; }; MyNewDataType myNewDataObject; myNewDataObject.member1 = ...;
4
Structures Definition Initialization Assignment
struct MyStruct{ int i; float f; }; MyStruct m1; MyStruct m2 = {1, 2.0f}; m1 = m2; // m1.i = m2.i; m1.f = m2.f;
5
Structures Nesting Type of member variables can be arbitrary
Self-defined types can also be used Example: No recursive nesting (no Date struct inside another Date)! Recursive data structures later in course struct Date{ int day; int month; int year; }; struct Person { Date birthday; string name; int age; };
6
Unions Definition Initialization
If they don‘t have the same size, the union takes the size of the biggest element Values of the union array after initialization: union MyUnion{ char c[4]; // On the same memory int i; // On the same memory }; c[3] c[2] c[1] c[0] MyUnion u1; u1.i = 1; I = 0x c[0] == 1, c[1] == 0, c[2] == 0, c[3] == 0
7
Enumerations Definition Assignment is limited:
enum Months{January, February, March}; enum Months{January = 1, February, March}; enum Months{January = 1, June = 6, March = 3}; int a = February; Months a = 2; // ERROR
8
Loops - Overview for loops while loops do – while loops
9
for Loop Declare and initialize loop variable:
Check continue condition BEFORE: Increment AFTER loop int i=0; i < 4; i++ for (int i=0; i < 4; i++) { cout << “i is: “ << i; } Sidenote: Shown here is the C99 standard. Older C-code might require this: int i; for (i=0; i < 4; i++)
10
while Loop Declare and initialize loop variable:
Check continue condition BEFORE: Increment AFTER loop int i=0; i < 4; i++ int i=0; while (i < 4) { cout << “i is: “ << i; i++; }
11
For and While Comparison
int i; for (i=0; i < 4; i++) { cout << “i is: “ << i; } For and while can be used equivalently Loop variable i stays valid after the loop if declared outside of braces For loops for known length iteration While loops to loop until complex condition is met int i=0; while (i < 4) { cout << “i is: “ << i; i++; }
12
do while Loop Declare and initialize loop variable:
Check continue condition AFTER: Increment AFTER loop int i=0; i < 4; i++ int i=0; do { cout << “i is: “ << i; i++; } while (i < 4);
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.