Pages

Monday, September 21, 2009

Declaring and using variables.

Lets now create some variables and make programs using them. Let's start with a basic addition program. To create a variable first declare the variables by using the following command.


datatype variablename

datatype can be either int(for real numbers), float (for decimal values),char (for single characters)

for example, the statement
int rollno
will declare a variables named "rollno" which can store an integer value, like 1,100,2493,-492 etc. Make sure that the value should not be more than 32767.

void main()
{
int a,b,c;
a=10;
b=20;
c=a+b;
printf("%d",c);
}

Type the whole code in the C editor window. Don't forget to add the includes (#include). After typing the program press Ctrl + F9 so that the program can compile and Alt+F5 to check the output. You will see that the number "30" will be printed on the screen.

Step By Step

  1. The first sentence #include tells the compiler to add or load the header file standard input output(stdio) from the disc to RAM. Whatever you see on the screen is loaded into RAM and then shown, so it neccessary that this file must be brought from the secondary memory to the primary memory. If you fail to add the include statement the compiler will not be able to process the printf(). The "#" sign is called the "Preprocessor Directive" and it tells the compiler to process this statement before anything else.
  2. The line "void main()" denotes the beginning of the program. You can also view it as the entry point of the program. The () denotes that main is a function(more about functions later) while void denotes that it a kind of function which doesn't return a value.
  3. int a,b,c --> are called declarations. Once a variable is declared it is ready to be used. You can define a variable as a temperory location or storage area in RAM which holds the value till a program is running. The name of the variables can be anything provided that you follow the rules of the language.
  4. a=10,b=20,c=a+b --> is called initialization or assignment. Here we are assigning the values to the variables declared in step 3. A is assigned a value of 10 , B is 20 while C will be storing the result of the addition of the two numbers.
  5. As the last step , the value of C is printed on the screen using the printf() statement. The symbol "%d" will not be printed on the screen it is just an identifier which tells the compiler that the value to be printed is an integer value. Instead of %d the value of the variable after the "," which is C, will be printed.
  6. Save the program by clicking on "File--> Save".

0 comments:

Post a Comment