0
0
Cprogramming~5 mins

Variable declaration and initialization

Choose your learning style9 modes available
Introduction

Variables store information that your program can use and change. Declaring and initializing them sets up space and gives them a starting value.

When you need to remember a number or text to use later in your program.
When you want to keep track of a score in a game.
When you want to store user input to use it again.
When you want to calculate something and save the result.
When you want to give a name to a value for easier understanding.
Syntax
C
type variable_name = value;

type is the kind of data (like int for whole numbers).

You can declare a variable without giving it a value first, but it's safer to initialize it right away.

Examples
This creates a variable named age that holds the number 25.
C
int age = 25;
This creates a variable named price that holds a decimal number.
C
float price = 19.99f;
This creates a variable named letter that holds a single character.
C
char letter = 'A';
This declares count first, then gives it the value 10 later.
C
int count;
count = 10;
Sample Program

This program declares three variables with different types and prints their values.

C
#include <stdio.h>

int main() {
    int age = 30;
    float height = 1.75f;
    char grade = 'B';

    printf("Age: %d\n", age);
    printf("Height: %.2f meters\n", height);
    printf("Grade: %c\n", grade);

    return 0;
}
OutputSuccess
Important Notes

Always choose the right type for your variable to save memory and avoid errors.

Uninitialized variables can hold random values, so it's best to initialize them.

Variable names should be clear and meaningful to make your code easier to read.

Summary

Variables hold data your program uses.

Declaration sets up the variable's type and name.

Initialization gives the variable its first value.