C++ · C++ Beginner

C++ Basics: Data Types, Variables, and Constants

Run this in the Online C++ compiler

Introduction

Welcome to the exciting world of C++ programming! In this journey of exploration, we'll delve into the fundamentals of C++, focusing on essential concepts like Data Types, Variables, and Constants.

Understanding Basic Data Types

In C++, data types help define the kind of information a variable can hold. Here are some fundamental data types:

Data Types Description Example
'int' Used for Integer data type for whole numbers (without a decimal point) 1, -123
'float' Floating-point data type for real numbers that can have a decimal point. 3.14, -3.14, 6.2
'char' Character data type for handling single characters. 'c', '3', '$'
'bool' Boolean data type for representing true or false values. True - 1, False - 0

Variable and Constant Declaration and Initialization

Variables

Variables are like containers that hold data. To use a variable, you need to declare its type and give it a name. Here's how you do it:

int age;        // Declaring an integer variable named 'age'
char grade;     // Declaring a character variable named 'grade'
float height;   // Declaring a float variable named 'height'

Once declared, you can assign values to these variables:

age = 25;        // Assigning the value 25 to the 'age' variable
grade = 'A';     // Assigning the character 'A' to the 'grade' variable
height = 5.9;    // Assigning the value 5.9 to the 'height' variable

You can also declare and initialize a variable in one line:

int quantity = 10;   // Declaring and initializing an integer variable

Constants

Constants, as the name suggests, are values that do not change during the program's execution. They are declared using the const keyword:

const int monthsInYear = 12;    // Declaring a constant for months in a year
const float pi = 3.14159;       // Declaring a constant for the mathematical constant pi

Exercise: Declare and Manipulate Variables and Constants

Let's put this into practice. Declare variables for your age, a letter representing your favorite grade, and your height. Assign values to these variables and try performing simple operations:

Conclusion

Compile and run this program to see the results. You've now successfully declared, assigned values to, and manipulated variables and constants in C++. Keep exploring and experimenting to solidify your understanding!

This website uses cookies to ensure you get the best experience on our website.