-->

Constants and Variables

Constants and Variables in C Programming

Constants and Variables

In a 'C' program, data can exist in two forms: constants and variables
A constant is a variable, whose value does not change. When we are writing a program to find the area of a circle (πr2) , the value of 'π'(3.142) does not change, irrespective of the value of the radius. 
Therefore 'π' is a constant.
In the previous formula, the radius of a circle may be called a variable, since its value differs from one circle to another, the value of the variable changes.

Storing a variable
When a computer has to process a data, it should first store the data temporarily in its memory (Random Access Memory).
A Variable is a name, that is written in the program, to identify a memory location, where the data is stored.
For example, if we are writing a program to find the area of two different circles, the variable radius can take two different values, and hence the name variable.

Rules to follow in Naming Variables
A variable name follows the rules of the identifier
Variables should be named to denote the purpose of the variable.
Example: To represent Radius, the variable name should be radius, r, rad etc.
A variable name should be meaningful and should help in the overall understanding of the program.
Note: Always give meaningful names to variables. If you are writing a program to calculate the average of marks in four subjects, instead of naming the variables a, b, c, d and so on, name them 'marks_C', marks_VB, marks_SQL and marks_Java etc. Meaningful names make it immediately obvious as to what the variables stand for.

Using Variables
Any variable used in the program, must be declared before using it in any statement, It means that we are informing the 'C' compiler, about the kind of data that we want to store in the memory.
A variable is declared, by writing a type declaration statement in the program

Declaring Variables
While declaring a variable:
First, decide the type of variable: integer (int), float (float) or character (char)
Name a variable, so that it clearly states what it stands for, like C, VB, SQL etc. rather than a, b, c.
Syntax: data type variable name;

For example: 
int marks; //declaring marks as an integer
float average; //declaring average as a float
It should be noted that, every executable statement in C, ends with a semicolon.
Note:
In C, all the variables must be declared at beginning or a block.

What is initialization?
Initialization is the process of assigning an initial value, to a data type or a variable
Initialization is useful in programs that manipulate the initial value contained in a variable and results in a different value in the later stage.
Example: If you are writing a program to find the sum of the first 5 natural numbers, you initialize a variable sum to 0 and add it to the remaining numbers, resulting in the final result of 15.


Related Posts

Post a Comment

Subscribe Our Newsletter