Saturday 9 February 2013

C programming "Hello world"...detailed example

 


So basically I thought why not to have a mini programming tutorial.The programming language we are going to use is called "C".Not C++ or C#.There is a big enough difference.
First what you are going to need is an IDE(Integrated Development Environment),unless you are pro and can program in notepad or gedit...In that case just skip this post.There are many good free IDE's but I would recommend Devcpp for Windows or Monodevelop for Linux(for Mac idk,try googling "C IDE for mac").Once you have that open a "solution",select "C console project" and give it a name.Click "OK" and double click on main.c and you are ready to go.Erase everything that was in the file because we are going to start from scratch.

"main.c" is very important,because this is the core file of your program and this is the only file of your program that is actually "running".All the other  simply "attach" themselves to main.c when they are needed.

Now write this line into main.c:
#include<stdio.h>
Congratulations,you just wrote your first line of code,you are no longer a programming virgin.#include is the command which "attaches" files into each other.Unfortunately the link is not bidirectional,but you do not have to worry about that yet.stdio.h is called a "header file".You should think of it as "the library that has all the basic C commands".

Now press enter and write this:
int main()
{
int is called a "type modifier".As you progress you will learn more about it.Now,what is a function?A function is a batch of variables and commands and it usually does something.Every C program has a "main" function.It is the central part of every C program.The bracket in this case is the beginning of the function body.
Press enter and write this:
printf("hello world");
printf is the function which is used for telling the program that it should write something on the screen.The brackets and apostrophes are mandatory,whatever is between them will be written on the screen.The ; is used to tell the program that this is the end of that line of code and it is mandatory most of the times.You will learn later where it is not mandatory.
Now press enter and write:
return 0;
}
In this case the return command is used for stopping your program.It has some other uses though.The final bracket is the end of the function body.
Now it should look like this:
#include<stdio.h>
int main()
{
printf("hello world");
return 0;
}
Why all those "enter's"?Because readable C code should expand vertically not horizontally.
Now somewhere in your IDE's menus there should be a "start without debugging" button.Press it.No errors?Good!In the console window that popped up you should be able to read a line that says hello world!

Congratulations you just finished your first program!Now google "c programming tutorials"!




No comments: