Variables in C++
Learn why we need variables in our code and how we can use them.
Up till now, we have displayed a pre-decided text— ‘Hello, World!’ on the screen. No matter how many times we run the program, the same text will be displayed.
In programming, “hard coding” refers to the practice of embedding specific values or data directly into the code instead of allowing them to be determined at runtime by getting them as user input or extracting them from external files.
Variable in memory locations
What if we wanted to print a different text each time? What if we wanted the user to decide what needs to be displayed? Suppose we need to write a program that displays the user’s age. To make this possible, the programming language needs to provide us with a feature using which we can take the input from the user, save it to a memory location, and retrieve it from the memory location whenever the program requires it. Have a look at the following slides:
Suppose we want to write a program that displays the circumference of a circle. Let’s recall the formula for calculating the circumference of a circle:
In this equation, which information remains the same (can be hardcoded), and which information changes for each circle (needs to be stored in a variable)?
This feature we need is called ‘variables’. Let’s dive in!
Variables—the building blocks of our program
A variable is a named memory location that holds data during program execution. Think of it as a labeled container that you can use to store and manage information throughout your code.
Variables are located in the minds of programmers and in the memory of computers. Programmers use symbolic names to describe variables in their minds. For example, in our example given above, the radius of a circle would exist in the programmers mind and their code as “radius” and would be referred to with that name. However, in the computer’s memory, it would occupy a space that would be referred to by the ...