Thursday, March 4, 2010

C Programming Language - Variables and Operators

I introduced you to the C programming language and showed how to print something on screen in the last post. Now, I'm going to show you how to store data in variables, do operations on them, and print what's in those variables on screen.

Variables
What is a variable? You can think of it as a storage unit or like the letter x in math. Click here for a very detailed description of variables if you're interested. Variables have different types. Each type can hold a different type of value. For example, int holds integers and float holds floating points which are decimal numbers and there's also double which is like float but it has more digits which are useful in scientific applications and finally there is char which holds single characters. Here are their ranges.


char
-128 to 127
Int
-32768 to +32767
float
3.4 e-38 to 3.4 e+38
double
1.7 e-308 to 1.7 e+308


Now, you can either open our cHelloWorld project and delete the printf line or start a new project. If you're wondering why there's a "c" in front of "HelloWorld", the answer is I use Hungarian notation in which types are attached to names, in this case "cHelloWorld" means HelloWorld is a C language project and now maybe you're wondering why the "c" is a small letter. It's a naming convention called  lowerCamelCase. Oh, one last thing about naming, variable names can't start with non-alphabetic characters.


So our program looks like this now.


First of all, we will declare and define a variable. So write this line of code above the line "return 0;"

    int intFirstVariable = 0;

Here, the equal sign assigns 0 to our variable so "=" is the assign operator. So what does this line do? It allocates enough space to hold an integer value in memory and associates that location's memory address with the variable "intFirstVariable" and assigns the value 0 to it. You don't need to think about memory addresses for now. So why assign 0 to the variable? We could have just declared it like "int intFirstVariable;" and left it like that and assigned a value later on but in big and complex programs, if you use a variable which isn't defined then your program may crash because any value could be sitting at that memory location.

We declared and defined a variable, now what? Now we will learn how to print a value stored in a variable, on screen. So go ahead and write this line of code under the variable definition.

    printf("Value stored in the variable intFirstVariable is %d\n", intFirstVariable);

If you compile and run this program, you should see "Value stored in the variable intFirstVariable is 0" in the console (the black box) which is the value we assigned to our variable. The printf function prints a stream on screen so here by writing "%d" we are telling the function there is going to be a value from an integer variable in the stream and we tell the function what variable that is after the comma. If you declared another variable called intSecondVariable and assigned a value to it, you could display both of them on screen so let's do that. 


Write int intSecondVariable = 1; under the first one and change the printf function as the following one.


    printf("Value stored in the variable intFirstVariable is %d\nValue stored in the variable intSecondVariable is %d\n", intFirstVariable, intSecondVariable);

If you want to display more integer variables then you just add "%d" to where you want but be careful about where you write variable names after the first comma because they will be replaced with those "%d"s in that order.

