27 October 2013

Variables in C

Just like any other programming languages, C also has variables.
If you do not know already, a variable is a storage location for several types of values.
There are 4 basic types of variable type specifiers in C, according to Wikipedia :

-char
-int 
-float 
-double

 
which can be combined with optional specifiers :

-signed 
-unsigned 
-short 
-long


In total, there are 28 basic data types in C. Here is the complete list along with the description: http://en.wikipedia.org/wiki/C_data_types

The syntax to declare a variable in C is simple, which is :
data_type var_name = initial_value;
Let's see how we use it in a C source code:

#include <stdio.h>
#include <stdlib.h>

int main(){
//declaring the variables
int a = 5;
int b = 2;
int c = a + b;
//printing the value of c, which is a+b, or 5+2
printf("%d",c);
//printing a new line
printf("\n");
//pausing the program to see the result
system("Pause");
return 0;
}
If you can see, I wrote several lines of words using a "//" sign in front. They are called comments. Comments will not be run by the compiler, they are only used to aid programmers to understand the source code. More about comments in the next post.

From the code you can see that I declared an Integer a with the initial value of 5 and Integer b with the initial value of 2. I then declared another Integer c with the value of a + b. Next, I print out the result, which is the value of c using printf.
You can also use other data types for different operations. Let's do division with integer and float data types for example. Here is the code :
#include <stdio.h>
#include <stdlib.h>

int main(){
//declaring the variables
float a=5;
int b=2;
float c=a/b;
//printing the value of c, which is a/b, or 5/2
printf("%f",c);
//printing a new line
printf("\n");
//pausing the program to see the result
system("Pause");
return 0;
}
The code is pretty much the same, with small modifications here and there.
If you notice, we cannot use integers as the dividend here. Why?
An Integer will always be a non-decimal number, which will give you a wrong result of the division if you declare a or c, or both, as an Integer. Ex : 5/2 = 2.

There you go. Now you can apply variables in your codes. Congratulations !
 


Happy Coding,
Cyber Frost

No comments:

Post a Comment

Search