C Tutorial: switch, loops, and recursive functions

25 08 2009

This is the Tutorial I recently created for my Software Design students that we use during lab time here at the university. SFD is a basic intro to C type subject. I cannot post the other tutorials since they have been created by other lecturers but this one I can share. Enjoy !!!

Tutorial 5 (Outcome 3 ,4)

Part 1: switch Multiple-Selection Statement

When testing for many conditions the if statements that will be needed will grow large and make the code of your program harder to read. There is also some performance loss when using the if statement to check the same variable for many conditions. So when checking one variable for many conditions it is better to use the switch statement.

The basic syntax for a switch statement is:

switch (variable)
{

case test :
statement(s) if is case is true
break;

case test :
statement(s) if is case is true
even more statements
break;

default:
statement(s) if not one of the cases evaluated to true
break;

}

variable is the variables value you want to test.
test is the value you want to test variable for.
the statement(s) is the code that is going to be executed if true.
default: contains the code that is going to be executed if not one case evaluates to true.
always remember to end the case with a break;

Lets look at example one that uses a switch statement. In the example the user is asked to enter a number (int) between 1 and 5. The program first checks if the number is between one and five using an if statement. Then it displays on the screen the number the user entered but it shows the number in word format. So if the user enters 5 the program will display FIVE.

Example 1

Example 1

In example 1 the switch statement starts at line 25 and ends at line 47. In line 25 the variable number is sent to the switch. Line 28 contains the first case and checks if the number was 1. If the number was indeed one the program will move to line 29 were the printf() statement is executed. After the printf() in line 29 the program will encounter a break; statement in line 30 letting it know the case is done. If the number was not 1 the program moves to the next case etc.

You would notice that the switch statement in example one does not contain a default case. This is because the default case is optional. We can rewrite the code in example 1 and add a default case to the switch statement. The default case will only be executed if no other cases matched. This means if the user did not enter a number between 1 and 5 the default statement will execute. Since we now have a default case we can remove the if statement on lines 15 – 22 that checks if the number is between 1 and 5. Example 2 contains a switch with a default statement:

Example 2

In example 2 the if statement was removed. Line 38 – 43 now contains a default case. Note that each case including the default case ends with a break; statement. The break statement is very important since it tells the program that the statements in the case was executed and the program can now “break” out of the switch.

Part 2: Loop structures

Most programs contain structures known as loops. Loops allow for repetition in programs. Each loop structure will contain a number of instructions that gets repeated a certain number of times. The three basic loop structures are For, While and Do While.

Although the three types of loop structures do the same thing (repeat instructions) the way that they are implemented and used differ. Deciding on what type of loop structure to use will depend mostly on the type of repetition that is needed. The two types of repetition is Counter-controlled repetition and Sentinel-controlled repetition.

Counter-controlled repetition needs 3 things:

The loop counter that will count how many times the loop has been executed. The loop counter also needs an initial value.

The increment (+) or decrement (-) by which the loop counter is modified each time the loop is executed.

The test to check the loop counter and determine if the loop should be executed again.

Part 2.1: The while loop

The while loop will execute its statements while a certain condition is true. The basic syntax for a while loop is as follows:

while(test condition = = true)
{
//Execute some statements like incrementing the counter
}

Example 3 shows a basic while loop that will loop 10 times and display the counter. On line 8 the variable counter is created. counter Is the variable that will keep track of how many times the loop was executed and gets an initial value of 1. Line 10 – 15 contains the while loop. In line 10 one can see the test for the while loop. This loop will execute only while counter is less then or is 10. In line 14 after all the normal statements but still inside the loop counter is incremented with 1. This is done so that each time the loops executes counter gets larger by one until counter is more then 10 and the loop is not executed. If we do not increment counter at the end of each loop each time we will get what is called an infinite loop.

Infinite loops occur when the loop just gets executed for ever usually there is no way the test can result in false so the loop just keeps going.

Example 3

Part 2.2: The for loop

Unlike when using the while loop with the for loop you can initialise the counter, test the counter and increment / decrement the counter in one line. The syntax for the for loop is as follows:

for(assign value to counter ; test condition ; counter increment / decrement)
{
// Statements to execute
}

Example 4 shows an for loop implementation that does exactly the same thing as example 3.

Example 4

In example 4 a variable counter is declared on line 8. counter Will keep track of how many times the loop has been executed. The for loop is located at line 10 – 13. The counter was set to 1 the test will make sure the counter is not more then ten before the loop is executed and the counter is incremented by 1 each time the loop is executed. This al happens in line 10.

