Lec-03 (DataTypes and Varibles)
Lec-03 (DataTypes and Varibles)
In C++, constants and variables are essential for storing data. Here's a breakdown of each, along
with examples, data types, memory sizes, and practice questions.
Constants
Constants are fixed values that do not change during the execution of a program. You define a
constant using the const keyword or #define preprocessor directive.
Example:
#include <iostream>
using namespace std;
int main() {
const int days_in_week = 7; // Constant variable
cout << "Days in a week: " << days_in_week << endl;
// DAYS_IN_WEEK = 8; // This would cause a compilation error
return 0;
}
Variables
Variables are storage locations with a name that can hold data and may change throughout the
program's execution. You must declare a variable with a specific data type.
double pi = 3.14159;
Example:
#include <iostream>
using namespace std;
int main() {
int age = 30;
float height = 5.9f;
double weight = 70.5;
char initial = 'J';
bool isStudent = false;
string name = "Alice";
return 0;
}
Practice Questions
1. Declare an integer variable num and assign it the value of 10. Print it.
2. Create a constant PI with the value 3.14 and print it.
3. Define a float variable distance and assign it a value. Print it with a message.
4. Create a string variable city and assign your city name to it. Print it.
Solution
Assignment Questions [20 Marks]
1. Write a C++ program that declares a variable for storing your favorite book's title and
prints it.
2. Create a program that calculates and displays the area of a rectangle using variables for
length and width.
3. Modify the previous rectangle program to use constants for the dimensions if they don't
change.
4. Create a simple C++ program that prompts the user for their first and last names, and
prints a welcome message using string variables.
5. Create a simple C++ calculator -perform following Operations