Thursday, August 29, 2013

Variable Declaration

Variables are something like a character or word that you use to temporarily store some value.
There are specific types of data that you can store in C Language. A few of them are
integer (int), character (char), decimal number (float), etc...

There's a question in Chapter 2 Page no 89 of the book i mentioned

Code the variable declarations for each of the following:
a. a character variable named option
b. an integer variable, sum, initialised to 0
c. a floating-point variable, product, initialised to 1

Well lets see how to do it:

/*include your necessary headers*/
#include<stdio.h>

/*write your main() function*/
int main()
{
      /*Declare the character*/
      char option;
     
      /*Declare the integer*/
      int sum=0;

      /*Declare the decimal no*/
      float product;
      product=1;

      return 1;
}

You can see how we initialise the variables in two different ways.

  1. You can initialise the variable while declaring it.( int sum=0; )
  2. You can initialise the variable in a separate line after declaring it ( float product; product =1; )
Both will do the job!

A similar question in the same page:

Code the variable declarations for each of the following:
a. a short integer variable named code
b. a constant named salesTax initialised to .0825
c. a floating-point number sum of size double initialised to 0;

Well lets see how to do it:

/*include your necessary headers*/
#include<stdio.h>

/*write your main() function*/
int main()
{
      /*Declare the short integer*/
      short code;
     
      /*Declare the constant*/
      const float salesTax=0.0825;

      /*Declare the floating no of size double*/
      double sum;
      sum=0;

      return 1;
}

That's it! Now we can move on to the next topics.

I made a sample program to show the declaration:


No issues says that it is valid:)
Stay tuned for more!

No comments:

Post a Comment