Hochiminh University of Technology Computer Science and Engineering - [CO1011 - 501127] Fundamentals of Control Structures (part 2) C++ Programming Lecturer: Duc Dung Nguyen Credits: 4 Outcomes ❖ Using array, string, and structured data types ❖ Solve the problem using loop structures ❖ Implement program with loop structures: ❖ while, for, do-while ❖ Understand the role of algorithm in problem solving process 2 Today’s outline ❖ Structured data types ❖ Array ❖ Struct ❖ Basic control structures in C/C++ ❖ Loop statements: while, for, do-while ❖ Structure programming 3 Structured data types Structured data types ❖ Can we implement a program with only basic data types? ❖ What do we need beside basic data types? ❖ A sequence of memory slots that contains a specific data type ❖ A mixture of different data types 5 Structured data types ❖ Array: a sequence of memory slots that contains a specific data type ❖ <data type> <variable name>[<Size>]; ❖ int Fibonacci[MAX_LENGTH];/* declare an integer array of MAX_LENGTH elements. This is a static declaration! */ ❖ <data type> *<variable name>;// alternative declaration, a pointer ❖ float *plotY; 6 Structured data types ❖ Array ❖ int N; cout << “Please input size of the sequence: “; cin >> N; float x[N];// compiler will fire an error here … ❖ int N; cout << “Please input size of the sequence: “; cin >> N; std::vector<float> x(N);// no error, but x is a vector class … 7 Structured data types ❖ Array: initialization ❖ At declaration time (static) ❖ int sNum[5] = {5, 6, 9, 2, 1}; ❖ float x[] = {0.2};// allocated 4 elements ❖ Dynamically allocate ❖ float *pNum; … pNum = new float[N]; 8 Structured data types ❖ Array ❖ Access array elements: ❖ <variable name>[<index>] ❖ int sNum[5]; sNum[0] = 1; sNum[1] = 1; sNum[2] = sNum[0] + sNum[1]; sNum[3] = sNum[1] + sNum[2]; sNum[4] = sNum[2] + sNum[3]; sNum[5] = sNum[3] + sNum[4];// What will happen here? 9 Structured data types ❖ String: ❖ char strName[50];// undefined string ❖ char strName[50] = “Dustin”; ❖ char strOutText[] = “This text contains 32 characters”;//33 bytes ❖ char *pStr = “Unknown”; 10 Structured data types ❖ String: ❖ strlen: length of string ❖ strcpy: copy a string ❖ strcat: concatenate strings ❖ strcmp: compare two strings ❖ strchr: locate the first occurrent of character in a string ❖ strrchr: locate the last occurrent of character in a string 11 Structured data types ❖ String: ❖ string sText;// empty string “” ❖ string sText = “A C++ class that stores characters.max_size, sText.at(index) ❖ sText += anotherText; ❖ sText.push_back, sText.pop_back, sText. 12 Structured data types ❖ Struct: ❖ struct [<struct name>] { <elements>; } [<variables>]; ❖ struct Student { int ID; char name[50];// can you use string? Why should you use? }; struct Student studentList[40]; 13 Structured data types ❖ typedef: define a data type ❖ typedef struct{ char name[30]; } StdName_t; StdName studentList[50]; ❖ typedef struct Student { int ID; char name[50];// can you use string? Why should you use? } Student_t; Student_t studentList; 14 Control structures while statement ❖ Why do we need iterations? ❖ Waiting for something to happen ❖ Operate on several objects ❖ List, array of objects ❖ String 16 while statement ❖ while loop: ❖ Execute a section of code over and over under certain conditions ❖ while (<condition>) <statement>; ❖ while (<condition>) { <statements>; } ❖ E. ❖ Do not forget stopping condition.
❖ Take care of counters. ❖ Use infinite loop wisely. 22 while statement ❖ Nested loop ❖ A loop can be nested inside a loop. ❖ while (<condition 1>) { <statements>; while (<condition 2>) { <statements>; while (<condition 3>); } <statements>; } 23 while statement <exp> N Y statement <exp> N Y statement statement statement 24 while statement ❖ Nested loop ❖ Is used to process multi-dimension arrays ❖ Access customised data ❖ Waiting for inputs ❖ etc.
25 for statement ❖ Why do you need for statement? ❖ Just another way to write iteration/loop structure! ❖ Counting is a frequent activity ❖ for: a specialised loop that package the following tasks in a statement ❖ Initialise a counter variable ❖ Modify the counter ❖ Check complete condition 26 for statement ❖ for loop: ❖ for (<initialization>; <condition>; <modification>) <statement>; ❖ for (<initialization>; <condition>; <modification>) { <statements>; } ❖ E.: ❖ for (i = 0; i < 100; ++i) cout << i << “, “; ❖ for (j = 0; j > -10; --j) cout << j << “, “; 27 for statement ❖ Flowchart initialization <cond.> N modification Y statement statement 28 for statement ❖ Initialization: set value for the counter ❖ Declare one or many counters (same type) and init them at once ❖ Initialize many counters if needed ❖ Condition: a boolean expression that must be evaluated at each loop ❖ Modification: change value of the counter at each loop 29 for statement ❖ Nested loop: #include <iostream> #include <iostream> #include <math.h> int main() { int main() { int img[12][16]; int img[12][16]; int i = 0, j; for (int i = 0; i < 12; i++) { for (; i < 12; i++) { for (int j = 0; j < 16; j++) { for (j = 0; j < 16; j++) { img[i][j] = rand() % 256; img[i][j] = rand() % 256; } } } } return 0; return 0; } } 30 for statement ❖ Breaking the rule ❖ for (<initilization>; <condition>; <modification>) { <statements>; if (<special condition>) break; <statements>; } ❖ for (<initilization>; <condition>; <modification>) { <statements>; if (<special condition>) continue; <statements>; } 31 do-while statement ❖ do-while: do first, check later ❖ A convenient way to perform some operations ❖ E.: ❖ Asking user to input some values ❖ Check if any input value was invalid ❖ Loop to input again 32 do-while statement ❖ do-while loop: ❖ do <statement>; while (<condition>); ❖ do { <statements>; } while (<condition>); ❖ E.: ❖ do { cout << “Please input a positive number” << endl; cin >> i; // should prompt user } while (i < 0); 33 do-while statement ❖ Flowchart statement Y <exp> N statement 34 do-while statement ❖ Breaking the rule ❖ do { <statements>; if (<special condition>) break; <statements>; } while (<condition>); ❖ do { <statements>; if (<special condition>) continue; <statements>; } while (<condition>); 35 do-while statement ❖ Nested loop ❖ do { <statements>; do { <statements>; while (<condition 3>) { <statements>; } } while (<condition 2>); <statements>; } while (<condition 1>); 36 Structure programming Structure programming ❖ Definition: a programming paradigm aimed at improving the clarity, quality and development time of a computer program by making extensive use of subroutines, block structures and for/while loops ❖ Structured programming languages: ALGOL, Pascal, PL/I, Ada, C/C++, etc. 38 Problem solving strategies solution Plan Act method criteria known apply to new situations Define Gather Explore Check Generalize problem information constraints unknown make sense look at the evaluate Disseminate troubleshooting problem from brainstorm against different criteria viewpoint 39 Don Woods & Philip Wankat Structure programming ❖ Loop and array ❖ Loop is good for performing operations on arrays, strings. ❖ “while”, “do-while”, “for” are exchangeable. ❖ Fixed size data should be processed using finite loops.
40 Issues ❖ Infinite loops: ❖ while (100); ❖ while (true) cin >> i; ❖ do { } while (-20); ❖ for (;;); ❖ etc. 41 Issues ❖ Infinite loops: ❖ Sometimes your code is stuck in an infinite loop due to logic errors ❖ Factors: input, user interaction, or special computation ❖ E.* ->* pointer to member 5 * / % arithmetic: scaling 6 + - arithmetic: addition 7 >> << bitwise shift 8 < > <= >= relational 9. == != equality 10 & AND 11 ^ XOR 12 | OR 13 && conjunction 14 || disjunction 15. = *= /= %= += -= >>= <<= &= ^= |= ?: assignment level expressions 16 , sequencing 44 Problem solving - example ❖ Input and draw the following figure in terminal: ❖ Input: N (number of lines) ❖ Output: (in case N = 5) * * * * * * * * * * * * * * * 45 Problem solving - example ❖ Input and draw the following figure in terminal: ❖ Input: N (number of lines) ❖ Output: (in case N = 5) * * ** ** *** *** **** **** ********* 46 Problem solving - example ❖ Input and draw the following figure in terminal: ❖ Input: N (number of lines) ❖ Output: (in case N = 5) * * ** ** * * * * * * * * * * * 47 Problem solving - example ❖ Parse strings ❖ The command line is given as follows: ❖ <program name> [<arguments>] ❖ E.txt -d ❖ Write a program that parse the command line and print list of arguments 48 Problem solving - example ❖ Math: ❖ Print prime numbers from 2 to N (N is the input value) ❖ Print Fibonacci sequence from 3 to N (N is the input value) 49 Summarise ❖ Array, string, and structured data types ❖ Understand loop structures: while, for, do-while ❖ The role of algorithm in problem solving process ❖ Using loop structures on arrays, strings ❖ Implements algorithms with loops 50