Skip to content

C++ - Variables and Constants

Chapter 3: Variables and Constants

In this chapter, we will learn about variables and constants in C++. We will start by learning about variables and how to declare and initialize them. Then, we will learn about constants and how to declare and initialize them.

Variables and Constants

Variables are used to store data in a program. They can be changed during the execution of the program. Constants, on the other hand, are used to store data that cannot be changed during the execution of the program. They are declared using the const keyword.

Here’s an example of declaring and initializing a variable:

int age = 25;

In this example, we declare a variable named age and initialize it with the value 25. The int keyword is used to declare the variable as an integer.

Here’s an example of declaring and initializing a constant:

const double PI = 3.14159;

In this example, we declare a constant named PI and initialize it with the value 3.14159. The const keyword is used to declare the constant as a constant.

Code used in video

#include <iostream>
using namespace std;
int main(){
int score;
score = 110;
const int uid = 232323;
int hiteshBalance = 500;
hiteshBalance = 1000;
// uid = 1223;
cout << "Welcome to chai with cpp 1" << endl ;
cout << "Welcome to chai with cpp 2" << endl ;
cout << "Welcome to chai with cpp 3" << endl ;
return 0;
}

Going through the code

  • The int score; line declares a variable named score of type int.
  • The score = 110; line assigns the value 110 to the score variable.
  • The const int uid = 232323; line declares a constant named uid of type int and assigns the value 232323 to it.
  • The int hiteshBalance = 500; line declares a variable named hiteshBalance of type int and assigns the value 500 to it.
  • The hiteshBalance = 1000; line assigns the value 1000 to the hiteshBalance variable.
  • The uid = 1223; line assigns the value 1223 to the uid constant.
  • The cout << "Welcome to chai with cpp 1" << endl ; line prints the string “Welcome to chai with cpp 1” to the console.
  • The cout << "Welcome to chai with cpp 2" << endl ; line prints the string “Welcome to chai with cpp 2” to the console.
  • The cout << "Welcome to chai with cpp 3" << endl ; line prints the string “Welcome to chai with cpp 3” to the console.

Summary

In this chapter, we have learned about variables and constants in C++. We have also learned how to declare and initialize variables and constants. By the end of this chapter, you should have a good understanding of how to use variables and constants in C++.