Week 2: Loops, Branches, File Input/Output

 

 

Loops and Relational Expressions

 

Loops are used to do repetitive actions

Branches are used to make decisions

Loops and Branches are quite similar to C, Java, Fortarn, Basic, etc

Special attention will be needed for cin to handles input

 

 

Loop

 

Doing repetitive tasks

In C++, we have

 

 

for Loop Part I

 

In general, we have to do the following:

Setting a value initially

Performing a test to see if the loop should continue

Executing the loop actions

Updating value(s) used for the test

 

Syntax:

for (initialization; test-expression; update-expression)
	... body ...

Example:

// forloop.cpp -- introducing the for loop
#include <iostream.h>
int main(void)
{
	//   initialize; test ; update
	for (int i = 0; i < 5; i++)
		cout << "C++ knows loops.\n";
	cout << "C++ knows when to stop.\n";
	return 0;
}

 

 

for Loop Part II

 

// Mixing with input and outout
// num_test.cpp -- use numeric test in for loop
#include <iostream.h>
int main(void)
{
	cout << "Enter the starting countdown value: ";
	int limit;
	cin >> limit;
	for (int i = limit; i; i--)      // entry-condition test
		cout << "i = " << i << "\n";
	cout << "Done now that i = " << i << "\n";
	return 0;
}
// The output will be 
// Enter the starting countdown value: 4
// i = 4
// i = 3
// i = 2
// i = 1
// Done now that i = 0

 

 

The Increment (++) and Decrement (--) Operators

 

A new addition to C++

There are two version (prefix version ++x, postfix version x++)

Example:

// plus_one.cpp -- the increment operator
#include <iostream.h>
int main(void)
{
	int a = 20;
	int b = 20;

	cout << "a   = " << a << ":   b = " << b << "\n";
	cout << "a++ = " << a++ << ": ++b = " << ++b << "\n";
	cout << "a   = " << a << ":   b = " << b << "\n";
	return 0;
}
// The output will be
// a = 20:      b = 20
// a++ = 20:    ++b = 21
// a = 21:      b = 21

More Example:

int x = 5;
int y = ++x;  // change x, then assign to y
	      // y is 6, x is 6
int z = 5;
int y = z++; // assign to y, then change z
 	     // y is 5, z is 6

 

Combination Assignment Operators

 

Think of it as shorthand for programming

i = i + y; // Can be rewritten as

i += y;

Example:

int k = 5;
k += 3; // Now, k is set to 8

 

Operator Effect (L = Left operand, R = right operand)
+= assigns L + R to L
-= assigns L - R to L
*= assigns L * R to L
/= assigns L / R to L
%= assigns L % R to L

 

Block Statement

 

Can be called compound statement or block statement

for (int i = 1; i <= 5; i++)
{                              // block starts here
	cout << "Value " << i << ": ";
	cin >> number;
	sum += number;
}         

 

Comma

 

It is kind of a trick

Might be wise to stay away from it

j++, i-- // This count as one expression instead of two

int i, j; // One expression as well

 

 

Relational Expression

 

Operator Actual Meaning
< is less than
<= is less than or equal to
== is equal to
> is greater than
>= is greater than or equal to
!= is not equal to

 

Example:

for (x = 20; x > 5; x--) // continue while x is greater than 5

for (x = 1; y != x; x++) // continue while y is not equal to x

for (cin.get(c); c == ' '; cin.get(c)) // continue while c is a space

 

Note:

myint = 4; // Assignment

myint == 4 // Logical cmparsion

 

 

while Loop

 

A for loop stripped off the initialization and update parts. It is more general for application programmers

Syntax:

while (test-condition)
	body

Example:

// A while loop repeats itself until a certain condition
// is met. This loop adds the integers from 1 to ...
// until the sum is greater than 50.
sum = 0;
int m = 1;
while (sum <= 50) 
{
	cout << "Adding " << m << " to the sum." << endl;
	sum += m;
	++m;
}
cout << "The sum is " << sum << endl;

 

 

for vs while

 

for (init-expression; test-expression; update-expression)
{
	statement(s);
}
init-expression;
while (test-expression)
{
	statement(s);
	update-expression;
}
// Counting example
long wait = 0;
while (wait++ < 10000)
	;		// Count silently

 

 

Do while Loop

 

Exit condition loop

Execute at least once

Syntax:

do
	body
while (test-expression);

 

Example:
// dowhile.cpp -- exit-condition loop
#include <iostream.h>
int main(void)
{
	int n;

	cout << "Enter numbers in the range 1-10 to find ";
	cout << "my favorite number\n";
	do
	{
		cin >> n;		// execute body
	} while (n != 7);		// then test
	cout << "Yes, 7 is my favorite.\n" ;
	return 0;
}

 

Loops and Text Input

 

// If the input file look like this
5 ox
// If you open a file with an ifstream object,
// then you can read from it the same way that
// you read from cin.
ifstream inputFile ("week2b.in");

// Read the first number to find out how many
// occurrences we will replace.
int maxReplacements;
inputFile >> maxReplacements;

// Read the "from" and "to" characters that
// specify the replacement.
char fromCh;
char toCh;
inputFile >> fromCh >> toCh;
// Now
fromCh get o
toCh get x

maxReplacements is 5 !

 

Using Unadorned cin for Input

 

Instead of using cin >> ch
We can use cin.get(ch); // this will read the space as a character as well

 

End-of-File (EOF) Condition

 

Two ways of finding out whether we have a EOF or not

while (inputFile.good()) 
{
	....
}
// OR
while (cin.get(ch))	// cin.get(ch) is 0 on EOF
{
	cout << ch;
	count ++;
}

 

Branching Statements and Logical Operators

 

Use to decide whether a particular statement or block is executed or not

Syntax:

if (test-condition)
	statement1
else
	statement2

Example:

// ifelse.cpp -- using the if else statement
#include <iostream.h>
int main(void)
{
	char ch;

	cout << "Type, and I shall repeat.\n";
	while (cin.get(ch))
	{
		 if (ch == '\n')
			cout << ch;     // done if newline
		 else
			cout << ++ch;   // done otherwise
	}
	// try ch + 1 instead of ++ch for interesting effect
	cout << "Please excuse the slight confusion.\n";
	return 0;
}

 

The if-then-else combination

 

// Example 1
if (ch == 'A')
	a_grade++;
else
	if (ch == 'B')
		b_grade++;
	else
		soso++;

// Example 2
if (ch == 'A')
	a_grade++;
else if (ch == 'B')
	b_grade++;
else
	soso++;

 

Logical Expression

 

OR: ||

if (ch == 'y' || ch == 'Y')
{
	// Do something
}
AND: &&
while (i < size && sum >= 100)
{
	// continue the loop
	// etc
}
NOT: !
if (!(x>5))
{
	// do something
}

// It is the same as
if (x <= 5)
{
	// do something
}
// Range test
if ((x > 5) && (x < 10))
{
	// We are in the right range
	// do something
}

 

Switch Statement

 

Go for big if then else statement

switch (integer-expression)
{
	case label1 : statement(s)
	case label2 : statement(s)
	...
	default     : statement(s)
}

 

Demo and Lab

week2a.cpp

week2a.out

week2b.cpp

week2b.in

week2b.out