## Monday, December 26, 2011

### Coding lessons: C and String functions (lessons 13)

Firstly, Merry Christmas!!

Two lessons ago I discussed arrays, and how to use them.
in the last lessons I discussed that Strings were in fact just arrays of characters.

We noted (with code) that it was easy enough to poke values into these arrays, and pretty simple to read them back out using the %s operator, in the same way that we'd used %f for reading floating point numbers, and %i for integers and %c for characters.

It's all very well looking at how a program can display strings, but what we really want is to learn how to manipulate those strings.

This lesson will introduce some functions for manipulating strings.

Firstly, it's important to say that the C language has pretty much no built in functions for using strings. so far we've only been including the standard input/output library (stdio.h), but now we're going to need to start using a library that's been written especially to use strings.

string.h

the first function that we'll look at is strlen.

strlen determines the length of a string, it's a number, clearly an integer number you don't get  half a letter in a string.

Number = strlen(string);

so a quick program that makes use of this is

#include<stdio .h>
#include<string .h>
int main()
{
char hw[] = "Hello World";
int num;
num = strlen(hw);
printf("the string %s is %i characters long", hw, num);
}

Now let's look at copying strings between different arrays.

to copy a string, we need to use strcpy (string copy)

strcpy is a function that you pass two parameters to
strcpy(destination, source);

this is different from how you're used to copying thins saying copy this source to that destination.

here's a quick program to look at strcpy

#include<stdio .h>
#include<string .h>
int main()
{
char hw[] = "Hello World";
char ds[20];
strcpy(ds, hw);
printf("the start string is %s\r\n this is copied to string 2 which says %s", hw, ds);
}

