Tuesday, November 15, 2011

I Want to Learn Programming, but I Know Nothing!

I want this post to be a great resource for people who have absolutely zero knowledge of programming to be able to pick up and start coding in the language C. I feel I have a fair level of empathy for those just starting to learn (since I started learning not too long ago), and want to write this post out before I get too competent as a programmer and forget my empathy altogether!

So you want to learn to program. Great! So you're reading this article, and here you'll learn to start with C on a Windows Operating System. Starting with C is an excellent place to start, as it grounds you with a very solid base of understanding for programming in general, that of which I feel is easily transferable to other languages. I even feel that once you learn the basics of C and transfer to another language (I recommend Python!) you'll be better off in the long run than if you started with another language and then moved to C (perhaps start with Java and move to C). I won't get into deep details about this point as that's out of the scope of this article, but you should definitely take my word on the matter.


Be aware that I'm going to use a lot of new and scary programmer terminology in this post, like statements, declarations, and initialization. Don't be afraid, as I give a link to the definition of words when I first use them. Read the links and make sure you understand what I'm referring to.

The programming in C that I'll be teaching you, as an absolute beginner, will be of the following steps:
  • Write code
  • Compile code into an executable
An executable is a .exe file that your computer can run, and when this executable file is run your computer will actually follow the steps you wrote in your code, thus running your code as a program. Compiling your code is actually a step that a compiler does for you, in which it translates your C code into machine code. Machine code can be viewed as a lot of very hard to read 1's and 0's, also known as binary. The reason people don't code directly in machine code is because it's so hard to read. C is a nice translation of machine code for people to work with. If you want to learn more about how computers work on a very low level, I suggest reading Code: The Hidden Language of Computer Hardware and Software by Charles Petzhold.

You can write your C code in any text editor you like. You can just simply use notepad (to open hit windows key+r and type notepad, then hit enter), though I recommend using the IDE apart of Visual Studio. Once you write some C code, save your file as a .c file and then use a compiler to turn it into a .exe file.


Now what about this compiler business. You might have already googled for a C compiler by now and noticed that there is a multitude of compilers out there. Luckily I have one to recommend to you! Download and install Visual Studio 2010 Express.

When installing you'll be ask if you have a CD. Just say no and download the installation from online. Once you see this screen (mine is reinstalling however):



Be prepared to restart your computer in the middle of the installation. For some reason this installation took a long time, so be patient! After you restart, at the end of the installation it says: requires a key. Go ahead and hit the button to acquire one; you'll need a microsoft address from something like live.com. Once you fill out this lame questionnaire with fake answers copy/paste your key into the box and continue. You're now ready to code your C programs, and compile them.

Now Visual C++ is called Visual C++, but in actuality you'll only be writing C code for now as I recommend avoiding C++ until you're proficient with C. The reasons for this are simple: if you're proficient with C, you understand its limitations. Once you understand C's limitations and hardships, you can better utilize C++.

Now for the fun part, writing some code! I'm simply going to just give you some code to copy and paste into a .c file. Before this you need to create a .c file, however. Go to, in Visual C++, File >> New >>Project. Select Win32 Console Application -this means your application will run in a Windows console. Enter a name and a solution name (probably use the same thing for both), you can call it Test. Hit ok. This part is important, when you see this screen:




Be sure to hit the next button! We need to disable the precompiled header. Hitting next will take you to this screen:




You need to check mark the Empty Project box under Additional options, and uncheck the Precompiled header option. Hit finish! Now you'll see some folders on to your left:




Right click on the Source Files folder (they are actually called filters not folders) and go to Add >> New Item. Click on the C++ file button, enter a filename in the Enter_Name box. Enter in "main.c" without quotes and hit Add. The added .c file should open up! Even though you specified a C++ file, since you named it a .c file it will be for C code. Now lets get to coding! Copy/paste this little bit into your main.c file:

int main(void)
{
  return 0;
}

