Saturday, March 14, 2009

Lesson 3: Program flow

Many a time, programs would have to make certain decisions. We might want to control how our program runs. This is where program flow comes in.

Controlling program flow can come in the following or both: loops and decision-making statements. The following illustrates this point:

If-Else statements
This is a very simple decision making programming tool. It evaluates a statement. Evaluative statements come in the form of:


A [operator] B


Operators can be one of below:
== //equal to
>= //more than or equal to
<= //less than or equal to
!= //not equal to


To evaluate more than 2 statements, use the && (meaning AND) and || (meaning OR). The basic structure of an if-else decision is:


if([evaluative statement 1]) {
//do a;
} else if ([evaluative statement 2] {
//do b;
}


else {
//do c;
}


Of course, you can omit the else and else if in certain cases which you might not need to use them. Also, if your decision making statements are only one-liners, you can omit the curly braces as well.


For loops:

As its name suggests, it would do the same statements in the brackets (scope) until the condition is satisfied. For loops are good for iterating through arrays. It is written this way:


for ([initial variable value]; [evaluative statement]; [do something to variable if satisfied]) {

}




While loops:

Something like for loops, but only runs when that condition is satisfied.


while(evaluative statement) {

}


To make an infinite while loop, use “while(1) { … }”. While loops can be for loops as well:


int i = 0;
while(i < 5) {


i++;
}


However as you can see, this is not done usually as it is not very elegant.

Example:
Write a program that evaluates the type of roots from a polynomial of maximum base 2 with discriminant d = (b^2) – 4ac, of polynomial a x^2 + b x + c. d > 1 for real distinct roots, d = 0 for single real roots and d > 0 for no real roots.



#include <iostream>
using namespace std;

int main() {
int a,b,c,d
while(1) { //continue until break
cout << "Enter coefficient of x^2: "; cin >> a;
cout << "Enter coefficient of x^1: "; cin >> b;
cout << "Enter coefficient of x^0: "; cin >> c;
d = b * b - 4 * a * c;
if (d > 1) cout << "REAL DISTINCT ROOTS";
else if (d == 0) cout << "REAL SINGLE ROOT";
else cout << "NO REAL ROOTS";
}
return 0;
}



Program is self-explanatory; gives you a better picture of how to use loops and conditions.

No comments:

Post a Comment