Wednesday, July 28, 2010

C Programming Basic - Functions

Programming language

Think you need to tell a computer to count the number of green beans from the mix of green and black, the instruction may like this:

Look through each of the beans, if it's a green one, count one more and put it to another side. Continue until there isn't any bean.

That's quite natural for you, but it is not understandable for computers. The computers, they are quite dumb, they has the language capbility no more than a four-year-old-child. We, as coder programmers have to translate our language into the language which the computer can understand - named byte code. However, each CPU has its own set of instructions it can understand, so for each type of CPU there are diffrent byte codes. Think of this as many different childrent speak different language, and you have to tell all of them what to do. People are smart, so they come up with a solution: They write a program that do the translation automatically, and they also create a medium language for this program - programming language - which stand between speaking language and computer language. In C, the above instruction can be rewritten like this:

/* beans.c */
 
#inc <stdio.h>
 
int main() {
    int i, count;
 
    int beans[10];
 
    beans[0] = 1;
    beans[1] = 0;
    beans[2] = 0;
    beans[3] = 1;
    beans[4] = 1;
    beans[5] = 1;
    beans[6] = 1;
    beans[7] = 1;
    beans[8] = 0;
    beans[9] = 0;
 
    for (i = 0; i <= 10; i++) {
        if (IsGreenBean(beans[i])) {
            count++;
        }
    }
}

While this is not a runnable C program, it looks quite good. Let's dive into it.

C Functions

There is similarities between this new example and hello.c. You have already known about the first line, the semicolons and the curly brackets. Now we will discuss the building block of a C program: functions. You have seen one, it is the main() function:

int main() {
    ...
 
    return 0;
}

A function is group of statements to acomplish one task, with or without some given condition. There is another funtion you have known: it is the printf() function. When use printf("Some text");, you run the function, or more technically: called it. Functions can be classified into two kinds, but I tent to categorized them as three:

  • The void functions: this is a commond kind of function. In other programming language like pascal, void functions are called procedure, because they does not act like math functions, they can take in some number but does not return anything.
  • Normal functions: in contrast with void functions, normal functions act exactly like math functions, they take in variables and return one value through their name.
  • The main() function: this is a must have function in every C program. When you execute the program, the main() function is called. It can be a void function, but in modern programming, it is often declared as a normal function like I do above. It returns a integer, 0 if everything is OK and other if not. This is a good practice since we can read the state of a function through it returns value.

Function declaration

Go back and reobserve the given example of function declaration above. The first line tells the compiler that we will make a function named main, it takes no argument while returns an integer. Any function declaration can go like this:

return_type function_name(taken_arguments) {}

If you look at the stdio.h file you can file the printf() function is declared with something like this:

int printf (__const char *__restrict __format, ...);

Because the main() function doesn't require any argument, so we leave taken argument field blank. However, printf() require some argument, so it is declared as above.

Note: C is case-sensitive, so print is not equivalent to Printf or PRINTF.

Function call

We created a powerful function, then whenever we want to use it, we have to call it. Also, you have already know this.

printf("Hello, world!\n");

That's it! FunctionName(arguments). If the function has return value (it is a normal function), we can call the function and assign the returned value to a variable like this:

a = printf("Hello, world!\n");

The value of a is 0.

Exercises

Programming exercises:

  1. Examine function IsGreenBean() in the complete code, insert a printf statement inside the function body to ensure that the function is called ten times.
  2. Modify hello.c, create a SayHello() function that print the welcome message. Call this function 5 times in the main() function so it print out 5 welcome messages when run.
  3. Create a Add() function that takes two integers as argument, and return an interger value equals to the sum of the two arguments.
  4. Write a program using the Add() function you have created. Call it a few time to make sure it work. Ex: printf("The sum of 3 and 5 is: %d\n", Add(3, 5));

Reading exercise: Read about the printf() function, find out the meaning of %d and \n.

Source code: beans.c

Monday, July 19, 2010

C Programming Basic

Let's move on. Before we go ahead analyzing the program we wrote in the previous chapter, we'll spend a few minutes discussing about computer programming in general, and then about C.

Programming

First of all, why write a computer program? There are many reasons. However, most of them is written in order to take the advantage of computer in processing a large amount of data. For example, we have over 40.000 student in our university. Each study about 9 subjects per semester and we have to store, organize and do some calculation with 3 x 9 x 40.000 = 1.080.000 numbers. We can't deal with that by hand, can we?

Second, about C programming language. Nowadays, there are numerous of programming languages, but C is the most popular one. It was developed by Dennis Ritchie at AT&T Bell Labs in 1970s. The kernel - the core - of Unix and Linux operating system is written in C. Its syntax inspired many modern languages such as Java, C# and C++.

