Basic C tutorial for non-programmers
Page 1 of 2 12 LastLast
Results 1 to 10 of 12

Thread: Basic C tutorial for non-programmers

  1. #1

    Basic C tutorial for non-programmers

    Basic C programming tutorial




    **Note: this is in NO way a full explanation of the C language, i left some important parts out to
    keep it simple to understand**





    This tutorial is intended to be easy to follow for non-programmers and you will be able to write your own simple
    programs after you finished it.



    The Basics:

    You will need a compiler, a compiler is a program which turns your written code into machine code in such a way
    that the Operating System (Windows/Linux) can understand it and execute it.

    I personally prefer Dev-Cpp for windows, or gcc for linux, almost any linux distibution has gcc in it, and dev-cpp is
    free for download.
    If you happen to have another one, that will probably be fine too, since we will keep it to the basics.

    C is a high-level programming language, meaning it is easy for a man to read but not for the computer, this is the
    reason why you will need a compiler.


    Let's start with some simple code:
    Code:
    #include    	//the standard library for basic input and output functions
    
    int main(void)       	//this is the declaration of the main function, without it a program will not work
    {
    	return 0; 	//return 0 to the Operating system, meaning the program ran as it should
    }
    Now open up your compiler or favorite text-editor and copy the above code to it.
    Save the file as nothing.c and compile it:

    dev-cpp: "file" --> "new source file", copy the code, "file" --> "save as" enter "nothing.c", and press "F9" to build
    and run it.

    gcc: you will have to create this file in a texteditor and save it as "nothing.c", then run "gcc -o nothing nothing.c"
    after you have compiled it, you can run the executable "nothing" by entering "./nothing" in your shell.

    Now you have compiled your first program, if you have run it, you will see that it does absolutely nothing, but it does a
    great job doing that ;-)

    i will explain the code:

    everything what is put behind 2 slashes '//' is comment, the compiler doesn't do anything with it, but it is useful for the
    programmer or someone else who will read your code. So make sure you use a lot of comments in your code.

    #include --> this is the default input output library which contains functions we will need later on.

    int main(void) --> the main function, without it your program will not work. the function is devided in 3 parts:

    int --> meaning that the function will return an integer value to the Operating System.
    main --> the function name itself.
    (void) --> the parameters which the function needs to execute, "void" means empty, no parameters.

    as you can see in the main function, we have these symbols {}, those are used to state the beginning and the end of the
    function, without it your compiler would not know where the function starts and stops.

    return 0; --> return the integer value 0 to the Operating system, since we have stated this in the function
    declaration. as you can see we have ; at the end of the line, this is to state that this "command"
    will end there. you need these, otherwise your compiler would not know where the "command" stops.

    This was our first program, now lets start with another one, the famous "hello World!" program:
    Code:
    #include  		//here we have the library again needed for the default input and output functions
    
    int main(void)			//the main function, with an integer value as return and no parameters
    {				//opening the main function
    	printf("Hello World"); 	//our first calling to the output function which is in the library 
    	return 0;		//return 0 to the Operating System
    }				//close the main function
    now save the above code as "hello.c" and compile it. If you run it, you will get the output "Hello World" on the screen, WOW!
    note: if you can not see it in windows, this means the program executes to fast, you will need to open a command prompt and
    run it from there to see the output.

    now let's explain the code:

    #include <stdio.h> --> the library for the basic input/output functions, we have used it now for the printf function

    int main(void) --> the main function

    printf("Hello World"); --> the first function we use from the stdio.h library, it can be used in several ways, but here
    we use it to print the string "hello world" to the screen. the quotes are used to tell the
    function we want a string to print.
    return 0; --> return 0 back to the OS.




    The printf function:

    Now for the next program:

    This one will be a little more complicated, but you will see how easy it is when i explain it.
    Code:
    #include  		//include the standard I/O library
    
    int main(void)			//the main function	
    {
    	char character; 	//declare a variable of type char (can only contain characters).
    	character='A';		//put the letter 'A' in the variable
    	printf("%c",character);	//print the contents of the variable character to the screen
    	return 0;		//return 0 to the OS.
    }
    let's save it as "character.c", compile it and run it.
    hey, it printed the character 'A' to the screen (without the singe quotes).

    explaination:

    #include --> you know this one by now, no need to explain

    int main(void) --> same here

    char character; --> this is new, here we declare a variable of type char (can only contain characters).

    character='A'; --> here we store the character 'A' (without the quotes) into the variable character.

    printf("%c",character); --> here we tell the printf function to print the contents (%) of a variable with
    type char (c), and the variable we will use for this is the character variable which we
    just declared.

    return 0; --> already known by now





    Variables:

    Now that we have used a variable in our previous program, i will try to explain what a variable really is.
    A variable is nothing more then a piece of memory which can contain the data you store in it.
    You can see it like a box, a box where you can put data in.
    the name of a variable can be anything, but there are rules you will have to follow:

    - the variablename can only contain letters,digits and the underscore character '_'
    - the variablename must start with a character


    The type of data you can put into it, depends on the type of variable you declared, there are a couple of different types:

    * char --> this type of variable can contain exactly one character
    * int --> this type of variable can contain an integer number with nothing behind the comma.
    * float --> this type of variable can contain a number with numbers behind the comma, like this: 1234,56

    this list is NOT complete, but it will do for now, all we have left are types of different sizes then the ones above.


    let's write a program then will use all 3 types:
    Code:
    #include  
    
    int main(void)
    {
    	char charac;			//declare a var(iable) of type char with name "charac"
    	int number;			//declare a var of type int(eger) with name "number"
     	float comma_number;		//declare a var of type float with name "comma_number"
    
    	charac = 'B';			//put the value 'B' in the variable
    	number = 12;			//put the value '12' in the variable
    	comma_number = 1234,66;		//put the value '1234,66' in the variable
    	
    	printf("%c"charac);		//print the contents of the variable charac of type char on the screen
    	printf("\n");			//print a newline on the screen (go to the next line)
    	printf("%d",number);		//print the content of the variable number of type int to the screen
    	printf("\n");			//print a newline on the screen (just like we did above)
    	printf("%f",comma_number);	//print the content of the var comma_number of type float to the screen.
    
    	return 0;			//return 0 to the OS.
    }
    as you can see we need to specify the type of variable we want to print out, as well as the name of the variable.

    here are the types:

    type char --> %c
    type float --> %f
    type int --> %d
    type string --> %s

    there are more of these, but these will be the ones we will be using in this tutorial.

    you will probably be wondering, type string??? what the hell is that??

    well, a string is NOT a type of variable, it is simply an variable of type char which can contain more then one character.
    you can declare it like this:

    char string[]="Hello World";

    now we have declared a variable which can contain multiple characters, let's use the printf function to put it on the screen:

    printf("%s",string); // we give printf the parameters %s and string, the first is the type and the second the name.


    you call this variable an array since it can contain more then one character (i'm not getting into arrays, this is a
    basic tutorial, just remember they exist).



    User input:

    Now that we have gotten so far, let's talk about user input, cause after all, what would a program be if you aren't able to
    alter the output?

    user input can be done in almost the same way as printing text to the screen with the printf function, except this time we'll
    use the scanf function:

    scanf("%d",&number); see how it looks like the printf function? this code tells the compiler to scan for an integer
    value (%d), and store it in the variable number (&number), the only difference with printf is that
    you need to put the and & character before the name of the variable, this is because it puts the data
    into a memory address, and it needs to know where that address is, &number means:
    address of the variable number.

    if you would like to scan for a character, this would be the code:

    scanf("%c",&charac);

    there is only one difference with wanting to scan for a string:

    scanf("%s",string); see how the name of the variable is missing & in front of it? this has to do with pointers, don't
    worry about that for now, just remember that you do not need the & character to scan for a string
    but you DO need it for every other variable.


    Example program:
    Code:
    #include 
    
    int main(void)
    {
    	char name[80]; //we need to give the size (80) of the variable since we do not store anything in it at this time 
    	printf("Enter your name: ");	
    
    	scanf("%s",name);	//now lets scan for your name
    
    	printf("Hello %s, how are you?",name);	//now we use the variable to put your name between the rest of the text
    						//and print it to the screen
    
    	return 0;
    }
    save the code as userinput.c and compile and run it, you will be asked for your name, after you have pressed enter, the
    program will print out your name in a sentence.





    Calculating with variables:

    What good would a variable do if you could only store something in it, but are not able to do something else then print
    the values to the screen? nothing!

    so let's talk about making them useful:

    the following characters are used to calculate with variables/values:

    * --> the multiple character
    / --> the devide character
    + --> the add character
    - --> the substract character
    % --> the modules character (modules is the remainder after deviding one value through another: 12 % 5 = 2 and 5 % 2 = 1 )

    we will write an example program to show this:
    Code:
    #include 
    
    int main(void)
    {
    	int a;
    	int b;
    	int temp;
    
    	printf("Enter first value: ");
    	scanf("%d",&a);
    
    	printf("\nEnter next value: ");
    	scanf("%d",&a);
     
    	temp = a + b;
    	printf("\na + b = %d",temp);
    	
    	temp = a / b;
    	printf("\na / b = %d",temp);
    	
    	temp = a * b;
    	printf("\na * b = %d",temp);
    
    	temp = a - b;
    	printf("\na - b = %d",temp);
    
    	return 0;
    }
    now compile it and run it.

    as you can see we did some calculations with the values you've entered. Cool!


    We can also calculate this way with characters since a character value is also a decimal value:
    Code:
    #include 
    
    int main(void)
    {
    	char my_char = 'A';
    	
    	my_char = my_char + 1;
    	
    	printf("%c",my_char);
    	
    	return 0;
    }
    compile it and run it. you will see that although we've put the value 'A' in the variable, the output is the character 'B'.
    now why is this?
    the character 'A' is the same as the decimal value 65 in the ASCII table, and the character 'B' has value 66, so 65+1=66.





    Letting the program decide:

    We also would like the program to make decisions for us, since it would be pretty boring if the program always would
    run the same way.

    we have multiple ways to let the program decide, but we will stick to the if statement in this tutorial.


    here's the code:

    Code:
    #include 
    
    int main(void)
    {
    	int a;
    	int b;
    	
    	printf("Enter first value: ");
    	scanf("%d",&a);
    
    	printf("\nEnter second value: ");
    	scanf("%d",&b);
    
    	if( a > b)		//if value in var a is bigger then the value in var b then 
    	{
    		printf("\nfirst value is bigger then the second");
    	}
    	
    	if( a < b )		//if value in var a is smaller then the value in var b then 
    	{
    		printf("\nsecond value is bigger then the first");
    	}
    	
    	if( a == b )		//if value in var a is equal to the value in var b then 
    	{
    		printf("\nfirst value is equal to the second");
    	}
    	
    	if( a != ) 		//if value in var a is not to equal the value in var b then 
    	{
    		printf("\n first value is not equal to the second");
    	}
    
    
    	if( a <= b )		//if value in var a is smaller or equal to the value in var b then 
    	{
    		printf("\n first value is smaller or equal to the second");
    	}
    
    	if( a >= b )		//if value in var a is bigger  or equal to the value in var b then 
    	{
    		printf("\n first value is bigger or equal to the second");
    	}
    
    	return 0;
    }
    now compile it and run it, as you can see depending on your input there will be multiple lines printed to the screen.

    this is the end of what we will learn in this tutorial, if you have mastered all what is told here, then i suggest you
    go to this site as it contains a lot more tutorials
    for the C language.

    you should now be able to write your own simple programs.

    i hope this was helpful to you and please let me know about your comments / suggestions.

    my email: wscorpion(at)gmail(dot)com


    ps. i have attached this tutorial in html form as it will be on my site as soon as i have it up and running


    regards,

    White Scorpion

  2. #2
    AO Antique pwaring's Avatar
    Join Date
    Aug 2001
    Posts
    1,409
    Nice tutorial, just one small point - you don't need the void in int main(void), just int main() will work.
    Paul Waring - Web site design and development.

  3. #3
    maybe it will, but it is not correct language.

    also
    Code:
    main()
    {
           printf("hello");
    }
    will work, but it is a bad coding habit, so i put the void in there on purpose, cause this tutorial is meant for people who haven't programmed ever before, and why start with basically wrong syntax just to prevent to type more then absolutely neccessary?

  4. #4
    AO Antique pwaring's Avatar
    Join Date
    Aug 2001
    Posts
    1,409
    Actually, it is the correct syntax. If you read the standards you will see that the only two valid ways of declaring main are:

    int main() {}
    int main (int argc, char *argv[])

    main() will NOT compile if you use all warnings enabled, although the C standard does specify that function types default to int if not specified. However, void is completely optional when it comes to parameters and main() is the same as main(void) except it's less typing and more obvious that the function doesn't take any parameters (in my opinion).
    Paul Waring - Web site design and development.

  5. #5
    5.1.2.2.1 Program startup

    [#1] The function called at program startup is named main.
    The implementation declares no prototype for this function.
    It shall be defined with a return type of int and with no
    parameters:

    int main(void) { /* ... */ }

    or with two parameters (referred to here as argc and argv,
    though any names may be used, as they are local to the
    function in which they are declared):

    int main(int argc, char *argv[]) { /* ... */ }

    or equivalent;8) or in some other implementation-defined
    manner.
    source

    well, i did a little research, and as you can see, it is preffered to use main(void) if not using arguments.

  6. #6
    Senior Member
    Join Date
    Mar 2004
    Posts
    557
    Hi

    Amazing how one can elaborate such a thing

    A question: I use, very often,
    Code:
    void main(){
      ...
    }
    I assume, that's horrible programming style ?

    Cheers
    If the only tool you have is a hammer, you tend to see every problem as a nail.
    (Abraham Maslow, Psychologist, 1908-70)

  7. #7
    Antionline Herpetologist
    Join Date
    Aug 2001
    Posts
    1,165
    Code:
    void main()
    {
    ....
    }
    Is considered bad programming because the ANSI C standard specifies that the return type of main() must be int. However, most compilers will let you off with a warning.

    Cheers,
    cgkanchi
    Buy the Snakes of India book, support research and education (sorry the website has been discontinued)
    My blog: http://biology000.blogspot.com

  8. #8
    Senior Member
    Join Date
    Feb 2004
    Posts
    620
    Pretty good tut for beginners. The layout is good.


    I usually do it like this.

    Code:
    int main()
    {
    	printf("Hello, world!\n");
    	return 0;
    }

  9. #9
    Banned
    Join Date
    Jun 2003
    Posts
    1,302
    I have but one question, does it really matter, at anyway will it optimize your code more, if it is Int over Void?


    Is anything better, about using one over there other?

    If not, why does it matter.

    As for the tutorial, not bad

    However, you should probably of explained how conditionals work better.

  10. #10
    i understand what you mean whizkid2300, but that goes for about every part i have discussed, i also wanted to talk about loops, arrays, pointers, structs etc.. but this would make the tutorial so long that it would look more like a book then a tutorial and it would be (IMO) a little harder to memorize by a real newbie... but i will look at the conditional part again, and see what i can do about it


    I have but one question, does it really matter, at anyway will it optimize your code more, if it is Int over Void?


    Is anything better, about using one over there other?
    the only thing what would be better:
    some compilers might complain about the return type, and perhaps some compilers might complain about the arguments missing (even void missing), so i just don't take no chance since i want my code to be useable on as many compilers and operating systems as possible.

    but why do i get the feeling i do not need to tell you this whizkid2300??? i think you have more experience with C or programming in general as i will for a long time

Posting Permissions

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