Showing posts with label beginning. Show all posts
Showing posts with label beginning. Show all posts

Monday, 28 March 2011

Nested Loops

Just a quick post today on nested loops.

The basic concept is that you will have one (or more) loop inside of another loop. Each internal loop will run and terminate, and then any external loops will then run. Here's an example:

for(int i=0;i<5;i++)
{
    printf("i = %d\n",i);
    for(int j=0;j<5;j++)
    {
        printf("j = %d\n",j);
    }
}


The output would be:

i = 0
j = 0
j = 1
j = 2
j = 3
j = 4
i =1
j = 0
j = 1
j = 2
j = 3
j = 4
i =2
j = 0
j = 1
j = 2
j = 3
j = 4
i =3
j = 0
j = 1
j = 2
j = 3
j = 4
i =4
j = 0
j = 1
j = 2
j = 3
j = 4

So you see that it is really much like a normal loop. Each time a loop runs, it must execute all the code contained within its scope before looping again - even if it contains another loop.

This is just a quick basic concept that should be understood. This is very useful when dealing with multi-dimensional arrays (matrices), but I'll come to that in another lesson.

Sorry for the short post! I need to get back to studying for exams.

Friday, 25 March 2011

Loops

Loops are useful for running one or more lines of code repeatedly. The basis of how a loop works is similar to an if statement: There is a condition, and if the condition fails, the loop stops. The first loop I'll show you is a called a while loop, here's its syntax:

while(condition)
{
    //code
}

Pretty simple. Let's see this in an example

int i=0;
while(i<10)
{
    printf("%d\n",i);
    i++;
}

(For those who don't know, i++ is the same as saying i=i+1 or i+=1. It means "increment i")
This will print out the numbers 0 to 9.
Basically we start by initializing an integer to 0. We tell our while loop "Loop the code while the value of i is less than 10". In the first pass, the condition passes the test because 0<10. Good! So we go ahead and call our printf function. Here's the important part: we increment i by 1. So now the value of i is equal to 1 and we return to the beginning of the while loop and run the condition again. Now we're asking "Is 1 less than 10?" Yes it is. We run the loop again. printf, increment, loop again: "Is 2 less than 10" Yes....you get the idea.
Let's look at the last pass through the loop, when i is equal to 9. "Is 9 less than 10?" Yes, so go into the loop, call printf and increment i. Now we go back to the top yet again, but this time we ask "Is 10 less than 10?"
The answer of course is NO, so we skip the loop entirely, just as we would if a condition in an if statement failed.

This is a simple use for a while loop, and in fact, while loops using a simple incrementing variable can be rewritten as another type of loop: a for loop. The syntax is a little more complicated, but in the end, for loops generally end up being easier to manage.

for(initial state;terminating condition;increment)
{
    //code goes here
}

Let's look back at our while loop example for a sec. See how we declared an integer i before the loop? That's our initial state. We then had a condition in the while loop. That of course is the terminating condition. At the end of the while loop, we increased the value of i. That's our increment.

Here's the same loop above rewritten as a for loop:

for(int i=0;i<10;i++)
{
    printf("%d\n",i);
}

Both loops essentially do the exact same thing. The real difference for you is that in a for loop, all the useful loop information is stored in the parentheses after the word "for".
Note that in the for loop, I declared my incrementing variable inside the parentheses. This is a matter of preference, but I do it whenever possible. Basically, I'm saying that the following is still correct:


int i;
for(i=0;i<10;i++)
{
    printf("%d\n",i);
}


While this is still correct, I find it very beneficial to declare your incrementing variable inside your loop. This way, the variable "dies" after the loop ends. This means that you can reuse that variable name for other loops and you don't have to worry about this loose variable floating around your program. This means that I could do this:


for(int i=0;i<200;i++)
{
    //run some code
}

for(int i=0;i<42;i++)
{
    //run some different code
}

And I won't have to worry about which variable I used before. Again, it really is a matter of preference. I showed you mine.

When writing loops, you'll likely accidentally code an infinite loop at some point. For example, take a look at this:

int x=5;
int y=2;
while(x==5)
{
    printf("...");
    y++;
}

With a quick look at the code, you'll see that our condition is always true! This means that the loop will never end. Likewise, the following will be an infinite loop.

while(1)
{
    //code
}

Thinking back to our logical operators, a logical statement return a value of 1 if true or 0 if false. Thus, our condition is interpreted as "While 'a true statement', run this code." No wonder it will loop forever!

It is also important to check your for loops for infinite loops, since for loops especially are usually not meant to be infinite.

for(int i=0;i>-1;i++)
{
}

will be an infinite loop since we are looping as long as i is greater than -1 and each time the loop runs, i is incremented. An infinite for loop can also be forced by writing:

for( ; ; )
{
}

No initial state, no terminating condition, no increment. The loop has noting to worry about and will go on forever.

Next time, I'll talk about nested loops

Wednesday, 23 March 2011

More conditions

So yesterday, we looked at if statements and how to use them with simple conditions. To make our conditions more complicated, we need to make use of more of the logical operators. I'll give a real life example:

"It is sunny and I am not indoors."

A pretty simple statement. Not thinking about coding right now, let's let:
p = It is sunny
q = I am indoors

If we wanted to write this as a condition for an if statement, we would have:

p && !q

Pretty simple, right? Now let's look at the statement:

"It is sunny or cloudy, but not raining."

An important note about logic: BUT has the same logical meaning as AND. So we have:

"It is sunny or cloudy, and not raining."

Now, an important point about how this statement is interpreted. Do you remember BEDMAS, the order of operations when doing arithmetic? This states that certain operators must be evaluated before others (the order is: brackets, exponents, division/multiplication, addition/subtraction). Well logical operators also possess a precedence factor as you'll see. Let's look at our statement again. It states that it is sunny or  cloudy, but not raining. At first glance, it may seem at though the condition first checks to see whether it is sunny or cloudy, and then checks to see if it is raining. i.e. this:

(sunny or cloudy) and raining

In fact, when dealing with logic, I like to think of AND as a multiplication symbol and OR as addition (there's a discrete mathematical property that actually says this, but I won't get into that). In other words, AND will precede OR when dealing with operations, so our original statement actually means this:

sunny or (cloudy and raining)

See how it completely changes the sense of our condition? It's like comparing:

(5 * 5) + 10 = 250
and
5 * (5 + 10) = 75

Just a note to be careful when coding.
Great, now that that's out of the way, you are legally entitled to see some code.

Let's say we are writing a program in which we are asking the user for a time in hours and minutes. Obviously, we don't want to deal with hours greater than the number of hours in a day or minutes greater than 60, so a common fix is to set a default value if the user enters invalid data. We'll work from hours 0 to 23

int hour,min;
//prompt user for data
if(hour<0 || hour>23)
{
    hour=1;
}
if(min<1 || min>60)
{
    min=0;
}

Notice how we cannot use mathematical notation like: 0<hour<23. Instead, we must explicitly show each condition we want to include.

I hope this has been useful!

Next time, I'll talk about loops.

Friday, 18 March 2011

Simple Functions

Functions are the basis for writing programs in C.  They allow you to efficiently run repeated lines of code. For example, take a look at this mathematical function:

f(x) = x2

This function takes any real number x and squares it. Another way of writing this function could be:

f(x) = x*x

In C. Functions have 3 "Parts":
1) The function prototype which tells the program what to expect when the function is defined.
2) The function definition which tells the program how to execute the function.
3) The function call, which actually runs the function.

