Chapter 3: Loops and Conditionals
Introduction Section 3.1
So far all the programs that we've written have gone in a straight line. By that, I mean that each and every program has had a preselected path that it went through once, and that was it. After that the program would end. These types of programs are rare in real life applications. Most programs have to do one thing if the user acts one way, and do another thing if the user were to act a different way. Also, many times a program has to do a certain command, or a group of commands multiple times. You could write the statements over and over again, but this can get rather tedious, and after a while you would get fed up of doing so. In this chapter I will show you how to tell the computer to make a choice based on a variable, and how to tell the computer to run a set of statements multiple times in a not-so tedious manner.
Loops Section 3.2
There are three types of loops I will show you: the for loop, while loop, and do loop, but before you can use these you must know what they are.
A loop executes a set of commands multiple times. The general contents of a loop are a set of statements, a test variable or control variable, a condition, and usually an increment or decrement. The test variable holds a value which is tested against the condition. As long as the condition is met, the loop will continue executing the statements within. Generally, after all the statements in the loop are executed, the test variable is either incremented or decremented, and is tested against the condition again. Once the condition is not met, the loop is exited, and the computer will then go on with the rest of the program. This might presently seem complex to you, but once I show you how it works it will become a lot easier to understand.
The format of a loop is as follows (this is not actual code):
PHP Code:
nameOfLoop(condition)
{
statement 1;
statement 2;
statement 3;
statement 4;
.......
increment;
}
It's a simple concept.
Now, you might be wondering how the condition is tested. The condition is tested using a relational operator. There are 6 relational operators that you need to know:
> greater than
< less than
>= greater than or equal to
<= less than or equal to
== equal to
!= not equal to
The "greater than" operator, and "less than" operator, are just as you would see and use them in basic algebra. The "greater than or equal to" operator, and "less than or equal to operator", look slightly different than what you would see in basic algebra, but have the same concept. The "equal to" operator can get slightly confusing. Many times, a new programmer will confuse it with a single equal sign, or assignment operator. A single equal sign is used to assign a value to a variable, and the double equal signs are used for comparisons. The not equal to sign is pretty self explanatory. I will give you examples of how to use these in the next section when we actually use real loops.
The other thing you need to know about is the increment. An increment looks something like this:
All that means is that the value of one is being added to the previous value of x. So, if x was 10 before, after that statement executes, it would be 11. You could decrement the same way, all you would need to do would be to substitute the minus sign in place of the plus sign. If you really wanted, a multiplication symbol, or division symbol could also be placed there, although I can't really thing of any real uses for those. You could also increment or decrement by any number, not just one.
There is a shorthand for increments and decrements.
PHP Code:
x+=1; // same thing as x=x+1
x-=1; // same thing as x=x-1
Again, you could use any number for increments. x+=3 would be perfectly alright.
There is another shorthand, but this only works if you want to increment or decrement by one.
PHP Code:
x++; // increments x by 1
x--; // decrements x by 1
++x; // increments x by 1
--x; // decrements x by 1
Remember, that this only works if you want to increment or decrement by one. x+++ will not increment by 2, and your compiler would most likely give you a syntax error if you tried that. There is a slight difference between x++ and ++x, but I will cover that when I am covering for loops.
While loop Section 3.3
The first loop you will learn is the while loop. It looks something like this (not actual code):
PHP Code:
while(condition)
{
statement 1;
statement 2;
.....
increment;
}
The first part of the loop is the keyword while. This is the start of the while loop. The condition, enclosed in parenthesis, follows the while keyword. Remember, this uses one of the relational operators. Afterwords, there is an opening curly brace, followed by a set of statements that the programmer wants the program to execute. After that, the test variable is incremented. Here is a real program that prints the numbers 1-10, going to the next line after every number, using a while loop.
PHP Code:
#include <stdio.h>
int main(void)
{
int controlVariable = 1; // declares the test variable and sets it's value to 0
while(controlVariable <= 10) // as long as control variable is less than or equal to 10
{
printf("%d\n", controlVariable); // prints value of control variable
controlVariable++; // increments control variable by one
} // ends while loop
return 0;
}
An easy program, right? It starts off by including any header files required for the program like we have been doing for every program, and then starts main.
Within main, we declare the control variable, calling it "controlVariable", and initialize it with the value of one, since we want to print the numbers one through ten. On a side-note, the control variable doesn't have to be called "controlVariable'. I called it that hear for clarity. In reality, it can be called anything that any other variable could be called.
The next line declares that a while loop will proceed as long as the condition in the parenthesis is met. In this case, the condition that needs to be met for the loop to start is that control variable must be less than or equal to 10. If that condition is met, then the statements inside the curly braces will then be executed. In this case, it prints out the value of controlVariable, and then increments controlVariable by one.
You must remember to increment or decrement your control variable or you will be stuck in an infinite loop, which is a loop which goes on forever. Another thing to remember is you can put the increment anywhere you want in the loop. It doesn't necessarily have to be at the end of the loop.
After the increment, it tests controlVariable against the condition again. This process occurs over and over until the condition is not met, in which case the loop is exited, and the rest of the program goes on. Once the loop has exited, the value of controlVariable is 10, not 1 like it was originally.
For loop Section 3.4
The for loop is syntactically different from the while loop, but it will get the job accomplished just as well as a while loop, and is in fact the loop that I use most in my code. Its general format is (not actual code):
PHP Code:
for(control variable; condition; increment)
{
statement 1;
statement 2;
..........
}
This loop starts with the keyword for, and is followed by parenthesis. Now, what goes inside the parenthesis is where this loop gets slightly tricky. There are three things that must go inside the parenthesis, instead of just one as was the case in the while loop. Every single element that is placed inside the parenthesis is separated by a semicolon. The first element in there is the control variable. The control variable isn't declared, or initialized here, but you must put its name there, and you can assign it a value if you want. Next is the condition, which is no different from the condition in the while loop. The last element with the parenthesis is the increment. Once that is done, you don't have to worry about incrementing after all the statements in the loop. Only thing to do after the increment is put the statements which you want looped, encapsulated in curly braces.
Here is the same program we wrote for the while loop, except using a for loop:
PHP Code:
#include <stdio.h>
int main(void)
{
int controlVariable=1; // declares the control variable
for(controlVariable;controlVariable<=10;controlVariable++) // take note of the setup
{
printf("%d\n", controlVariable); // prints number
}
return 0;
}
I'm going to rewrite this program so that the value of controlVariable is assigned within the parenthesis themselves, for demonstration purposes.
PHP Code:
#include <stdio.h>
int main(void)
{
int controlVariable;
for(controlVariable=1;controlVariable<=10;controlVariable++) // notice the subtle change
{
printf("%d\n", controlVariable);
}
return 0;
}
Similar to the first program, the control variable is declared outside the loop. You have to remember, the first thing that goes in the parenthesis is the name of the control variable. Optionally, you can add a value along with it, as I have demonstrated in the second program, but it is not essential to the loop. It is always a good idea to give your control variable a starting value no matter which loop you are using, because if you do not, then the control variable could start with just about any value possible, the reason being that if a variable is not assigned a value, then it just uses the value already in memory from a program that has been previously run.
The next part in parenthesis, the condition, is just about identical to what it would be in the while loop. Remember to separate your control variable and your condition with a semicolon. The same applies for you condition and increment.
The increment is a little funny in this loop. Recall how I earlier told you that there is a slight difference between ++x, and x++. That difference comes in hear. If you were to use x++, then the loop would run through all statements and then increment the control variable, but if you were to say ++x, it would increment the variable before it ran all the statements.
The loop runs similar to the while loop. It tests the condition, and then, depending on how you have decided to increment your control variable, it either increments the control variable and then executes all the statements, or it executes all the statements first, and then increments the control variable. If we were to say ++controlVariable instead of controlVariable++, then this program would output the number two through eleven, and not one through ten.
Do loop Section 3.5
The final loop I will tell you about is the do loop. This loop deviates from the others, because the condition is tested at the end of this loop. This means that this loop will always be executed at least once. Here is it's general format:
PHP Code:
do
{
statement 1;
statement 2;
.....
increment;
} while(condition);
The do keyword starts it off, followed by a curly brace. Inside the curly braces, you put all the statements you want to, and then increment. Again, remember to increment, or your program will be stuck in an infinite loop. After incrementing, you follow with your closing curly brace. Directly following that, you have the condition just as you would for a while loop, except that this time the expression is followed by a semicolon; something that none of the other loops are followed by. Remember, the condition is tested at the end of this loop.
We'll use the same program again as an example.
PHP Code:
#include <stdio.h>
int main(void)
{
int controlVariable=1;
do
{
printf("%d\n", controlVariable);
controlVariable++;
} while(controlVariable<=10);
}
Easy. The control variable is declared outside the loop and is given a value. Then you initiate the loop with the do keyword. Inside the curly braces we have our
printf() statement, and our increment. After that, we have the condition, which is just like the writing a while loop, except with a semicolon to end it.
Just to clarify, the process that this loop takes is it runs through all the statements and increment, and then tests. So, on its first pass through the loop, it prints out one to the command line, and then increments controlVariable to two. When the test is performed, it tests whether two is less than or equal to 10.
Conditionals Section 3.6
What if you wanted the program to perform a certain set of statements if one condition were met, and a completely different set of statements if a different condition was met? Do to this, you use conditionals. In the following sections, I will attempt to familiarize you with the if/else and the switch. You will see conditionals in just about any real world program.
If Section 3.7
The if statement is more flexible, and in my opinion, more convenient to use out of the two conditionals that I will be showing you. It works by testing a variable against a condition, much the same way as the loops you learned about earlier in the chapter. It uses the same relational operators, in a similar format. One thing you should know about values produced by relational operations is that anything that is true returns as 1, and anything false return 0. The if statement's general format is as follows:
PHP Code:
if(condition)
{
statement 1;
statement 2;
...
}
I will write a simple program which demonstrates the use of an if statement. All it does is say, "you picked one," if the user inputs the number one, and nothing if the user doesn't enter number 1.
PHP Code:
#include <stdio.h>
int main(void)
{
int x;
printf("please enter a number\n");
scanf("%d", &x);
if(x==1)
{
printf("you picked one");
}
return 0;
}
The program above is another simple program. It declares a variable, x, and then prompts the user for a numerical value. Once the number is entered, it is tested. The condition to pass the test is that x must equal one. If x equals one, then the program outputs, "you picked one," and if it doesn't, it simply exits.
You can add as many if statements as you want in a program. Not only that, but you can add as many if statements as you want for one variable. I will rewrite the program above to where it prints, "you picked one," if one was entered at the keyboard, and "you picked two" if two was entered at the keyboard.
PHP Code:
#include <stdio.h>
int main(void)
{
int x;
printf(please enter a number\n");
scanf("%d", &x);
if(x==1)
{
printf("you picked one");
}
if(x==2)
{
printf("you picked two");
}
return 0;
}
Exact same code as the first program, the only thing added was the test for if x equals two, and the statement that needs to be performed if that condition is met. The way the program would run is, it would ask for input, and then first test against one. If that condition is met it will print, "you picked one." Then, regardless of whether the above statement was met or not, it would perform the second test. If that condition is met, then it will print, "you picked two." This is not the most efficient way to do this, though, and as programmers, we want to do everything as efficiently as possible. I will show you another way to do this in the next section.
Before I continue to teach you more about the if statement, I must teach you about logical operators, which can help relational operators. Here are the logical operators:
&& and
! not
|| or
If you use the and operator, then condition one, and condition two must be met for the entire condition to be true. If you use the or operator, then only one condition has to be met for the entire condition to be true.
Remember learning about order of operations in junior high? Well, it's back. Logical and relational operators also have an order of operation. Keep in mind, that just like arithmetic, you can explicitly override the order by using parenthesis. I have listed the order of operations from highest to lowest:
not
greater than, greater than or equal to, less than, less than or equal to
equal to, not equal to
and
or
The not operator is slightly hard to explain, so I will demonstrate how it is used in a few moments, and attempt to explain it from there. First, an example of the and operator. I will rewrite our program above, so if the user enters 1, then the program outputs, "you picked one," if the user enters two, the program will output "you picked two," and if the user enters any other number, the program will output "you picked a number other than one or two."
PHP Code:
#include <stdio.h>
int main(void)
{
int x;
printf("please enter a number\n");
scanf("%d", &x);
if(x==1)
{
printf("you picked one");
}
if(x==2)
{
printf("you picked two");
}
if(x!=1 && x!=2) // implementation of the and operator
{
printf("You picked a number other than one or two.");
}
return 0;
}
The program runs just as expected. Tests for x equaling one, and then two. Then it reaches the last if statement. Here, it tests if x is not equal to one, and if x is not equal to two. If both of these statements are true, then the program proceeds to execute the
printf() statement.
Now for the not operator. The last if statement in the previous program could be rewritten as:
PHP Code:
if(!(x==1 || x==2)
{
printf("you picked a number other than one or two.");
}
This does the same thing. Just read it from the inside to the outside. This statement is true if x is not equal to one or two.
else Section 3.8
The else statement really has two forms: else, and else-if. The else statement really expands the if statement. It cannot be used unless an if statement has just been used.
First we'll cover the else-if statement. Instead of using multiple if statements, like we did above, we could simply use an else if statement. The else-if statement is used if the programmer wants to test additional conditions after the initial one, which is in the original if statement, has been tested. Here is the general format:
PHP Code:
if(condition 1)
{
statement 1;
statement 2;
...
}
else if(condition 2)
{
statement 1;
statement 2;
...
}
else if(condition 3)
{
statement 1;
statement 2;
...
}
else if(condition 4)
{
statement 1;
statement 2;
...
}
Remember, you can have a lot more than four else-if statements in a set if you want. You can put as many else-if statements as you want in a set.
Now, doing it this way is a lot more efficient than doing it by only if statements. Lets say, for example, that the second statement is true. Once it reaches this statement, the program will not test condition 3, and condition 4. It will just skip those conditions and continue with the rest of the code. Were these all if statements, each condition would have to be tested before normal execution of the program would ensue.
Lets take the program we wrote before for the if statements, and properly change the if statements into if-else statements.
PHP Code:
#include <stdio.h>
int main(void)
{
int x;
printf("please enter a number");
scanf("%d", &x);
if(x==1)
{
printf("you picked one");
}
else if(x==2)
{
printf("you picked two");
}
else if(!(x==1 || x==2))
{
printf("you picked a number other than one or two");
}
return 0;
}
The only change in this program was that an else was added in front of the second and third if statements. This subtle change in code with give the program the same output in a slightly more efficient manner. I reiterate the fact, as a programmer, you want your code to be efficient.
Now, if the else statement stands alone, it is used as a last resort. If none of the conditions in the ifs or if-elses are met, then the statements that are associated with the else statement are executed. So, the general format would look something like this:
PHP Code:
if(condition 1)
{
statement 1;
statement 2;
}
else if(condition 2)
{
statement 1;
statement 2;
}
else if(condition 3)
{
statement 1;
statement 2;
}
else
{
statement 1;
statement 2;
}
So, once again, if were rewriting the program in the above example, it would look like this:
PHP Code:
#include <stdio.h>
int main(void)
{
int x;
printf("please enter a number");
scanf("%d", &x);
if(x==1)
{
printf("you picked one");
}
else if(x==2)
{
printf("you picked two");
}
else
{
printf("you picked a number other than one or two");
}
return 0;
}
In this program, the final else-if statement was replaced with an else statement. Remember the way we had set up the last else-if statement? We had set it up so that if none of the other conditions were true, then the final else-if statement would be, and it would execute. Substituting that with the else statement does the exact same thing.
Switch Section 3.9
The switch statement is another conditional. It can only test integers and characters, and it can only test for equality. Its syntax is slightly different than what you saw for the if statement. The switch statement doesn't use any of the relational operators, since it can only test equality. Its general format is like this:
PHP Code:
switch(variable-to-be-tested)
{
case value1:
statement 1;
statement 2;
break;
case value2:
statement 1;
statement 2;
break;
case value3:
statement 1;
statement 2;
break;
default:
statement 1;
statement 2;
}
ou start out with the switch keyword, and put the variable you want tested in parenthesis. That's it. You don't put a condition in the parenthesis, only a variable, which is slightly different than what we've been doing so far.
hen, you type the keyword case, followed by a value. This value is what the variable will be tested against. If the value that is by the case keyword matches the value in the variable, then all the statements in that are below that case are performed. Remember, that only integers and characters can be tested. If you test characters, you must enclose the value that you are testing against (the value next to the case) in single quotes.
The default, which is below the third case statement, executes if none of the values next to the cases matches the value held by the variable that you are testing. A default is not mandatory. If you choose to not use a default, and no match is found with the values that are associated with the cases, then nothing happens in the switch statement, and the execution of the program continues as normal.
Now, in this program you are presented with a new statement, the break. It has many uses, but here, it is used to signal the end of a particular case. This is mandatory, otherwise your program will be buggy. Once a match between the value a variable holds, and the value next to a case, then it executes all statements inside that case until a break is found. If a break is not found it goes on to the next case, and proceeds to execute its statements. It keeps going in this manner until a break statement is found. A break is not required under default.
Now, as usual, for an example. Lets use the same program we have been using for conditionals so far, and change it to where it uses the switch statement, instead of the if-else statements.
PHP Code:
#include <stdio.h>
int main(void)
{
int x;
printf("please enter a numbe");
scanf("%d", &x);
switch(x)
case 1:
printf("you picked one");
break;
case 2:
printf("you picked two");
break;
default:
printf("you picked a number other than one or two.");
}
return 0;
}
After asking you for a number, this program uses the switch statement. Since the variable we are testing is x, that goes inside the parenthesis. First we test if x is equal to one, so the number one is placed next to the case. If that is true, then the statements inside the first case are executed, and the break signals to exit the switch statement. If not, then you test against the second case. If that is true, then all the statements associated with the second case are executed, and then the break signals to exit the switch statement. If neither of those conditions match the value in x, then the statement inside default executes, and the program then continues as it is supposed to.
Nested Loops/if statements section 3.10
Loops and if statements can be part of a separate loop, or if statement. These are called nested loops, or nested if statements.
First thing you need to know is that loops can be within if statements, and if statements can be inside loops, and the program would run just as you would expect. It would be no different than placing a set of statements inside the loop, or if statement. Here is an example of a loop within an if statement:
PHP Code:
#include <stdio.h>
int main(void)
{
int x;
scanf("%d", &x);
if(x<5) // if this condition is met, then the loop will take place
{
int i;
for(i=0;i<10;i++)
{
printf("%d\n", i);
}
}
else
{
printf("you entered a number greater than or equal to five.");
}
return 0;
}
This is a simple program. It declares the variable, x, and then asks the user to enter a value and assigns it to x. Once this is done, it tests if x is less than five. If it is, then it performs whatever is encased within the curly braces associated with the if statement, which is the loop. If the condition is met, and the loop is executed, then the computer outputs the numbers 0-9 on the screen. If it is not met it simply prints that the user entered a number greater than or equal to five.
If an if statement is within the curly braces of another if, else, or else if statement, then it is said to be nested in the original if statement. The way a nested if statement works is that the outer if statement (the if statement that is declared first) is tested. If the condition is true in the outer if statement, it then goes into the inner if-statement, and tests that. There can be virtually an unlimited number of nested if statements, but you should check your compiler's documentation for more information. Here is the general form of a nested if-statement:
PHP Code:
if(condition) //outer if statement
{
if(condition) // inner if statement
{
statement1;
statement2;
...
}
}
Remember, it is required that both conditions in the inner and outer if-statement to be met before the statements in the inner if-statement can execute. Also, if you would like, you can add statements inside the outer if-statement, and outside the inner if-statement, and they would execute, requiring only the first condition to be met.
The principal of nested loops is based upon the same idea as nested if-statements. There is an outer loop, and an inner loop (or multiple inner loops if you desire). Any type of loop can be nested, but for the purpose of this article, I will only demonstrate with for loops, and you can experiment with other loops later. The way a nested loop works is, once the outer loop is initiated, it goes into the inner loop and makes one complete round through the inner loop until the control variable no longer meets the condition needed to make the inner loop run. Then, the control variable for the outer loop is incremented, and the cycle repeats itself. It keeps going until the control variable in the outer loop does not meet the conditions required for the loop to keep cycling.
Here is the general format of a nested loop:
PHP Code:
for(controlVariable;condition;increment) //outer loop
{
for(controlVariable;condition;increment)
{
statements;
}
}
It's as simple as that. I will demonstrate a nested for loop for you by writing a program which prints the multiplication table up to 10.
PHP Code:
#include <stdio.h>
int main(void)
{
int i;
printf("\n"); //make sure we are not on a line with other text on it
for(i=1;i<=10;i++) // outer loop
{
int j;
for(j=1;j<=10;j++) // inner loop
{
printf("%d\t", i*j) // the operation i*j is performed in printf() before output
}
printf("\n"); //print new line every time the inner loop is complete
}
return 0;
}
The program declares i, the control variable for the outer loop. It then uses a
printf() function to print a new line. This is to make sure that no other text is on the same line as the first row of your table. This is just to add a little elegance to the program, and is inessential for making the actual program run. After that, the outer loop is initiated. The first thing that is within the outer loop is the declaration for j, the control variable for the inner loop. After that, the program goes into the inner loop. It executes the
printf() function. The format specifier sees the second argument is i*j. It runs that simple calculation first, and then outputs the answer along with a tab. It then increments the inner loop. Once the control variable for the inner loop, j, is 10, and the final cycle for the inner loop is complete, the program exits the inner loop, and goes back to the outer loop. It sees a statement that prints a new line so that your next row can be started. After the last statement in the outer loop is executed, it increments i, the outer loop's control variable. It redeclares j, and reassigns it the value of 1, ergo repeating to the whole process repeating itself over. After the outer loop's last cycle, it exits the loop, which in this case proceeds to exiting the program.
Break/Continue Section 3.11
There are two statements which allow you to expand the control you have over a loop. These two are the break and continue statement. Both statements would be placed inside the loop as needed. The break statement exits the loop altogether, and continues on with the rest of the program. The continue statement, on the other hand, exits only the cycle, and begins the next iteration of the loop, as long as the control variable still meets the condition. It doesn't execute any code in between itself and the end of the loop. In while loops, and do-while loops, the continue statement simply goes to the beginning of the loop without performing doing anything else. In the case of a for loop, it will perform the increment, and then start the next iteration of the loop.
Here is a little program that adds numbers forever, unless explicitly told to exit by the user.
PHP Code:
#include <stdio.h>
int main(void)
{
for(;;) // an infinite loop (outer loop)
{
printf("\nPlease enter an integer");
int x;
int y;
scanf("%d", &x);
printf("\nPlease enter another integer");
scanf("%d", &y);
printf("\nthe sum of the integers is: %d", x+y);
int test;
for(;;) //(inner loop)
{
printf("\nEnter \"1\" if you want to perform another operation");
printf("\nEnter \"2\" if you want to exit");
scanf("%d", &test);
if(test == 1)
{
break; // break from the inner loop
}
else if(test == 2)
{
break; //break from inner loop
}
else
{
continue;
/* continue in inner loop
this continue only takes place if the user didn't enter "1" or "2"
it asks the user again what they want to do*/
}
}
if(test == 1)
{
continue; //continue outer loop performing this whole process again
}
else
{
break; // break from outer loop
}
}
return 0;
}
This program is an excellent example, because it uses many of the concepts of C that we have already learned.
The program begins by starting the outer loop as soon as we enter main. A for loop with nothing inside means that there is no control variable, no condition, and since there is no control variable, there is no increment. It is an infinite loop, which continues forever, or until it hits a break statement. The outer loop asks for two integers, adds them, and outputs their sum. After that, an integer variable, test, is declared.
The test variable is the one which holds the value of whether the user wants to perform another calculation or not. Once we are in the inner loop, the computer asks the user to press one if they want to perform another operation, or two if they want to exit. It uses an if statement to perform a different set of statements for the two choices.
If the user inputted one, the break command exits the inner loop. It then goes into the outer loop, and sees that the first command is another test. It once again tests if the variable test holds the value "1". If it does, it uses the continue command. This causes the next iteration of the outer loop to be initiated.
If the user selected to exit the program by inputting "2", the inner loop is once again exited using the break command. Again, once in the outer loop, it sees that the first command tests the variable test against one. This will not be true, so it will go on to the else statement, where it breaks from the outer loop, and thus exiting the program.
If the user does not select one or two, the continue command in the inner loop causes the entire loop to be run through again until the user either inputs a one or a two.
Scope Section 3.12
An important thing to know about variables is how to know the scope of a variable. The scope of a variable defines in which sections of code the variable can be referenced. A variable can either be a global variable, or a local variable. A global variable is declared outside of any functions, including the main function, and a local variable is declared in a certain function.
A global variable can be referenced from anywhere in the program. It is generally a good idea to avoid using global variables whenever possible, but they are required at certain times.
A local variable belongs only to a function. It can be accessed or referenced by any statement in that function, it can be manipulated in that function, used for calculations in that function, and whatever other uses you can think of for a variable, but it can only be used in the particular function that it was declared in. If you try to access it outside of that particular function, you will get an error while compiling. Also, since local variables or only accessible within their own particular function, it is perfectly alright to have two variables with the same name, as long as they are in separate functions.
Also, if a variable is declared inside a block of loop (within a set of curly braces), it is only accessible by that block. If you try to access it from outside its block, you will get an error. Consider this example (not actual code):
PHP Code:
for(;;) //arbitrary outer loop
{ // start of block 1
int i;
if(someCondition)
{ // start of block 2
int j;
for(;;) //arbitrary inner loop
{ // start of block 3
int k;
statements;
} // end of block 3
} // end of block 2
} // end of block 1
Here, the variable i will be accessible throughout this segment of code, since everything is under its block, which is block 1. The variable j will not be accessible outside of block 2, but the inner loop could use it, since it is under block 2. The variable k will only be accessible by the inner loop.
C conventions Section 3.13
here are a few C conventions that programmers like to follow. Of course, this is only convention, and there is no requirement that says you must follow it, but it is usually a good habit.
The first convention is that programmers never start a variable name or a function name with a capital letter.
Secondly, keep your variable names and function names something that relates to what the variable's or function's purpose is. This is so if you want to come back and read your code six months later, it is easy for you to understand. You are not going to remember every single variable in a piece of code that you have written after a while. Unfortunately, I have not demonstrated this convention too well. Also, when naming characters, if you want a function name or variable name to consist of more than one word, a programmer usually does this by capitalizing the first letter of every word, except for the first word.
Third, it is a good habit to tab your code over when beginning a block, as I have been doing thus far. It makes your code cleaner, and easier to read.
Basically, just keep your code as clean and easy to read as possible.
Conclusion Section 3.14
You have learned quite a bit in this chapter. You will be surprised at how much you can already make your computer do. Conditionals and loops are one of the biggest parts in any programming language.
To test your knowledge, write a program that allows the user to input an integer. Calculate every single prime number up to the number that the user has entered. Use functions wherever you deem necessary. This is challenging, but will help you practice just about everything you have learned so far.
As always, leave me some feedback. I like to know what you think. If you need help with the challenge, post here. If I made a mistake, let me know.