Variables & 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
constkeyword.
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 namedscoreof typeint. - The
score = 110;line assigns the value110to thescorevariable. - The
const int uid = 232323;line declares a constant nameduidof typeintand assigns the value232323to it. - The
int hiteshBalance = 500;line declares a variable namedhiteshBalanceof typeintand assigns the value500to it. - The
hiteshBalance = 1000;line assigns the value1000to thehiteshBalancevariable. - The
uid = 1223;line assigns the value1223to theuidconstant. - 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.
Start your journey with ChaiCode
All of our courses are available on chaicode.com. Feel free to check them out.