The next thing that we're going to do is look at comparing strings.
The function for comparing strings is called strcmp
There are three possible results for the strcmp function
the are 0, (they are identical)
Less than zero, (the strings are different and the first string is alphabetically before the second string, (e.g A is alphabetically before B).
if more than zero is returned this tells you that the first string is alphabetically after the second string. (e.g C is alphabetically after B).

#include<stdio .h>
#include<string .h>
int main()
{
char string1[] = "hello";
char string2[] = "world";
int result;
result = strcmp(string1, string2);
if (result < 0)
{
printf("the result is less than zero (%d), so string 1 (%s) is alphabetically before string2 (%s)", result, string1, string2);
}
if (result == 0)
{
printf("the result is zero (%d), so string 1 (%s) is athe same as string2 (%s)", result, string1, string2);
}
if (result > 0)
{
printf("the result is greater than zero (%d), so string 1 (%s) is alphabetically after string2 (%s)", result, string1, string2);
}
}

Now we'll look at adding strings together, to add strings together, Or catenate strings we use the strcat function.
when using strcat, like strcpy the name of the destination string comes as the first variable passed to the function, then data you want to poke into it comes next.

#include<stdio .h>
#include<string .h>
int main()
{
char firstname = "john";
char lastname = "doe";
char fullname[50]; /*make an array at least big enough to hold the greatest expected data entry*/
/*Print the last name string*/
printf("uncorrected last name = %s\r\r\n", lastname);

/*see we need to write null values to each box of the string array -we'll use a for loop if we don't do this then some odd things can be displayed!*/
for (i=0;i<=49;i++)
{
fullname[i]='\0';
}
/*first put the firstname into the string*/
strcat(fullname, firstname);
/*now put last name in after that*/
strcat(fullname, lastname);
printf("fullname = %s", fullname);

}

And for now that's all I'm going to write about strings.

## Monday, December 19, 2011

### Coding lesson: Loops (lesson 12)

In the last lesson I spoke about conditional statements.
Now I'm going to have a look at how we do something repeatedly whilst something is true, or how we do something a finite number of times.

Firstly I'll look at the while function

the while function does something whilst a condition is satisfied.

for example

i = 1;
while (i<=10)
{
printf("i isn't 10!");
}

as i is never modified this statement is always true, and so the loop never finishes.

i = 1;
while (i<=10)
{
printf("i isn't 10!");
i = i+1;
}

you see we're modifying i now so that eventually the condition for the loop to end will be met.

the while statement checks the condition before it is executed.

if we want to run the code at least once, and also again and again whilst a condition is true we use the do function

do
{
}

this will ask you for a password, and would keep running until the condition was false, (until the password guess matched the password)

The other kind of loops that we can use are for loops.
The for loop sets up conditions in the start statement, and runs until the condition is satisfied.

for(start value; condition; modified for each loop)

for
a = 0; /*start a at zero*/
a ==9; /*do this loop whilst this condition is true/*
a = a+1 /*add 1 to the value a on each loop*/

for(i=0;i<=9;i=i+1)
{
printf("A");
}

this prints the letter A ten times.

## Monday, December 12, 2011

### Coding lessons: C and conditions (Lessons 11)

So far I've discussed how to get some data into a program, and how to display data out of a program.
I looked at adding number data together. Different ways to store and group data.

but so far that's pretty useless without being able to make decisions about data pin software.

So in this lesson I'm going to discuss conditions and statements in C.

so first lets have a look at the kind of operators we use when looking at logical conditions.

Does A equal B?
Does A not equal B?
Is A greater than B?
Is A less than B?
Is A greater than or equal to B?
Is A greater and B or Greater than C?
Is A greater than B and greater than C?

in short we have, equal, not equal, greater than, less than, greater than or equal, less than or equal.
and we want a way of glueing multiple conditions together in an if this AND this, or and if this OR this kind of way.

we also want to know what to do:
if This then do this, otherwise do that instead.

what we're going to look at is IF

if is a function, and like all functions we have a function name, and then parameters to pass to it that are contained inside brackets.

if(conditions)

our conditions are all logic based

if 1 = 1 then...

except, we already have a function that happens when we write a=1;

so for the logical is a = b we say

if (a==b)

(double equals signs)

instead of saying then, we open new curly brackets

if (1==1)
{
printf("one equals one");
}

notice that the ilne with the if statement is not terminated with a semi colon

for not equal we use the symbol !=

if (1!=1)
{
printf("Oh dear, one doesn't equal one any more");
}

in some circumstances we may want to have alternative paths.
for this we use the else statement

if (1!=1)
{
printf("Oh dear, one doesn't equal one any more");
}
else
{
printf("It's OK, maths still works");
}

I also mentioned that we may like to use the greater than > or less than <
or greater than or equal to >= or less than or equal to <=

if (1<=5)

or more useful for programs would be saying is a variable something

if(a>=10)

Now there may be times when we want to glue a few things together.

In this case we say
is A equal to be, and equal to C?

if ((a==b)&&(a=c))
{
printf("A, B and C are all equal");
}

you can understand how the & symbol is used for AND statements, (well two of them)

for OR statements we use two pipe characters ||

if ((a>=b)||(a>=c))
{
printf("A is greater than or equal to either B or C");
}

you use brackets to contain statements in exactly the same way you would in regular mathematical expressions.

Finally, you may wish to have a lot of possible outcomes, in this case rather than writing out.

if (a==1)
{
...
}
if (a==2)
{
...
}

you use a switch function.

the switch function compares a variable against a series of outputs and runs code against a chosen output.

if no pre-defined output matches the variable then a default set of code can be run.

Lets say that variable A is some error code information.
where the following statements describe the error

if the error code is 0, the program is fine.
if the error code is 1, the program ran out of memory

If anything else happens then this is bad, because some kind of unknown condition has occurred.

so the code would look something like this:

switch (a)
{
case '0':
printf("no errors have been reported");
break;
case '1':
printf("This program requires more memory, you must have at least some memory to run this program");
break;
default:
printf("this program encountered an unexpected condition and should be shut down");

}

This should be enough information to get you writing some code that you can use to start manipulating data with.

a good example would be the body mass calculator made in a previous lab, rather than telling people what their body mass index is, then telling them to figure out for themselves if they have a problem you can instead use a nested if statement.

if (bmi>25)
{
printf("overweight");
}
else if(bmi > 20)
{
printf("ideal weight") /*at this point we know it's less than 25 else the previous statement would have been executed*/
}
else if(bmi>15)
{
printf("underweight");
}

## Monday, December 05, 2011

### Coding lessons: C and strings (lesson 10)

In the last C lessons I talked about Arrays, I sort of gave some poor examples of how you may want to use an array for storing co-ordinate data, (for a map or a graph?) but really I just needed to introduce the concept.

In programming a string is a series of characters, each and every word I type is a string, this sentence is a string.

Strings are groups of characters all placed side by side in an array.

Boxes

The simplest way to describe an array is to look at a single input as a box, our Char variable allows only a single character to be put into the variable, it's like a single box that's 8 bits wide (so it can store the 8 bit char.)

Arrays

An array is like a load of boxes all placed next to each other.

The word "example" is a string, it's an array of characters, that's 7 characters in length

e x a m p l e

so we have seven 8 bit wide boxes (one for each letter) placed side by side.

basically, a string is an array of characters,
BUT what separates a string from an array of charecters is that the last "data pocket" in the array that makes up a string is a special NUL character. (this is just a regular char with value 0)

We can create strings in two ways.
Either declare an array, then enter in the data, and enter in the NUL character ourselves, or we can declare and fill the string when declaring it.

#include <stdio .h>
int main()
{
char hello[6];
hello[0] = 'H';
hello[1] = 'e';
hello[2] = 'l';
hello[3] = 'l';
hello[4] = 'o';
hello[5] = '\0';

printf("%s", hello);
return(0);
}

but that is a very difficult way of working with strings, in order to do more complex stuff with strings we will need to include the library string.h

in this next example we can see that we can have the compiler automatically see that we're creating a string, and not only create an array of the correct size of what we're trying to put in there, but also add the NUL character into the end of the array also.

#include <stdio .h>
int main()
{
char hello[6];
char world[] ="world";
hello[0] = 'H';
hello[1] = 'e';
hello[2] = 'l';
hello[3] = 'l';
hello[4] = 'o';
hello[5] = '\0';

printf("%s %s", hello, world);
return(0);

}

Notice in both these examples that when poking characters into the array they are contained in a single quote.
single quotes for characters, double quotes for strings.

hello[0] = "H";
Doesn't work because as H is contained inside double quotes it's data type is a string. you can't put a string of data into a single char space of data. trying to do this will result in a program that throws errors whilst compiling.