Friday, October 21, 2011

Declaration of Variables

The following program demonstrates the declaration of a variable and how it is used in the program :
Program:


#include<stdio.h>
void main()
{
     int i=6,j;
     printf("The value of the variable i is \t%d",i);
     j=8;
     printf("\n The value of the variable j is \t%d",j);
     printf("\n The value of i is %d and j is %d",i,j);
}


In the line 4 'int i=6 , j' means 'i' and 'j' are declared as variables of integer data type. The value of 'i' is initialized to 6.

In the line 5 '%d' used to indicate that the value printed is of the integer data type. Here the value of 'i' is substituted for '%d'. '\t' is used to print a tab space on the screen.

For floating point (decimal numbers) '%f', for characters '%c' and for strings '%s' is used. These data types are discussed later.

In the line 6 the variable 'j' is assigned the value 8

In the line 8, the first and second '%d' are substituted by the values of i and j respectively



Output:

The value of the variable i is 6
The value of the variable j is 8
The value of i is 6 and j is 8

Rules to be followed while declaring variables :
  1. A Variable name may consist of upper case / lower case letters and digits and sometimes _(underscore) too.
  2. It should not contain any special characters except _(underscore). Usage of others for variable names are strictly prohibited.
  3. A variable name must always begin with a letter / _(underscore - sometimes) and strictly not digit.
  4. A variable name should not be the same as that of one of the keywords.
  5. White Spaces are not allowed in a variable name

No comments:

Post a Comment