Announcement

Collapse
No announcement yet.

C Tutorial (1 - First Program)

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • C Tutorial (1 - First Program)

    This tutorial is for people new to C or programming.
    In this tutorial we will start from the very basics and create a
    simple program (executable) that will display a message to our
    screen.

    1. Download a development enviroment that will compile our code from
    simple text to and executable. A free one is Dev-C++.
    2. Install it, and in our case (Dev-C++) press CTRL+N to create
    a new source file (its nothing but a white page to write in)


    Type the following (Dont just copy-paste the code, you need to
    type in order to memorize faster and better):

    #include <stdio.h>
    #include <stdlib.h>

    main()
    {
    printf("Hello World\n");
    system("pause");
    }


    Compile and run it (In Dev-C++ press F9)


    1.Lets talk about C in general(you have to read this first and after scroll down to
    see what the code does):
    Info: A C program contains functions. The functions specify the
    tasks to be performed by the program. The "main" function
    establishes the overall logic of the code. It is normally
    kept short and calls *different functions to perform the
    necessary sub-tasks. All C codes must have a "main" function.

    2. A function's structure:
    type name(parameters){code}
    Example:
    int main(a,b){printf("Hello World");}
    But for now (in simple programs like this one) forget about
    type and parametres, and lets keep it simple.

    3. *different functions: in our code the commands printf and
    system are nothing else but "precooked" functions. They are just
    code that has already been written to help us do basic stuff
    like in our code, so we dont have to reinvent the wheel everytime
    we want to print a message.
    Someone, someday was sitting at his computer (lets call him Dennis)
    creating c and said to himself.. "hmm all this "precooked" code must be available
    to everyone using c" and he decided to create a "package or officially a library" called
    stdio.h which means standard input output and it contains
    code that helps you to to print messages(output) and to scan
    for keyboard buttons being pressed(input). So when you see things like
    printf("x"),system("x") dont get confused.. He just wanted to name
    his functions like that and give them this stracture. We just need
    to memorize it. Dennis also created many other libraries!

    Now we are really ready to understand the commands be explaing them
    one by one..


    A) #include <stdio.h>
    #include <> is standard. It informs the computer that
    we are going to use some code from the libray. If we type
    stdio.h in it, like that #include <stdio.h>, we inform the computer
    that we are going to use the library stdio.h which is nothing
    else but the "precooked" code of Dennis(remember?).
    The reason we use it is because we used the command
    printf("Hello World")
    B) #include <stdlib.h>
    stdlib.h contains functions involving memory allocation,
    process control, conversions and others. The reason we use it is
    because we used the command system("pause")

    After we are done with the libraries we are going to use we
    create our main function.
    And we start writing the heart of our program.

    C)printf("Hello World\n");
    printf("") is standard. In "Hello world" goes your text.
    e.g printf("forza motorsport"). The \n right after our text
    is not printed to the screen and it works just like when
    you are typing and you hit enter to move one line down.
    So it moves the cursor by one line. Try removing it and compile
    your program and you well see the results. You can put as many
    as you like e.g printf("\nalcohol\n\n\n\n\n\). The ; MUST be used
    everytime right after a command to inform the computer that
    this command ends exactly where the ; is. The only times you dont
    need to use ; is when you include your libraries and when your
    function ends because in both cases the ending of each one is obvious,
    in our code it might seem like it easy but as we progress you will see
    that unfortunatly is not.

    D)system("pause");

    Although we used this command dont pay too much attention. What
    it does is stop the execution of the code and print a message
    to the screen "press any key to continue.." and only if you
    press a key the code progresses. We used it because in many computers
    when the commands are executed the program closes (it's normal, that's
    what computers do, they just execute commands and they doesn't "care"
    if you will see what they did). System("pause") pauses our
    system so we can see the message we typed in printf, "Hello World".
    Otherwise it would be executed so fast that you would see just a
    quick flash and a programm closing. System("pause") helps us in that case.
    As i said dont pay to much attention to it yet.

    This is the end of the tutorial. Yes, just this little piece of code
    nothing else. I focused and getting you to undestand what is happening
    and not just tell you about it. If you liked the tutorial and i make
    others then you will see that although there will be more
    and more code in them and fewer talking you will feel much
    more confident when looking at it. This mostly theoretical
    tutorial is necessary.

    Last edited by Former92; February 9, 2011, 02:55 PM.

  • #2
    I am interested in learning this language. I'm not very experienced with programing. I've gotten pretty good at html (tables and such - copy and paste) but that has come to a stand still and I don't find it interesting enough to learn css as I would basically be starting all over again with the same language.

    I'm using linux at the moment and I'm not sure how to go about getting starting, what -dev, lib packages to install. Do you have any experience with C++ in linux?

    (I don't mean to "cut corners" by utilizing this forum but in my opinion IRC and Google are mad houses)

    Comment


    • #3
      Im very interested in learning this too

      Thank you for sharing this

      Comment


      • #4
        This brings back a lot of painful memories from when I was first trying to learn it in college .

        Comment


        • #5
          Originally posted by Sever View Post
          I'm using linux at the moment and I'm not sure how to go about getting starting, what -dev, lib packages to install. Do you have any experience with C++ in linux?
          For C you need libc6-dev, for C++ you need libstdc++6-dev. But installing the compiler should automatically install these basic development libraries.

          Comment


          • #6
            Originally posted by Sever View Post
            I am interested in learning this language. I'm not very experienced with programing. I've gotten pretty good at html (tables and such - copy and paste) but that has come to a stand still and I don't find it interesting enough to learn css as I would basically be starting all over again with the same language.

            I'm using linux at the moment and I'm not sure how to go about getting starting, what -dev, lib packages to install. Do you have any experience with C++ in linux?

            (I don't mean to "cut corners" by utilizing this forum but in my opinion IRC and Google are mad houses)
            I'm assuming you're a beginner. Does your system use synaptic (it's the only package manager I'm familiar with)? If so, search for "gcc" and "g++" Download those meta packages, and you should have the required libraries to compile and run anything. If you're searching for an IDE, I'm gonna have to give a plug for Code::Blocks. It's excellent, in my opinion, and is quite easy to start off with.

            Comment


            • #7
              Originally posted by dantearouet View Post
              I'm assuming you're a beginner. Does your system use synaptic (it's the only package manager I'm familiar with)?
              I'm using mint. It's not synaptic to my knowledge but does the same thing. I am definitely a beginner with linux.

              thanks for the help. I have a project for today.

              [edit]yes, it's synaptic :)
              Last edited by Sever; February 20, 2011, 11:06 AM.

              Comment


              • #8
                Originally posted by maverick2001 View Post
                This brings back a lot of painful memories from when I was first trying to learn it in college .
                I really enjoyed learning to program. I started with Pascal, because that's what they first teached us at the University (Material Sciences). On my second year it was C, and that's when I realized everything you could do with few lines.

                Since then I've been trying Delphi, then Visual Basic. I still need (and probably always will) reference books to help me, but I keep programming either for my own interest, or for professional purpose (though I don't work in this area at all). It's good for the brain !
                Last edited by Goman; February 21, 2011, 12:52 PM. Reason: typo

                Comment


                • #9
                  A few comments:

                  1. @Sever, in my experience Linux is the best environment for programming, so you've made the right choice to use it! The C compiler usually even comes installed with all distributions. I suggest you write your programs in emacs, and compile from the command line.

                  2. Don't write main(), write int main(). Main is a function, and so should have a type. While just writing main() will usually work, it is bad form, and there might still be some compilers which wouldn't even work with just main().

                  3. Also, the function main should return a value. By convention, it returns the value 0 if the program executed correctly, and you can use other values for different errors. The operating system catches the return value, and this can then be used to check if the program executed correctly. So in other words, your program should be (just the body):

                  int main()
                  {
                  printf("Hello World\n");
                  system("pause");

                  return 0;

                  }


                  I know this might seem like nit picking, and will not make much difference in this simple program, but it is important to pick up good programing practices from the beginning, so that later you don't have to unlearn any bad habits.

                  Comment


                  • #10
                    @Glanton
                    It's not like nit picking. I will keep in mind what you said, because i totally agree about picking up good programming techniques.

                    Comment


                    • #11
                      I'm going to try those tips. I wrote the program in gedit and compiled it with gcc via command line and when I ran it, it didn't 'end' correctly.

                      but I was proud of it non the less :)

                      Comment


                      • #12
                        hmm. Perhaps you forgot to return 0 at the end? Normally not ending correctly means it returned other than 0, i.e. error.

                        Comment


                        • #13
                          @Sever, actually I just looked at the program again, the system("pause") command will not work in Linux. And even in Windows, it's probably best to avoid it, since it is heavy on resources and not portable to other operating systems.

                          There's a variety of things you can use instead. For this program, since you are running it from the command line, you can just delete that whole line, since it doesn't really do anything important. So for the first program you can write this:

                          #include <stdio.h>

                          int main()
                          {

                          printf("Hello World\n");

                          return 0;

                          }

                          If you do want your system to pause, here is an alternative you can use:
                          Things to Avoid in C/C++ -- system("pause"), Part 4 - GIDNetwork

                          By the way, since you are now using return 0, in Linux to check how your last command executed type

                          echo $?

                          This will show you the return value of the last executed command. By default, the return value of 0 means the command executed correctly. When you start writing bigger programs, you can define your own return values for various errors, and then you will know what caused the error.

                          Comment


                          • #14
                            Afaik, there is no "pause" command in linux. You can use getchar() instead, it should work for both windows and linux.

                            Comment


                            • #15
                              I decided to learn this language. I found some good example programming tasks for beginners on a school's website. Unfortunately I can't get along with them, though I heard that they are really easy. If anyone has some time to help me by writing some code with detailed comments /so I would have a better view about functions and what do they do/ please pm me. I woul really appreciate that. :)

                              Comment

                              Working...
                              X