とらりもんHOME  Index  Search  Changes  Login

とらりもん - C intro 1. Brief introduction Diff

  • Added parts are displayed like this.
  • Deleted parts are displayed like this.

!!Your first programming

First, let's experience C language programming. Launch the console on Linux, input/edit the following program (source code) with the vi editor, and save it with a file name "test.c".

  # include <stdio.h>
  int main()
  {
  printf("Hello!\n");
  }

Note: This is a boring program that only displays Hello! The source code of C language is made with the file name with the extension .c.

Note: Depending on the system, in the printf sentence on the second line from the bottom, symbols between Hello! and n are displayed either as "Japanese Yen" (two horizontal bars in Y) or backslash (from upper left to lower right straight line). These are the same characters in the computer, and either one can be used. You can find the key at the upper right of the keyboard (next to back space).

* '''Q:''' I have typed in, but I do not know the meaning of each. What is include or int?
* '''A:''' For now, it's ok that you don't know the meaning. Let's get experience of "C language" like this little by little.

After you complete it and save it, let's compile this source code. To do that, you can type the following command on the shell command line (type in the part after $):

command 01 $ gcc test.c

* '''Q:''' What is gcc?
* '''A:''' It is a command to run a compiler which converts a C language source code to a binary code.

* '''Q:''' I got an error message like "gcc is not installed yet"!
* '''A:''' You should install gcc by $ sudo apt-get install gcc

If you have a bug in your source code, it makes an error during compile. In such a case, you correct the source code. Check the error messages and the line number of the error.

Once you eliminate all bugs, you get no error messages during compile. Then check the new file which has been created by the compiler:

command 02 $ ls -lt | head

Then you will get like this:

  -rwxrwxr-x 1 nasahara nasahara 8600 Oct 26 06:43 a.out*
  -rw-rw-r--  1 nasahara nasahara 55 Oct 26 06:42 test.c
  ....

This command 02 ($ ls - lt | head) is very useful in programming. This is to display the files in ascending order (ls -t option), including creation date and time and file size (ls -l option), and display only a few of them (head command). This shows that the files test.c and a.out are newly created, and you can see that a.out is newer than test.c.

* '''Q:''' Why not "ls" or "ls -l" instead?
* '''A:''' It's ok, but it may sometimes be messy if you have many files in a directory. Moreover, it is very important to check the timestamp of the file. By doing this, you can avoid confusions of old files or unsuccessful result of compile. It is the reason of the "-l" option.

Thus, in programming, it is important to frequently check the created file (the latest file). By doing so, trace in the head "What has made what".

Actually, "a.out" is a file created with the command 01. The gcc command (compiler) makes the result (binary code) a file named a.out.

* '''Q:''' What is the meaning of "a.out"?
* '''A:''' I don't know.

Then let's run this a.out by:
command 03 $ ./a.out
Then you will get
Hello!
on the display.

* '''Q:''' What is "./" in the command 03?
* '''A:''' It is a path of a.out file. When you execute (run) a binary file, you need to give its path to the shell. Because "./" is the current directory, "$ ./a.out" means "please run a.out in the current directory".
* '''Q:''' Just "$ a.out" does not work?
* '''A:''' Try it. Perhaps you get an error message.

!!If something wrong?
If something goes wrong so far, in many cases, you are making a mistake somewhere. For example, in the first line of the source code:
  # include <stdio.h>
you may imagine "studio" instead of "stdio", and you may type:
  # include <studio.h>
then you get an error. "stdio" is not "studio"!

* '''Q:''' What does stdio mean?
* '''A:''' "standard input output". You know about it if you understand the basics of Linux.

If you can not find a bug, try copying the above program. If you get still some errors, it is possible that you made a mistaken for a part other than the source code, for example compile or execute command, or gcc is not in your computer, etc.

Note: Copy-and-paste is inherently not good at education. Even if it is troublesome, let's type one source code one by one. Copy is easy but nothing remains in the head.

!!Let's make various remodeling

Once you have something which works, try and enjoy various remodeling based on it. Not to be taught, but to discover by trial and error on your own! It is the best way of improving your programming skills. For example, let's do the following tasks by modifying the above source code:

* '''Exercise 1-1''' Display "Good bye!" instead of "Hello!"

* '''Exercise 1-2''' After "Hello!", display "Good bye!". (Hint: one more line with printf somewhere)

* '''Exercise 1-3''' Delete "\n".

Note: You will execute similar commands many times, so you should use the shell's history function (the keyboard's ↑ and ↓ keys to recall and reuse commands in the past).

With these three tasks, do you understand that printf is a command to display some sentences, and \n represents a linefeed?

Then let's play a bit more. I want you to do the next task:

* '''Exercise 1-4''' Delete the semicolon (;) at the end of "printf("Hello!\n");"

In this exercise, you will get an error message :
test.c: In function ‘main’:
test.c:5:1: error: expected ‘;’ before ‘}’ token
  }

