User Tools

Site Tools


handbook:handbook:programing1

My first C program

Traditionally, the first C program we will discuss is the Hello World program. So, let’s view the source code of that program, and then discuss it line after line:

1.#include <stdio.h>
2.
3.int main()
4.{
5.printf(“Hello World\n”);
6.
7.return 0;
8.}

Libraries and include files

Let’s first pay some attention to the first line. It says “#include <stdio.h>”. The sign ‘#’ makes a big difference. The line which follows the ‘#’ sign is dedicated to the preprocessor, meaning that it will be translated by it. Actually, the preprocessor will notice the include command and therefore will include the file in the brackets, and that is “stdio.h”. But, what does it all mean? Well, files like stdio.h are called header files. That means that these files contain some special functions, structures, or other form of source code, grouped together in accomplishing one goal. For example, the name ‘stdio’ stands for Standard Input Output. That means, that all functions and variables contained in the stdio.h header file serve and exist for one goal: to provide standard input and output abilities to the user. One of the functions which provide such ability is the printf function, used in the fifth line. We will discuss it later. Of course, there are a lot of other header files, but built with different purpose. Many header files are located in the /usr/local/include directory, but that is also changeable, since the header files can be put into other directories also, but the #include line will have to be changed. For example, let’s assume that we have the following directory tree:

/home/program
/home/program/source

and the source file we are writing is located in the /home/program/source directory. The header file we need, example.h is located in /home/program. To include it in our source code file, we would have to do the following:

#include “../example.h”

The two dots represent the directory above the current working dir, and “example.h” is the filename, of course. But, there is one more significant difference. Notice the “ signs , they stay there instead of the brackets (<>) we used in the first example. The difference is, that when the brackets are used, the search for the specified header file will be executed only in the standard include dir, /usr/local/include in many compilers. But if we used the double quotes, then the searching will first start in the current dir, and then will continue in the standard include directory.

Many header files, all together, build a library. Library is a big collection of functions, variables and source code structures, designed to help in the programmer’s aim. Just to mention, there are GUI libraries, which provide function to draw windows, buttons and other forms of graphical interface to the screen, there are mathematical libraries, which contain all mathematical functions and so on.

Variables and functions

Variables

Now, lets continue with the other important line which follows. That is line no. 3. It says: “int main()”. First, we will discuss what variables are. Variables are simply storage places, capable of keeping different types of data. In other words, variables are reference to some place in the computer memory, which we work with. All variables in C are typed, meaning that the programmer must specify the type of the variable, before using it. There are several known variable types, and these are the four basic ones:

  • int: Integer values. It holds “whole numbers”,values like –1,-3,3,5 and so on. Typical integer can take 4 bytes of the computer memory, so, it can hold values from –2147483648 up to 2147483647. To declare an integer:
 int number;
 number = 5; 
  • char: Character type. It can store characters, like ‘a’,’b’,’^’. Actually, it is an integer value, but limited. Every character variable can take only ASCII values. The ASCII tables connects integer values with a charater. For example, the letter ‘A’ , represented in the ASCII table would be 41. Of course, 41 is an integer. So, the char variables take integer values , represented as characters. Declaring a char:
 char letter = ‘A’;
  • float: It reserves memory for decimal, real numbers. Float , actually, is a short of Floating Point. But, float variables has less precision then the double values, which will be discussed after. Float numbers should end with ‘f’ or ‘F’, otherwise, they will be translated as double type. Declaring float number:
float num = 0.2343f;
  • double: This is a very similar type to float. This type of variable is called double, because it has double-precision. It can store the integer and the non-integer values of a number. If you declare a double variable, and specify no decimal part (for ex. 5.0 instead of 5) , that variable will be treated as integer. Declaring a double:
double num = 5.30384;

Strings and arrays will be discussed in the advanced C section in this handbook.

Variable modifiers

There are several variable modifiers, which of course, can somehow modify the preferences of the variable itself. The short and long modifiers are used to shorten or to extend the memory range of the variable. A typical integer occupies 4 bytes of memory, a short integer would take 2 bytes and a long 8 bytes. Of course, the range of the numbers which can be used varies widely between these three types. Declaring:

short int number;
long int num;

As you might well know, numbers can have also signs, positive or negative. Because of that, unsigned and signed modifiers exist. If some variable always holds positive data, you should use unsigned keyword and with that you increase the limit of the positive numbers which can be reached through that variable. The signed variable can take negative and positive values. By default all variables are signed. Declaring:

