×

C VARIABLES


In this Tutorial, we will be learning about Variables in C.


Variable

What is a variable?

Variable in C is a name given to memory location.

Whenever we need to store some information, we store it in some memory locations. So rather retaining a muddled memory address/area like 0x5989848239, we gave a name to such memory address/area. For instance, result, aggregate, and so on. The name is called Variable.

How to declare variables?

We must declare the variable before using it in the program. Whenever you declare a variable, it tells the compiler, that there is a Variable of some Data Type exist. Therefore to declare a Variable in C, follow the instruction below.

Syntax of variable declaration

data_type variable_name;

Data types must be a valid C type like int, float, char, struct and so forth.

For example consider the below variable declarations -

int sum;
char letter;

From the above declaration, the compiler will understand that -

In variable sum, integer type of data will be stored.

Similarly, in the variable letter, a character type will be stored.

Here sum and letter are known as Variables.

How to initialize a variable -

Initializing a variable means storing some data in the declared variable. Below is the example :

Initialization of variable
int variable_a; // Declaration of variable
variable_a = 45; // Initialization of variable_a

Here variable_a is initialized by assigning 45.

Now let's write a simple c program to illustrate the use of variables.

File - variable_example.c
#include<stdio.h>
int main()
{

    int height, width, area; /* Variable declaration */
    height = 15; // initializing height variable with value 15
    width = 10; // initializing width variable with value 10
    area = height * width; // area variable will be initialized to value 150

    printf("Height = %d\n", height);
    printf("Width = %d\n", width);
    printf("Area of rectangle is %d\n", area);
    return 0;

}
Output
Height = 15
Width = 10
Area of rectangle is 150

In the next Tutorial, We will learn about Constants.

Please share this tutorial if you like this