Part 2.3: The do…while loop

Very similar to the while loop the do…while loop is only different in that it tests the loop condition at the end of the loop instead of the beginning. This means that the statements included in the loop body will be executed at least once before the test condition is evaluated. If after the initial execution the test condition evaluates to false the loop will not be executed again. You can use the do…while loop when you want to ensure the statements inside the loop is executed at least once in your application. The syntax for the do…while loop is:

do
{
//Statements to be executed
}
while (condition)

Example 5 shows the do…while in action. Notice that even if the counter variable is set to more then 10 the statements will be executed at least once. This is different to the for and while loops that will first evaluate the test condition before any statements is executed:

Example 5

In example 5 a variable counter with default value 1 is created in line 8. The do…while statement is located in lines 6 -15. Notice how the while is located at the end in line 15. Also be sure to remember to increment the counter each time the loop is executed as in line 13.

Part 2.4: break and continue

We can use the break and continue statements to alter the flow of programs especially inside loops.

The break statement is used to exit the loop completely even if the next condition will still evaluate to true. We have used the break statement in the switch statement before to exit the switch after the cases statements have been executed. break Can perform the same function loops.

The continue statement will continue with next iteration of the loop ignoring any additional statements in the loop body after the statement.

Example program 6 shows the use of break and continue:

Example 6

Example program 6 tracks the numbers of years that the Dalton gang spends in jail. Line 6 -7 contains variables that is used in the program. jail_years is the number of years in jail and rnum is a random number between 0 – 10

Line 13 – 39 contains the for loop. On line 13 a new for loop is created. The for loop is created in such a way that the loop will execute until a break statement is encountered.

The first statement in the the for loop (line 16) will use the the getran() function (line 45 -54) to get a random number between 0 and 10.

The first if in the for loop will execute if the random number is 4 and then break out of the loop. A message is displayed showing that the Dalton gang breaks out of jail.

The second if in the for loop (line 28) will check if the random number is more then 5. If that is the case the number of years in jail will be incremented two times. The continue statement is then executed ignoring any other lines of code in the for loop (lines 37 – 38) .

If the random number was not more then 5 then the jail time is only incremented once in line 37.

Part 2.5: Nested loops

Just like if statements loops can also be nested. A nested loop will contain an outer and inner loop. With nested loops the inner loop is executed for each time that the outer loop is executed. Example 7 shows a nested loop:

Example 7

Part 3: Recursive functions

A recursive function is a function that calls itself repeatedly until some condition is met and the function can return a value. This sounds very much like loops and in a way they are the same. The most basic recursive function you can create is shown in example 8:

Example 8

In Example program 8 the function recurse(int count) (line 15) receives as an argument one integer. Then inside the function on line 18 the function calls itself with the original count + 1. This will lead to each instance of the recurse function receiving an argument that was incremented by one. The recurse function will keep calling itself and never return a value leading to an infinite recurse.

To make sure that the function does not just keep calling itself one needs to add a base case to the function. The base case is a condition that will return something from the function and stop the cycle of calls.

Example 9 shows a recursive function with a base case. The function will receive a number and start counting down until 0 is reached where it will the return 0 :

Example 9





My Podcast selection

21 06 2009

I have a 30 min drive to work each day. The road I use is single lane and used by big trucks, taxi’s and a wide array of mine vehicles. I always thought that taxi drivers were the worst but have since changed my mind.

In my opinion the worst drivers are people driving mine vehicles especially the ones with 4×4’s. But luckily I have found something to take my mind of the driving in a range of nice podcasts. This is my selection in order of preference:

1. Dan Carlin’s Hardcore History

WOW History presented in an interesting and fun way. You can hear that Dan does much research before each show. The way he presents each topic makes you think differently about history and the present day.

2. The Naked Scientists

Not just science news but also stuff you can do at home. Great for learning about all the different science fields

3. Linux Outlaws

Fabian and Dan are just two normal Linux users talking about Linux and related free/open source topics. The show always has a great selection of news and is probably the best pod cast when it comes to finding out what distribution released when. The Microwatch section also keeps tabs on what the evil Micro$oft is up to.

4. Ubuntu UK Podcast

A few Brits talking about Linux and Ubuntu. Because of their link to the Ubuntu distribution you get a good idea about the latest ongoings at Canonical and the Ubuntu distro. Also look out for the competitions.

There you go. If you have any other podcasts that you like please let me know so that I can try them.





Google Web Toolkit (GWT) – Generate FileMenu from XML

21 06 2009