This code is the minimum requirement for any C program to be able to run. Basically it starts, and then ends. In order to compile this code into an exe, hit Debug >> Build Solution (or F7). You'll see some output form from the compiler in a little box at the bottom of the window It should read:


1>------ Build started: Project: Test2, Configuration: Debug Win32 ------
1>  main.cpp
1>  Test2.vcxproj -> c:\users\cecil\documents\visual studio 2010\Projects\Test2\Debug\Test2.exe
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========


There you go! You've compiled your program. To run it open up the folder your solution is in. To do this you can copy paste the path to the file from your compiler output, as shown in the text above. Once you find your Test.exe (in the debug folder of your solution folder) try double clicking on it. A black box should open and then quickly close. This code starts, and then ends. I'll teach you how to make your program pause until you hit enter later, but for now lets get into the basics of C code syntax.

In C whenever you write lines of code those lines of code are going to be turned into actions that a computer will follow. Whenever you write a statement it must end with a semi-colon ;. The ; is letting the computer know that it has reached the end of a statement. This is important, otherwise the computer running your code could perhaps mix two statements together as a single statement, which would result in strange behavior.

Take a look back at your code you copy/pasted and lets check out what these different lines of code do. int main(void) is setting up the part of your code the program starts at. Every single time any program is ever started that was written in C, it starts at the line with main in it. This line is actually creating what is called the main function. I won't go into detail on exactly what a function is, as all you need to know for now is that this is the first code that is run when your program is started, and then the next line below it will be read then executed, and so on. The open curly bracket { is beginning of the main function, and the } is the end of the main function. For now you're going to write all your code within these two brackets. It's standard C syntax that code within two curly brackets is one tab farther to the right than the code outside of those two curly brackets, which is why the return 0; line is indented. The last thing to explain is this return 0; business. The return 0; line is actually the line of code that ends your program. Once your code is run and this line is executed, your program ends immediately. The 0 is actually a value returned to your operating system letting it know that the program ended successfully. If this sounds confusing, then don't worry about it - all you need to know is that when this line is reached your program ends.

A variable in C is a place in memory that stores a value. There are different types of values that can be stored, and so there are different types of variables to hold those different types of values. I'd like to talk about Integers. For a more complete list of the different types of variables available in C, check out this link on Wikipedia.

Lets start with integers. An integer in C is a whole number value ranging from −2,147,483,648 to 2,147,483,647. In order to create a variable in C of the type integer, you would write:

int myInteger;

This code declares a variable with the name myInteger, and specifies it's type as an integer with the word int. Don't forget your semi-colon to end the statement! Now what is the value of myInteger? Well currently it would have an undefined value since you have not initialized it yet. To initialize myInteger with a value, you can write:

myInteger = 10;

The above code will place the value of 10 into myInteger. Now you can type the word myInteger somewhere in your code, and it will refer to the value inside of it, which is currently 10. The equal sign is actually an operator. An operator in C takes a value and operates on it somehow. The equal sign, called the assignment operator, takes whatever is to its right and places the value of it into whatever is on its left. This means that the following code is invalid:

10 = myInteger;

The above code is invalid because it would be trying to place the value inside of the variable myInteger into 10, which is simply a constant value. Some other operators you can use to manipulate values are: - + * / %. Here is what each one does:

  • - The subtraction operator. Finds the difference between two values.
  • + The addition operator. Finds the sum of two values.
  • * The multiplication operator. Finds the product of two values.
  • / The division operator. Finds the quotient of two values..
  • % The modulo operator. Finds the remainder of two divided values.

What do you think the following code does:

int val;
val = 5;
val = val + 5;

The above code creates an integer variable called val, and then assigns the value of 5 to it in the next line. The last line then assigns the value of val + 5 to val. You can also do the following:

int val1, val2, val3;
val1 = 2;
val2 = 5;
val3 = val1 + val2;

