C++ Variables šŸŽÆ

beginner
6 min

C++ Variables šŸŽÆ

Welcome to your C++ Variables journey! In this lesson, you'll learn how to work with variables - the fundamental building blocks of any programming language. Let's dive in!

What are Variables? šŸ“

Variables are containers used to store data values in a program. They help us name data and make our code easier to understand and manage.

Variable Types šŸ“

C++ has several variable types to accommodate different types of data. The primary variable types are:

  • Integer Variables: used for whole numbers, like int, short, long.
  • Floating-point Variables: used for decimal numbers, like float, double.
  • Character Variables: used for individual characters, like char.
  • Boolean Variables: used for true or false values, like bool.

Declaring Variables āœ…

To declare a variable, you need to specify its name, data type, and (optionally) an initial value. Here's an example of how to declare variables:

cpp
int myInt = 10; float myFloat = 5.5; char myChar = 'A'; bool myBool = true;

šŸ’” Pro Tip: Give your variables meaningful names to make your code easy to understand.

Variable Naming Rules šŸ“

  • Variable names can contain letters, digits, and underscores.
  • The first character must be a letter or an underscore.
  • Variable names are case-sensitive (myVar and myvar are different variables).

Assigning Values āœ…

You can assign values to variables using the equal sign =. Here's an example:

cpp
int age = 25; float weight = 75.5; char initial = 'M'; bool isStudent = true;

Variable Operations āœ…

You can perform mathematical operations with variables. Here's an example:

cpp
int x = 10; int y = 20; int sum = x + y;

In this example, we've added the values of x and y and stored the result in the sum variable.

Quiz

Quick Quiz
Question 1 of 1

What are the primary variable types in C++?

That's it for today! In the next lesson, we'll dive deeper into working with variables and explore more operations you can perform with them. Until then, keep practicing! šŸ’” Happy Coding! šŸ’”