So our program looks like this now (I won't show #include directives from now on because they come by default)


    int main()
    {
         int intFirstVariable = 0;
         int intSecondVariable = 1;

         printf("Value stored in the variable intFirstVariable is %d\nValue stored in the variable intSecondVariable is %d\n", intFirstVariable, intSecondVariable);

         return 0;
     }

There are different special characters for different variable types. They are called specifiers. For example integers get replaced with "%d", floats and doubles get replaced with "%f" (if you want to show certain number of digits in the decimal part, you can use "%.2f" which means there will be 2 digits in the decimal part), and chars get replaced with "%c".

Operators
There are different types of operators. I will show you the arithmetic ones in this post. Some of them are just like the basic operators in math which are add, subtract, multiply, and divide. Let's use them. Change intFirstVariable's value to 1, intSecondVariable's value to 2 and declare a float variable called floatResult under them and assign it to 0.0 then write the following just under the first printf.

    floatResult = intFirstVariable + intSecondVariable;
    printf("intFirstVariable + intSecondVariable = %.1f\n", floatResult);
    floatResult = intFirstVariable - intSecondVariable;
    printf("intFirstVariable - intSecondVariable = %.1f\n", floatResult);
    floatResult = intFirstVariable * intSecondVariable;
    printf("intFirstVariable * intSecondVariable = %.1f\n", floatResult);
    floatResult = (float)intFirstVariable / intSecondVariable;
    printf("intFirstVariable / intSecondVariable = %.1f\n", floatResult);
    floatResult = intFirstVariable % intSecondVariable;
    printf("intFirstVariable mod intSecondVariable = %.1f\n", floatResult);


Why use float? It was unnecessary for the first three and the last operations because we added, subtracted, multiplied and took modulo (remainder of division of two numbers) of integers (whole numbers) but in the fourth operation, we divided one of them by the other one and in this case, it was 1 divided by 2 which is a fraction so in order to show that the result for this is 0.5, we need to use a float type variable. What did that (float) do? (float) casted intFirstVariable to float type so we would get a float result from an integer division. If we didn't cast one side of the division, we would get 0.0 as the result. Type name in parentheses followed by a variable is casted to the specified type.

The ones I wrote about were binary operators. There are other arithmetic operators which work as shortcuts.

Unary Operators
    +intFirstVariable; means intFirstVariable = 1 * intFirstVariable;
    -intFirstVariable; means intFirstVariable = -1 * intFirstVariable;

Assignment Operators
    intFirstVariable += 5; means intFirstVariable = intFirstVariable  + 5;
    intFirstVariable -= 5; means intFirstVariable = intFirstVariable  - 5;
    intFirstVariable *= 5; means intFirstVariable = intFirstVariable  * 5;
    intFirstVariable /= 5; means intFirstVariable = intFirstVariable  / 5;
    intFirstVariable %= 5; means intFirstVariable = intFirstVariable  % 5;

Prefix and Postfix Operators
    intFirstVariable++; means intFirstVariable = intFirstVariable  + 1;
    ++ intFirstVariable; also means intFirstVariable = intFirstVariable  + 1; but in this case, the operation is performed before. I will write about this when we get to loops.
    intFirstVariable--; means intFirstVariable = intFirstVariable  - 1;
    --intFirstVariable; also means intFirstVariable = intFirstVariable  - 1;

I will write about logical operators in the coming post. If you want to go ahead and take a look at all the operators, click here.

So our code looks like this now


and works like this.

Wednesday, March 3, 2010

Introduction to C Programming Language - Hello World!

Before I start, I want to say "Hello World!" in English first. This is the first post for this blog and my purpose is to introduce readers to the C programming language. I don't claim to be the best teacher or I don't claim that you'll learn everything about C in this blog but I'll try and do my best, after all, I'm a first year software engineering student.

First of all, you'll need a compiler (if you don't know what a compiler is, click here). I use Net Beans IDE for C programming, it can also be used with several other languages. You can download it here. Choose the 30mb one that has C/C++ or choose the 288mb one that has all supported languages if you like. The latter is good to have if you're planning on learning other languages in the future.

After installing Net Beans, open it and go to "File" and click on "New Project" then from categories, choose "C/C++" and from projects, choose "C/C++ Application", click on "Next", name your project, choose a location for it and from the drop-down box, choose "C" and click on "Finish". Then, from the solution explorer box on the left of Net Beans IDE, click on your project's "Source Files" node, then double click on "main.c". Click on the image below to see the steps.


Everything in C programming language is case-sensitive, so be careful about that. A and a are not the same.

// Two slashes next to each other mean a comment line 
// and this line will be ignored by the compiler

/*
These mean that anything in between is a comment and will be ignored by the compiler

*/


/* Apparently, I can't use pointy brackets in a post so I'll use screenshots of them. */
#include  /* # sign is a directive for the compiler and this is basically telling the compiler to include the stdio.h (standard input/output) header file to our code. We include header files that contain useful functions for us. Click here to see what function means in detail. */
#include  /* stlib means standard library, the .h extension means header file. */

int main()  /* Every executable program must have a main function, this is where a program begins to execute. int means an integer and in this context, it means the return type for this function "main" is an integer */
{ /* Curly braces indicate beginning and ending points of a scope. Click here to see what a scope is. They basically show where something's domain or area begins and ends. In this case, the opening curly brace means the domain of function "main" has begun. Every line in between these curly braces under the function "main" will be executed when the function "main" is called and the function "main" is going to be called by the OS (operating system) when we run this program */
  
    return 0; /* When you run a program, it is executed line by line. If all the code in the scope of function "main" is executed then the function "main" returns the value 0 to the caller which is the OS. This means the program ran successfully. Don't think that every function needs to return a value for running successfully or not. For example, you can write a function to calculate sum of two numbers and then return the sum. We will discuss this in the coming posts. And, oh, in C and C based languages ";" means end of line, without the quotation marks though.  */
}

So this was the explanation for the code already created by the compiler for us. Remember the #include directives which include header files that contain functions? In the stdio.h header file, there is a function called "printf" which prints strings of text. So we will use a printf function to print "Hello World" on our screens. Let's see how it is used.

#include
#include


int main() 
{
    printf("Hello World!\n"); /* "\n" here is a special character which means a new line. */
    return 0;
}

After writing your printf, hit F6 if you're using Net Beans IDE, this will compile and run your program. It may be a different key in other compilers but you get the idea.

Aaaand... Tadaaaa! You've written your first program in the C language, congratulations!