lec2 Notes: Flow of Control
1 Motivation
- Normally, a program executes statements from first to last. The first statement is executed, then the second, then the third, and so on, until the program reaches its end and terminates.A computer program likely wouldn't very useful if it ran the same sequence of statements every time it was run.
2 Control Structures
- Control structures are portions of program code that contain statements within them and, depending on the circumstances, execute these statements in a certain way. There are typically two kinds: conditions and loops
- Conditionals
In order for a program to change its behavior depending on the input, there must a way to test that input. Conditionals allow the program to check the values of variables and to execute (or not execute) certain statements. C++ has if and switch-case conditional structures - Operators
, >=, <, <=, ==, !=, &&, ||, !
- if, if-else and else if
#include <iostream>
using namespace std;
int main() {
int x = 6;
int y = 2;
if (x > y)
cout << "x is greater than y\n";
else if (y > x)
cout << "y is greater than x\n";
else
cout << "x and y are equal\n";
return 0;
}
- switch-case
#include <iostream>
using namespace std;
int main() {
int x = 6;
switch(x) {
case 1:
cout << "x is 1\n";
break;
case 2:
case 3:
cout << "x is 2 or 3";
break;
default:
cout << "x is not 1, 2, or 3";
}
return 0;
}
- loops
#include <iostream>
using namespace std;
int main() {
int x = 0;
while (x < 10)
x = x + 1;
cout << "x is " << x << "\n";
return 0;
}
do {
statement1
statement2
} while(condition);
#include <iostream>
using namespace std;
int main() {
for (int x = 0; x < 10; x = x + 1)
cout << x << "\n";
return 0;
}
- Nested Control Structures
#include <iostream>
using namespace std;
int main() {
int x = 6;
int y = 0;
if (x > y) {
cout << "x is greater than y\n";
if (x == 6)
cout << "x is equal to 6\n";
else
cout << "x is not equal to 6\n";
} else
cout << "x is not greater than y\n";
return 0;
}
#include <iostream>
using namespace std;
int main() {
for (int x = 0; x < 4; x = x + 1) {
for (int y = 0; y < 4; y = y + 1)
cout << y
cout << "\n";
}
return 0;
}