Post

[C++] Chap 02 - Flow of Control

[C++] Chap 02 - Flow of Control

Branching Mechanisms

If-else statements

1
2
3
4
if (<boolean_expression>) 
    <yes_statement>
else
    <no_statement>
  • Use brackets for compound statements
  • Logical Operators
    • Logical AND ( && )
    • Logical OR (||)
  • Boolean Expression
    • any nonzero number → true, 0 → false
1
2
bool result = (1<2);
cout<<result<<endl; // 1
  • Short-circuit evaluation
    • Evaluation stops when the result is already decided
1
2
3
4
int x = 0;
int y = 0;
bool result = (x>=1) && (y++); // y++ is not executed
cout<<y;
  • Do not use (x<y<z)!
1
2
3
int x(1), y(2), z(2);
cout<<(x<y<z) <<endl; // 1
cout<<(x<y && y<z) <<endl; // 0
  • Consider
1
2
3
4
5
6
int x(3), y(4), z(5), r(0);
bool result = !x; //0
bool result = (!0*x); // 1
int result = (!0*x); // 3
bool result = (x<5) ||(x/r); //1, short circuit evaluation
bool result = (x&&y) + (!z); // 1. bool 1 + bool 1 = bool 1
  • Precedence of Operators

    Postfix/Prefix → +,-,*,/,→ Comparison Operators → Equal, Not equal → AND OR → Assign

  • x + 1 > 2 || x + 1 < -3
  • Roughly, arithmetic done before comparison & logical
  • +>||
  • evaluating assignment expression is the Rvalue.
1
2
3
4
5
if (x=12)  // (x=12) = 12 -> true
    Do_Something
    
if (12==x) // works same with x==12
if (12=x) //error

Switch statement

  • Uses controlling expression which returns either (Bool, Enu, Integer, Character)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
switch (Controlling_Expression) {
	case Constant_1:
		Statement_seq1
		break;
	case Constant_2:
		Statement_seq2
		break;
	case Constant_3:
	case Constant_4:
		Statement_seq3
		break;
	default:
		Default_Statement_sequence
}
  • Omitting break will continue until it meets new ‘break’ or end of switch statement

Enumeration types

  • List of constants of type int ← Only integer is valid
  • When no values are assigned, consecutive values starting from 0 are assigned.
1
2
3
enum MyEnum { a=17, b, c, d=-3, e};
// is equivalent with
enum MyEnum2 { a=17, b=18, c=19, d=-3, e=-2};

Conditional Operator

  • Also called ternary operator
1
max = (n1 > n2) ? n1 : n2;
  • Shorthand version of if-else

Loop statements

  • While / Do-while / for

Do-while

1
2
3
do {
	Statement
} while (Boolean_Expression); // Don't forget the semicolon!
  • do loop is executed at least once
  • while : checks before the body is executed / do-while : checks after the body is executed
  • Generally diescouraged to use increment/decrement operators in boolean exp. in while
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int n, cnt, one, t;
cin>>n; //enter number of integers to be inputted
t=0;
cnt=1;
while (cnt++<=n) { // Boolean expression executed before executing body
	cin>>one;
	t+=one;
}
cout<<t<<endl; // prints total number of inputted values
cout<<cnt<<endl; // if n==4, cnt is 6.
/*
cnt=4 <=4 passes, then cnt++, cnt=5
cnt=5 <=4 blocked, but cnt++, cnt=6
*/

For loop syntax

1
2
3
4
for (Initialization_Action; Boolean_Expression;Update_Action) // No semicolon
{
	Body
}
  • The third Update Action is optional
1
2
3
4
5
6
7
8
9
10
11
12
13
14
sum=0;
int n;
for (n=1;n<=10;n++)
	sum = sum + n;

for (sum=0, n=1;n<=10;n++)
	sum = sum + n;
for (sum=0, n=1;n<=10;) // Update Action omitted 
{
	sum+=n;
	n++;
}

for (sum=0;n=1;n<=10;sum+=n, n++); //Semicolon needed.
  • Two semicolons are required inside the Expressions.
  • Initialization → {check condition → loop body → update action} → and so on …
  • Common pitfalls : misplaced ;
1
2
for (int cnt = 1;cnt<=10;cnt++);
		cout<<"Hello"; // Nothing happens..
  • Similar issue exists for the while loop

Break and continue statements

  • break : Ends the entire loop
  • continue : Ends the current iteration of the loop body

IOstream

Opening a text file

1
2
3
4
5
6
7
 #include <fstream>
 using namespace std;
 
 ifstream is;
 is.open("filename.txt"); // the file is the same directory as the code
 is>>var1 >> var2; // by spacing. if 1 2, var1=1, var2=2 
 is.close();
  • Reading a string is done UP TO a whitespace character( " ", “\t”, “\n”)
  • When done, close the file with .close();
  • ifstream : input only, ofstream : output only, fstream both I/O

Using a loop to read the text file input

1
2
3
4
5
6
7
string text;
fstream iS;
iS.open("player.txt");
while (iS >> text)  // Performs two actions : Read, check boolean result 
{
	cout<<text<<endl; //not line by line.
}
  • The boolean expression is evaluated to false when there is no data left to read from the file
This post is licensed under CC BY 4.0 by the author.