0
0
C++programming~5 mins

Why variables are needed in C++

Choose your learning style9 modes available
Introduction

Variables help us store and remember information in a program. They let us use names to keep data that can change or be used later.

When you want to save a user's age to use it later in the program.
When you need to keep track of a score in a game that changes over time.
When you want to store a temperature reading from a sensor to display it.
When you want to remember a person's name to greet them multiple times.
When you want to calculate and store the result of a math operation for later use.
Syntax
C++
type variableName = value;

type is the kind of data (like int for numbers, char for letters).

variableName is the name you give to the storage spot.

Examples
This creates a variable named age that holds the number 25.
C++
int age = 25;
This creates a variable named grade that holds the letter 'A'.
C++
char grade = 'A';
This creates a variable named temperature that holds a decimal number.
C++
float temperature = 36.5f;
Sample Program

This program shows how a variable score can store a number, then change it later. It prints the score before and after updating.

C++
#include <iostream>

int main() {
    int score = 0;  // Start with zero score
    std::cout << "Initial score: " << score << "\n";

    score = 10;  // Update score
    std::cout << "Updated score: " << score << "\n";

    return 0;
}
OutputSuccess
Important Notes

Variables make programs flexible because you can change their values anytime.

Always give variables clear names so your code is easy to understand.

Summary

Variables store information that your program can use and change.

They help keep your data organized and easy to work with.