C lacks many functionalities that modern programming language requires. For example: It is too close to the hardware (C is know as the most low level of high-level programming languages); there is not any garbage collection so we have to do all the memory managing task by hand. Further more, it is not object oriented, so for complicated projects, people tend to use object oriented flavor of C such as Objective-C or C++.

C Programming

In general, a programming language comprise at least three components, the syntax, the compiler or interpreter, and the core library. Let's all of those things working together in our example in previous chapter.

The C syntax

As I said above, C's syntax inspired many modern programming languages. It is very clean and efficient. Obviously, each statement is finished by a semicolon (;); and chunk of statements can be grouped together inside curvely bracket ({}). Of course, learning a programming language is all about the syntax, so we will talk about it many times later.

The C compiler

Some programming languages have compiler, some others have interpreter, and some even have both compiler and interpreter. What these things do is to translate the source code into binary, or execute it. With C, there are both compiler and interpreter, but most of the time we will use compiler because it is the C way. There are also various C compiler, such as GNU C Compiler (gcc - which we used), Borland C, Microsoft C Compiler and many more. We use gcc in this course because it is free and open source, it is also cross platform and it is the most popular one. Remember our command?

gcc -Wall -Werror -W -o hello hello.c

gcc invoke the compiler. -Wall, -W, and -Werror is short for Warn all and Warn Error, which tell the compiler provide more feed back if there was something wrong with our program. -o hello let the compiler know that it should provide the binary file named hello instead of its default hello.out. Finally, hello.c is the file it should compile.

C Standard Library

The first line in our program:

#include <stdio.h>

tells the compiler that we will be using a standard C library named stdio.h. Naturally, C programming language comes with many standard libraries, which is collections of pre-written functions we can use in our program later. In this example, we include this library so that later we can use the function printf(), whose job is to print out a given string.

What's next?

Up to this point, you haven't had have many thing to learn yet. So your exercise will be as easy as skim the gcc man page and make the program display "Hell, no!". Until next time.

Source code: hello.c

Setting up

Before doing anything, you'll need to download and install some packages so that you have tools for your development.

Compiler

Basically, the only simple step you have to do is type in the Terminal:

sudo apt-get install build-essential

Hit Enter, type in your password and let it run. The command is applied for Ubuntu Linux and every other Debian-based distros. If your distro is not Debian-based, I am sure there is a equivalent package for it; go download and set it up.

For those who curious, this package is a set of tools considered essential for building software (Exactly it is the GNU C Compiler (GCC( and its dependencies)

Get a text editor

There are tons of decent text editor available for Linux user; However, in this series we are focusing on programming, so we will forget about choosing between different text editors for a while. Instead, we will use the text editor comes with Ubuntu and many other Linux distros - GEdit.

Believe me, GEdit is very cool, especially after we give it some power-up. We do this by typing in the Terminal:

sudo apt-get install gedit-plugins

Again, this command is Debian-based specific, but there is equivalen for other distros. Open GEdit and then you may ask me, what's up? I don't see the differences.

Open Edit->Preferences, disable text wrapping, enable line numbers, right margin and highlight matching bracket. These option is not compulsory, but they are very helpful.

  • Wrapping for long lines is easier for read, but for beginners, it bring difficulties to distinguish the statements.
  • Line numbers comes in very handy when you need to switch between different locations in the source code.
  • Next, about the right margin. You will see long lines of code is particularly hard to see, especially when line wrapping is disabled as I said above, right? Instead of rely on the text editor breaking the line randomly for us, we do it manually at column 80 following the right margin. This is a good practice followed by most programmer in the world (but our professors may not do so I guess :D).
  • Finally, highlight matching bracket options help you to ensure that you closed all the opening ones, reducing the error rate.

Next go to Editor, set tab width to 4 as it is the standard, and enable automatic indentation to save your time coding.

In Font & Colors you can change the color scheme to fit your taste.

So that's it! Your working environment is set and we're ready to go.

Your very first C program

Well, I don't want to start it now, as you will have some time to prepare your mind. However, we need to write a program, compile it and run it to ensure that our setup is OK.

Let's start of by creating a new Folder for the first program. You may want to place it in a folder for the whole series, such as [Your Home]/Study/LearnC/Chapter-1/.

Create a new file, name it hello.c, then open it with GEdit and type in:

#include <stdio.h>

int main() {
    printf("Hello, world!\n");

    return 0;
}

Looks weird? No problem, we can deal with it later. Now let's just compile and run it by typing so in the Terminal (make sure you have changed to our working folder):

gcc -Wall -Werror -W -o hello hello.c
./hello

You should see the string "Hello, world!" to be printed out. So it worked!

Conclusion

We have worked hard today, so we should stop now. As the exercise, try to figure out what is the meaning of each line in the program, and what we have done in order to compile it. The answer of course is in the next chapter. See you later.