For this example, let's look at this square example. To declare a function, you must specify its return type (more on this is a sec) and then give the function an identifier and specify its parameter type. The parameters are the values that get passed into and used by the function (in f(x), our parameter is x). Here's a function prototype for our square function.

int square(int);

Later in your program, usually after your main method (unless you decide to declare it before, in which case a function prototype is not necessary), you will include your function definition. Here's the definition for square.

int square(int x)
{
    return x*x;
}

A really simple function. The program will take whatever value gets passed into the function. That value is now represented by x. The function now calculates the square of x and returns the value back to wherever the function was called. Here's an example showing how to call this function

#include<stdio.h>


int square(int);


int main()
{
    y=2;
    printf("The square of %d is % d.\n",y,square(y));
    return 0;
}


int square(int x)
{
    return x*x;
}


Compile this and you'll see that the output of the program is:
The square of 2 is 4.

Notice how to call the function, you simply write the function name and then the values you want to pass into the function (These are called the arguments).

Wednesday, 16 March 2011

Declaring and initialising variables

Today, I'll show you how to declare and initialize variables and talk about the possible types.

C has a few "core" data types called primitives these data types typically hold some sort of numerical value. The following are primitives:

int (integers)
long (integers)
float (real numbers)
double (real numbers)
char (characters)

The most used primitives are int, float, and char. Long and double are simply ints and floats respectively which allow a wider range of values.

Declaring a variable is easy. You first type the type of variable you want to declare, and then you give it an identifier (a name) which must start with a letter and may contain numbers and underscore characters as well. For example:

int x;

would declare an integer with the name x. You can now assign a value to x using the assignment operator =.

x=5;

This would store a value of 5 in x. It is also possible to combine declaration and assignment in one line.

int x=5;

is also acceptable. floats are declared in the same way.

float y=2.7;

however, attempting something like:

int z=3.14;

would cause an error, because 3.14 is not an integer.
Declaring characters is done in the same way, however, assignment is slightly different.

char c='f';

This would declare a character and hold the character 'f' in it.

Every character has its own unique code to identify it. Given the 256 standard characters, these codes are called ASCII codes and each ASCII character has its own. In C, when you store a character in a variable, you are actually storing the value of its ASCII code. When you want to specify that you're talking about a character, you must put it between apostrophes.

Next time, I'll talk about modifying the contents of variables and displaying their contents using printf();