Program Flow is what you think it is. How the program will flow. As you know the compiler will just go down the code. Program flow is what you use to make it run a certain thing a few times, do something based on a variable, etc... There are some basic comands to program flow. The first two are loops: While and For. When you want something to loop for an amount of times based on a variable, use while. If you know how many times you want something to run, use for. If and else statements are pretty self explanable. Dont be afraid, I will go over all the syntaxes and how to do everything!
The For Loophttp://www.syschat.com Use a for loop when you know how many times you want something to run. For example, we want to have an application that counts from 0 to 50 and count by fives. To do this we would need a for loop. Here is how you do it:
Code you want to run. } Ok, so with our 0-50 program, we would do the following:
for(int x = 0; x < 51; x=x+5){
cout<
If we wanted to count by ones, we would make the last statement x++.
While Loops When you want to have something run multiple times, but you dont know how many, use a while loop. For example, we have a program that will ask if you want to exit and keep running until you type 'y'. Making a while loop is pretty simple:
while(case) { code... }
How to write a case: Most are pretty easy, for example: x>8 However, they can get tricky: her is a list of operators to use:
Eqaul: == And: && Or: || Greater than or equal to: >= Not Equal to: !=
The program that we are going to make checks if the user is writing a 'y'? So the case is going to be: While(exit!='y')
Full Code:
char exit = 'n';
while(exit=='n')
{
cout<<"Do you want to Exit (y/n)?";
cin>>exit;
}
If Statements If you want something to run if something has a certain value, you can use an if statement. To do that, you type: if(case){code;}. If you want something to run that does not fit into that if case, you can use an else statement. To do that, you just write else{ code; } The example I am going to show you will ask someones age and say if they are old enough to drive or not:
int age;
cout<<"Age: ";
cin>>age;
if(age >=16){
cout<<"You are old enough";
}
else{
cout<<"You have "<<16-age<<" More years.";
}
cin>>age;
Go out and make a program! I have thought up a good challenge for you that will use all the topics I have covered on this lesson: Try to make a program that will draw a box based on user input. If the user types more than 60, they have to pick a smaller number. Hint: You can put a for loop inside a for loop, and you are going to need to make the user type x, which is also going to be the y value because it is a square. If you need help, dont be afraid to ask, I can tell you how to do it or a hint if you want
Chris Silop - http://www.syschat.com, Computer Forum