It is a confusing message, but we can translate it as "You may need a ; before the symbol } in the first letter of the fifth line in function main in test.c" In other words, you got an error on deleting the semicolon. As you can see from here, it seems that it is bad to cut down semicolons in C language.

Now let's try the same command again as command 02:
command 04 $ ls -lt | head
-rw-rw-r--  1 nishida nishida      54 Oct 26 06:50 test.c
-rwxrwxr-x  1 nishida nishida    8600 Oct 26 06:47 a.out*

Please compare this with the result of command 02. Do you notice the following differences?
* a.out comes after test.c
* file size of test.c decreased.

* '''Exercise 1-5''' Explain why these changes happened.

This exercise may not be that difficult. Because the semicolon was deleted in assignment 1-4, the file became smaller by one semicolon. Also, since compilation after that change failed (error got out!), "a.out" was not recreated and the old "a.out" that was made a while ago remained.

Please correct the error that occurred in assignment 1-4 and then do the next task after that:

* '''Exercise 1-6''' Instead of command 01, try:
command 05 $ gcc test.c -o test
Check the result by command 02 and consider what happended.

Perhaps you have already understood. Rather than reading explanations or listening to instructions, it is faster to think and understand by trials and errors following your own ideas.

!!Basics of a source code of C language

Let me explain a bit about the details of the source code ↓ typed in earlier. The number at the far left is the line number, which is not in the original source code, but for the sake of explanation it is added here.

  1. # include <stdio.h>
  2. int main()
  3. {
  4. printf("Hello!\n");
  5. }

* The first line means "Please use standard input / output with this program" (If you want to know more in detail, try searching by "stdio.h"). Since ordinary programs do some input or output (in this case display as Hello!), This #include <stdio.h> is at the top of the source code of most programs. Well, it is like a promise or a pillow. When I decided to write the C language source code, first I opened the editor and hit #include <stdio.h> and I start thinking what next.

* The second line is also "a promise" of C language. The "main" is the main body of this program (more specifically, the source code of C consists of a collection of things called "functions", among which the main body functions I say main (), but now you should not mind that). The "int" in front of "main" has also a meaning but you do not care about it for the moment.

* The { in the third line and } in the fifth line are a pair. These represent the range that describes the contents of main (). In general, in C language, the part between { and } is treated as one block. Beginners are often worried about errors due to misaligned correspondence (eg forgetting to add the last }).

!!Let's try a more complicated program

Input and edit the following program (source code) with the vi editor and save it with the file name of add.c.

  /* add.c */
  /* 2017/02/18 K. Nasahara */
  # include <stdio.h>
  main()
  {
  int x, y, z;
  printf("What is x? ");
  scanf("%d", &x);
  printf("What is y? ");
  scanf("%d", &y);
  z=x+y; 
  printf("x+y= %d\n", z);
  }

This is a program which calculates and displays the sum when two integers are input by the user. After inputting, compile it with the following command:

command 05 $ gcc add.c -o add

As you learned in Exercise 1-6 above, you can specify the file name of the binary code you want to generate after -o option. Then a binary code will be created with that file name instead of "a.out". Here we use "add" as the filename of the binary code.

When the compilation completes successfully (without error), let's check the fresh binary code (a file called add) with $ ls - lt | head. If you can confirm it, let's run it:

command 06 $ ./add

Then, you will be asked:

What is x?

then, give your favorite numbers (such as 2) with a keyboard and hit enter key. Then you will be asked again:

What is y?

you should input another number (sunc as 8), then you will get

x+y= 10

If it does not go well? ... If the program does not run well and it does not stop running, do not panic, hold down the CTRL key (lower left of the keyboard) and press the C key. Execution of the program is forcibly interrupted and you can return to the prompt.

Here is the program you just experienced with line number and explanation:

    1. /* add.c */                  // comment
    2. /* 2017/02/18 K. Nasahara */ // comment
    3. # include <stdio.h>          // read a header file of a library
    4.                              // blank. not necessary.
    5. main()                       // start of the main body of the program
    6. {                           // start of a block (pair with line 14)
    7. int x, y, z;                 // declaration of variables x, y, and z
    8. printf("What is x? ");       // display a message on a screen
    9. scanf("%d", &x);             // get a value of x from the user
   10. printf("What is y? ");      // display a message on a screen
   11. scanf("%d", &y);            // get a value of y from the user
   12. z=x+y;                     // do addition and store the result in z
   13. printf("x+y= %d\n", z);     // display a message and the result stored in z
   14. }                           // end of the block

line 1-2: The part between /* and */ or the lines staring by // are comments for people (not for computer). The computer ignores them. Let's always put your name and date at the head of your source code. After this, please replace them by your name and today's date.

* '''Q:''' Because it is a comment, we can erase it, right?
* '''A:''' Yes. Try!

'''Exercise 1-7'''. Modify this program to give you multiple of two numbers.

'''Exercise 1-8'''. Modify this program to give you summation of three numbers.

[Go back to [[C language introduction]]]