Results 1 to 4 of 4

Thread: C programming for beginners

Hybrid View

  1. #1
    Very good friend of the forum Virchanza's Avatar
    Join Date
    Jan 2010
    Posts
    863

    Default C programming for beginners

    A C program starts out as follows:

    Code:
    int main(void)
    {
        /* Write your code here */
    
        return 0;
    }
    (You can write comments in a C program by using /* and */, as shown above)

    To make an executable file out of this C program, you have to compile it. First off, create a file called "prog.c", then copy and paste the above into it. You compile it as follows:

    gcc prog.c -Wall -ansi -pedantic -o prog

    I'll explain the commandline switches:
    -Wall : This tells the compiler to give every warning possible
    -ansi : This tells the compiler to follow the ANSI standard of C
    -pedantic : This tells the compiler to follow the ANSI standard of C to the letter and to tell you about every little violation your program contains
    -o prog : This tells the compiler that the executable file should be called "prog"

    After you've compiled the program, you'll have a file called "prog". To run the program, just type "prog" and hit Return. (Our program is empty at the moment so it won't actually do anything). For now, that's all you need to know about compilation, so back to the actual programming:

    "main" is a function, and it happens to be the function that is called when the program begins execution. When main finishes, your program is over.

    In computer programming, there is the concept of a "variable". When you define a "variable", you're setting aside a little section of memory to use for storage. For instance, you might want to use a variable to store an integer number. To define a variable, you specify its type followed by its name. So for instance, let's say you want to store an unsigned integer ("unsigned" means that it cannot be negative); to do this you'll want to define a variable of type "unsigned int":

    Code:
    int main(void)
    {
        unsigned int i;
    
        return 0;
    }
    "unsigned int" is the type, and "i" is the name of the variable. In C, the default variable type is "int", so you can shorten "unsigned int" to "unsigned". We can set the value of "i" and also do mathematical operations on it:

    Code:
     int main(void)
     {
         unsigned i;
     
         i = 4;
    
         i = i + 2;
    
         i = i * 5;
    
         return 0;
     }
    (You'll notice in C, every statement is followed by a semi-colon, i.e. ";")

    Some of the built-in types of C are as follows:

    char = Store a character (such as a letter, digit, or symbol)
    int = Store an integer
    float = Store a floating-point number (e.g. a number such as 36.782)

    Let's say we want to write a program to convert Fahrenheit to Celsius. In order to do this, we have to be able to ask the user to input a number using the keyboard, and also we have to be able to print the result to the screen. The "standard library" of C contains functions for doing this. The functions that are involved with user input and output are declared in the header file "stdio.h". In order to gain access to these functions, we have to "include" that header file. Here's a program that will print "I like monkeys" to the screen:

    Code:
    #include <stdio.h>
    
    int main(void)
    {
        printf("I like monkeys\n");
      
        return 0;
    }
    As you can see, you can use the function "printf" to write to the screen, and you enclose the text in inverted commas. In programming, we refer to text as a "string" (reason being that it's a string of characters in a sequence). The "\n" at the end of the string represents a new line. If you don't have a new line at the end of the string, then "printf" might not print the string to the screen right away, instead it will hold the string in a buffer to print to the screen at a later time (e.g. when it encounters a new line). On Windows, "printf" writes to the screen straight away regardless of whether you have the '\n'. On Linux, you need the '\n'.

    In order to read input from the user, you can use the function "scanf". "scanf" can read in all sorts of input from the user, it can read an integer number, a floating point number, a character. For our program to convert Fahrenheit to Celsius, we want to use a floating-point variable to store the temperature. Here's the beginnings of it (complete with line numbers):

    Code:
    0: #include <stdio.h>
    1:
    2: int main(void)
    3: {
    4:     float i;
    5:
    6:     printf("Enter the temperature in Fahrenheit: ");
    7:     fflush(stdout);
    8:
    9:     scanf("%f", &i);
    10:
    11:    return 0;
    12:}
    I'll explain what each line does:
    4: This creates a variable called "i", and its type is "float".
    6: This prints a string to the screen.
    7: As discussed previously, printf might not print to the screen right away if there's no newline, instead it will store the string in a buffer for later. In order to make sure this buffer gets printed to the screen immediately, you can flush the standard output stream; you do this by calling the function "fflush" and passing "stdout" as an argument to the function ("stdout" stands for "standard output").
    9: This line reads in a floating-point number from the user and stores it in the variable "i". The string "%f" looks funny, but it's just how you tell scanf what type you want to read in (if you want to read in an unsigned integer, you do "%u"). Also you might notice that we have "&" before "i", this is called the "address of" operator, and it's used to get the address of a variable ("scanf" wants to know the address of "i" because it wants to store the number in that part of memory).

    So to write our program to convert Fahrenheit to Celsius, we first have to figure out how to actually convert Fahrenheit to Celsius. What you do is as follows:

    1) Subtract 32
    2) Multiply by 5
    3) Divide by 9

    So altogether here's our program:

    Code:
    #include <stdio.h>
    
    int main(void)
    {
         float i;
    
         printf("Enter the temperature in Fahrenheit: ");
         fflush(stdout);
    
         scanf("%f", &i);
    
         i -= 32;  /* Short-hand for  i = i - 32 */
    
         i *= 5;   /* Short-hand for  i = i * 5 */
    
         i /= 9;   /* Short-hand for i = i / 9 */
    
         printf("Answer is: %f\n", i);
    
         return 0;
    }
    You'll see here that we use "%f" again with "printf". Here we use it to print the value of "i" to the screen. When using printf, you don't need to give the address of "i" because printf doesn't need to store anything at that memory address, instead you can just give it the number directly.

    This program we have is a fully-portable program to the ANSI standard of C. What this means is as follows:
    1) It doesn't contain anything that is in violation of the Standard
    2) It will work as intended on every implementation of the ANSI standard of C
    Ask questions on the open forums, that way everybody benefits from the solution, and everybody can be corrected when they make mistakes. Don't send me private messages asking questions that should be asked on the open forums, I won't respond. I decline all "Friend Requests".

  2. #2
    Junior Member
    Join Date
    May 2008
    Posts
    56

    Default

    This is very helpful. Thank you.

    -Josh.
    A+
    Network +
    Security +
    Linux +

    Work in progress: Saving for OSCP

    Currently reading:Hacking-The Art Of Exploitation.

  3. #3
    Just burned his ISO
    Join Date
    Jul 2008
    Posts
    17

    Default

    I think It's better to write the codes in C++ cuz there aren't great differences between C And C++ and The Tutorial to be C/C++ for those who wnat to learn basic structural "C" and object-oriented "C++" programming.
    I have the basic knowlage of both programming languages so if someone needs asisstance im here to help as much as i can.

    btw, Great Topic...

  4. #4
    Very good friend of the forum Virchanza's Avatar
    Join Date
    Jan 2010
    Posts
    863

    Default

    Quote Originally Posted by nCounTr View Post
    I think It's better to write the codes in C++ cuz there aren't great differences between C And C++ and The Tutorial to be C/C++ for those who wnat to learn basic structural "C" and object-oriented "C++" programming.
    Structural programming was born before object-orientated programming. C has built-in functionality for structural programming, but no built-in functionality for object-orientated programming. You can do object-orientated programming in C, it's just not very easy or convenient to do because you've to implement it all by yourself.

    C++ is an extension of C. If C is the "icecream cone", the C++ is "the icecream cone with the flake". So of course, C++ has built-in functionality for structural programming, but it also has "classes" so that you can do object-orientated programming. C++ also has many other features, like templates. Put classes and templates together and you've got an extremely powerful language.

    But just because you're programming in C++, that doesn't mean you've to do things in an object-orientated way. I myself prefer structural programming most of the time unless the problem I want to solve fits very nicely into the whole object-orientated way of doing things. Ever since I took up C for doing embedded systems programming, I've gotten to like structural programming more and more. Still though, I'm fully aware that some things are too much of a nightmare to code in structural programming and are far better suited to object-orientated programming.

    Since C++ is pretty much "C with the flake", you think everybody would abandon C and just use C++. The problem though is that it takes a hell of a lot more work to write a C++ compiler than it does to write a C compiler. If you can only use one language on a particular machine, you can bet it's C. If you're writing something like a web browser, then you should definitely opt for object-orientated programming, but if you're writing a program that performs Network Address Translation then you'll get along just fine using structural programming.

    If you're writing a web browser, you probably don't expect it to run on an 8-Bit microprocessor the size of your thumbnail, so you probably won't be too bothered by only being able to compile it for bigger computers (i.e. computers for which there is a C++ compiler). However if you're writing a program to perform Network Address Translation, it wouldn't be too outlandish at all for this to run on an 8-Bit microprocessor inside a router (especially if you're doing it for a college project ), so in that regard you'd want to stick with C.

    The biggest differences between C and C++ aren't between the actual languages at all though -- it's the way in which they're taught that's different. People teaching C tend to jump right into the nitty-gritty. People teaching C++ tend to do a play-it-safe sort of thing (the list of Frequently Asked Questions for the newsgroup "comp.lang.c++" explicitly says that "pointers are evil" ). If you were to tell a C programmer that pointers are evil, he'd smile.

    The more proficient programmers don't follow the "rules". For instance, I don't do structural programming and I don't do object-orientated programming... I simply pick the right tool for the job at the exact time I need it. Sometimes I write a simple function, other times I write an elaborate class with all sorts of operator overloads, but I never subscribe to one way of doing things.

    I would have written my tutorial about C++, but I didn't want to deprive people of the ability to program for small microchips. For anyone who's interested, here's the Fahrenheit-Celsius program written in C++:

    Code:
    #include <iostream>
    using std::cout;
    using std::cin;
    using std::flush;
    using std::endl;
    
    int main()
    {
         float i;
    
         cout << "Enter the temperature in Fahrenheit: " << flush;
         
         cin >> i;
    
         i -= 32;
    
         i *= 5;
    
         i /= 9;
    
         cout << "Answer is: " << i << endl;
    }
    In C++, you don't use "printf" and "scanf", instead they have new objects called "cout" and "cin" which are easier to use. Also, in C++, you'll see that instead of writing "(void)", you can just write "()". The basic language features are identical though.
    Ask questions on the open forums, that way everybody benefits from the solution, and everybody can be corrected when they make mistakes. Don't send me private messages asking questions that should be asked on the open forums, I won't respond. I decline all "Friend Requests".

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •