Declaring and Initializing Variables in C: A Beginner's Guide


A variable in simple terms is a storage place which has some memory allocated to it.Basically, a variable used to store some form of data. Different types of variables require different amounts of memory, and have some specific set of operations which can be applied on them.Here is the simple program variables and literals in C programming.

Syntax:
Datatype variable_name = variable_value;

Example:
To store the numeric value 10 in a variable named "a":
int a = 10;

Variables Rules:

  • Variable name don’t start variable name with digits.
  • Beginning with underscore is valid but not recommended.
  • Special character not allowed in the name of variable.
  • Blank or White spaces are not allowed.
  • Don’t use keywords to name of you variable.

The above code is a C program that declares and initializes variables of different data types, and then it prints the values of the variables using the printf() function. Here is an explanation of each line of the code:

  • int a=10; declares a variable a of type int and assigns it a value of 10.
  • char b='$'; declares a variable b of type char and assigns it a value of '$'.
  • float c=12.5f; declares a variable c of type float and assigns it a value of 12.5. The letter f at the end of the number is used to indicate that this is a float value.
  • long int d=2582l; declares a variable d of type long int and assigns it a value of 2582. The letter l at the end of the number is used to indicate that this is a long int value.
  • int aa=0x41; declares a variable aa of type int and assigns it a value of 0x41. The prefix 0x is used to indicate that this is a hexadecimal value.
  • float cc=253e-2f; declares a variable cc of type float and assigns it a value of 253e-2. The letter f at the end of the number is used to indicate that this is a float value, while the e-2 is used to indicate that the number is in scientific

Source Code

#include<stdio.h>
int main()
{
    int a=10;
    char b='$';
    float c=12.5f;
    long int d=2582l;
    int aa=0x41;
    float cc=253e-2f;
    printf("%d \n %d \n%0.2f",a,b,c);
    return 0;
}
To download raw file Click Here

Output

10
36
12.50

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C