I have been playing around with GWT the last few weeks and wrote a nice little function that reads a XML file and builds a FileMenu.

Real GWT programmers will probably frown on the code but please keep in mind this is only for fun. The XML structure looks like this:


links

mainLink name='My Links'
subLink name='Blog' url='http://fredreh.wordpress.com' title='My Blog' /subLink
subLink name='Facebook' url='http://facebook.com' title='See some friends' /subLink
/mainLink

mainLink name='Test'
subLink name='Tester' url='http://www.test.ac.za/' title='Tester' /subLink
/mainLink

mainLink name='Search Engines'
subLink name='Google' url='http://www.google.com/' title='Google' /subLink
subLink name='Wolfram' url='http://www.google.com/' title='Wolfram' /subLink
/mainLink

/links

The file name is links.xml the function BuildMenu() looks like this:


public void BuildMenu()
{
//Build the menus
//The requist builder for the XML passwords
RequestBuilder buildL = new RequestBuilder(RequestBuilder.GET,"links.xml");
//The main menu
final MenuBar linksmen = new MenuBar(true);
try
{
buildL.sendRequest(null,new RequestCallback()
{
public void onError(Request request, Throwable exception)
{
Window.alert("Could not get a list of Links for MenuBar");
}

public void onResponseReceived(Request request, Response response)
{

//Check the xml file and load the nodes inside
Element TopLvl = XMLParser.parse(response.getText()).getDocumentElement();

//Get a list of nodes under the main node
NodeList mainLink = TopLvl.getElementsByTagName("mainLink");

//Loop through the list of mainLink nodes
for(int j=0;j<mainLink.getLength();j++)
{
//Create the Element representing a
Element main = (Element)mainLink.item(j);

//The menubar representing a
MenuBar MLink = new MenuBar(true);

//A list of nodes inside the each one is a
NodeList subLink = main.getElementsByTagName("subLink");

//Loop through the list of subLink nodes
for(int i=0;i<subLink.getLength();i++)
{
//Create the Element representing a
final Element sub = (Element)subLink.item(i);
//Add the subLink details to the Mlink MenuBar
MLink.addItem(sub.getAttribute("name"),new Command(){public void execute(){Window.open(sub.getAttribute("url"),sub.getAttribute("title"),"");}});
}

//Add the completed MLink menubar to the main linksmen MenuBar
linksmen.addItem( main.getAttribute("name"),MLink);
}

}
}
);
}
catch (RequestException e)
{
Window.alert("Error");
return;
}

GLeftMen.setWidget(0,0,lblLinks);
GLeftMen.setWidget(1,0,linksmen);
}

I commented the code heavily and it shoud be clear.

Looking at the code I wonder how difficult it would be to take the XML generated by Glade and then build an interface when the user loads the page.

Anyway I hope someone can use the code it is licenced under WTFPL





A Cyber-Attack on an American City… (by South Africans)

23 04 2009

Bruce Perens writes about a recent cyber attack on an American  city:

“Just after midnight on Thursday, April 9, unidentified attackers climbed down four manholes serving the Northern California city of Morgan Hill and cut eight fiber cables in what appears to have been an organized attack on the electronic infrastructure of an American city. Its implications, though startling, have gone almost un-reported.”

We have been having problems with criminals stealing the Telkom cables maybe they upped their game and went International with this job.  Did anyone check if the cables was removed instead of just cut ?.

But it is interesting on how a city can be technology disabled by cutting a cable in America, luckily we don’t suffer from the same problem since we can not  rely on fixed lines in the first place.





Long time no post

19 04 2009

I am happy to report that my lack of posting is because of a few nice changes in my life.

I have started a new job as Junior Lecturer at Tswane University of Technology teaching 1st and 3rd years. This doest leave a lot of time for working on projects but I have made some progress on the Mxit perl library.

Since Mxit have released the protocol specification I have moved the project over to their site located here: http://devzone.mxit.com/

The project has its own space located here (Wiki) and here (Blog)

Since the campus were I teach is located in Witbank I have moved back in with my parents in Middelburg about 30 km from the campus. I will probably get my own place before the end of the year.

One cool application I can report on is DropBox . DropBox allows you to sync files over multiple computers and is nicely
integrated with Gnome. The registration process is totally painless and you get 2 GB free when you sign up (250 mb extra for using this https://www.getdropbox.com/link/21.X7hWEhmrJV link)

I have also upgraded to Ubuntu 9.04 and will report on the experience at a later time.

Remember keep the source open and have a nice series of long weekends (If you are in S.A)