unsigned int number;
signed int num;

Note: int num equals to signed int num;

There is another important modifiers and that is the const modifier. It is used to declare constant values, variables which will never change its value. A good example of that would be the number pi, which has value 3.14. Declaring:

const double pi = 3.14;

There are a lot of others modifiers, like static, register, extern, but they will be discussed later.

Functions

Function is a grouped source code, surrounded by brackets ({}), in order to do something useful. When i say grouped source code, i mean that every expression, every variable in some functions works to get that function’s work done. In every C program, there must be the main function. In our example program, it is declared as int main(). I am sure you’ve noticed that int keyword before the function name (main). That says that every function has a specific return value. For example, the int main() functions should return integer value as a result. That’s why we use return 0, in line 7. Other possible function would be char return_charater(), which of course serves for returning some character, and the result would be character of course, character is the result of function’s digest. The functions names should be clear, easy understandable and must correspondent with the job of the function. Preferably, it should not take names like a() or c(), because the source code reader would now understand why the function exist. Clear function names help in debugging of the source code later.

Functions take arguments. The function is fed by those arguments, they are the subjects it works with. The arguments, of course, must be from some of the defined variable types. Examples:

int calculate( int num1, int num2);

In this example, we declared a function which returns integer, has name calculate, and has two arguments. The first argument is of type integer and is named num1, the other is also an integer and is called num2. They are used later in the function body. A function body is the source code surrounded by the brackets. An example of a full function follows:

int calculate (int num1, int num2) /*the ret. value, the name and the arguments*/
{ /*starting the body
int result;
result = num1 + num2;
return result; /*this is the return value, of course integer*/
} /*the end of the function body*/

The advanced topics about functions are the discussed in the advanced part of this handbook.

Input and output

So, we have left only line 5 unclear, which says “printf(“Hello World.\n”);”. When we were discussing libraries, i have given an example of the stdio.h header file, and told that it exists to provide input/output abilities to the user.

Output

The printf() function is used to output data to the screen (a.k.a STDOUT – Standard Output). This function takes only one formatted argument. The simplest usage of printf() would be exactly as line no.5 – printf(“Hello World\n”);. Here, the Hello World is printed out directly. But, however, printf() can take other arguments. For example, if we would like to print some variable, named number, and to insert it into the output string , we would do it as follows:

printf(“The number is: %d\n”,number);

We print out the variable value by using a format identifiers. Here is a table of format identifiers:

 %d %i        Decimal signed integer.
  %o	      Octal integer.
  %x %X       Hex integer.
  %u	      Unsigned integer.
  %c	      Character.
  %s	      String. See below.
  %f	      double
  %e %E       double.
  %g %G       double.
  %p          pointer.
  %n	      Number of characters written by this printf.
              No argument expected.
  %%	      %. No argument expected.

These format identifiers can be used just like the one in our upper example. For example. if we used %x instead of %d, the value of the variable number would have been printed out in hexadecimal form.

Printf has also a number of escape sequences. In our example, that would be ‘\n’. They are character constants, telling the printf that they are not about to be printed out, because they are used for something else. Here is a table of escape sequences and their usage:

   \n 	        Newline
   \t	        Horizontal Tab
   \v	        Vertical Tab
   \b	        Backspace
   \r	        Carriage Return
   \f	        Form feed
   \a	        Audible Alert (bell)
   \\	        Backslash
   \?	        Question mark
   \'	        Single quote
   \"	        Double quote
   \000	        Oct - No one uses Octal unless they have an ICL background...
   \xhh	        Hex number
   \            Preprocessor line continuation, must be immediately followed 
                by a newline.

Input

For input, we use the scanf() function. It allows you to receive data from STDIN (Standard Input), in other words, the keyboard. Take a look at the example:

scanf(“%d”,&number);

The %d is a formatting identifier, already discussed in the printf() section, while number is some variable. So, the scanf() function, expects a integer value, and when it is read from the keyboard, it places its value into number variable. Notice that the ‘&’ sign must be used vefore the variable name, because when the compiler will see that sign will create a pointer to the variable, and will pass the pointer to scanf(). So, every time when scanf() runs, it is given a pointer, where the result of the input is stored.

So, the explanation for our simplest program should be finished, and the program should be easy to understand.

handbook/handbook/programing1.txt · Last modified: 2010/04/15 21:18 (external edit)