The above code creates three variables all at once within a single line. All three variables var1, var2, and var3 are all of the type integer, as denoted by the int keyword. val1 and val2 are initialized as 2 and 5 respectively, then val3 is assigned the value of the sum of val1 and val2, which is 7. Note that val1 and val2 remain unchanged, as the assignment operator doesn't change anything to the right side of it; it only assigns the value of what is on the right, to whatever is on its left.

Now what if you want to actually see the value inside of a variable? Well then you need to modify your program slightly. Take a look at the following code:

#include <stdio.h>

int main(void)
{
  printf("This is a string!");

  return 0;
}

The above code introduces a couple new things. printf is a line of code that is apart of the C standard library (a bunch of features for you to use as a coder), and it prints a string onto the screen. For now, just know that anything within C code that is within double quotes "" is a string. So if you place text within double quotes, within a printf statement like above, it will be considered a string and printf will place it onto the screen when you run your program. The other new thing is the #include <stdio.h> line. This line of code actually is telling the compiler to include a portion of the C standard library into your .C file, specifically the portion with the name stdio.h. stdio stands for Standard In Out, which is referring to input and output, which is why we need it to output a string onto the screen.

Try compiling and running this code. Sadly, your program opened and then closed very quickly. This is because your program prints the message "This is a string!" and then abruptly reaches the return 0; line and ends. To fix this, modify your code to look like so:

#include <stdio.h>

int main(void)
{
  printf("This is a string!");
  getchar();

  return 0;
}

The line getchar(); is a function from the C standard library in stdio.h. I won't go into the details, as that's out of the scope of this post, but just know that this line waits for the user to hit enter before executing the next line of code, thus letting you read what you output to the screen.

In order to have your value show up on the screen, you need to modify your code slightly:

#include <stdio.h>

int main(void)
{
  int i;

  i = 5;
  printf("%d", i);

  getchar();
  return 0;
}


This new version of the code uses a special character within the string in the printf statement. The %d line is actually saying to place the variable i into the spot in the string where %d is located. %d basically means "insert variable of type integer into this location". You can place more characters before and after the %d, but not in between the percent sign and the d character. This will let you see the value of the integer i on the screen! You can now try more fancy things, here's an example program to calculate the product of two variables and print it to the screen:


#include <stdio.h>

int main(void)
{
  int i, j, k;

  i = 5;
  j = 10;
  k = i * j;
  printf("%d", k);

  getchar();
  return 0;
}

And there you have it! You've now learned how to write a simple program to do mathematical calculations on integers and display a single integer on the screen. Congradulations!

7 comments:

  1. Awesome guide, thank you a lot!

    ReplyDelete
  2. No I don't think it's best. It's just extremely easy to get started with. I think moving from that to GCC or Visual Studio soon after you're comfortable with the idea of making .c files, compiling them, and got some of the basics of programming down is a good idea. I just don't think installing GCC or Visual Studio and learning everything all at once is very smart for a complete beginner, as I tried doing that as a beginner and was overloaded.

    ReplyDelete
  3. yes I did start with dev-c++ too and I think it was really easy to start with, but my friend told me I really should move onto somethin else so I tried bunch of different ones n found all of them extremely hard to get into. Now I write code with notepad++ (just a regular text editor with some features for programmers) and compile with command line with mingw and I love this combination :)

    ReplyDelete
  4. Would you recommend using Visual C?

    ReplyDelete
  5. You mean like Visual Studio? Yeah definitely if you can figure out how to use it! I'll probably be writing additional info on this post about using Visual Studio once I figure it out more (I'm transitioning from linux gcc).

    ReplyDelete
  6. I've heard Visual C is much slower than "normal" C. The reason is that normal C compiles straight to machine code, whereas Visual C compiles to Microsoft's intermediate code (JIT), which then is translated. However, if the game isn't very complicated, it shouldn't be a big deal

    ReplyDelete
  7. Updated for use with Visual C++ 2010 Express! Free version of Visual Studio (still very similar).

    ReplyDelete

Note: Only a member of this blog may post a comment.