C++ Tutorial menu

C++ Variables, Data Types and Input

Variables are named containers that hold data, like a name, a price or a score.

Declaring Variables

Write the type, the name and (usually) a starting value:

Example

cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
  string name = "Bilal";
  int age = 22;
  double salary = 55000.75;
  char grade = 'B';
  bool isStudent = true;

  cout << name << " is " << age << " years old\n";
  cout << "Salary: " << salary << "\n";
  cout << "Grade: " << grade << "\n";
  cout << "Student: " << isStudent << "\n";
  return 0;
}
Output
Bilal is 22 years old
Salary: 55000.8
Grade: B
Student: 1

Two things to notice:

  • cout shows about 6 significant digits by default, so 55000.75 is shown as 55000.8
  • bool values print as 1 (true) and 0 (false). Add cout << boolalpha; to print true and false

Data Types

TypeStoresExample
intWhole numbersint rooms = 3;
doubleDecimal numbersdouble kg = 2.5;
floatDecimals, less precisefloat r = 1.5f;
charOne characterchar c = 'Z';
booltrue or falsebool done = false;
stringText (needs <string>)string city = "Hyderabad";

Constants and auto

Example

cpp
const double GST = 0.18;   // cannot be changed later
auto count = 10;           // the compiler decides: int
auto rate = 2.75;          // the compiler decides: double

Use const for values that should never change, like tax rates or the number of days in a week. The compiler will stop you if you try to change them by mistake.

Type Conversion

Dividing two int values drops the decimal part. Use static_cast to convert:

Example

cpp
#include <iostream>
using namespace std;

int main() {
  int total = 7;
  int parts = 2;
  cout << total / parts << "\n";
  cout << static_cast<double>(total) / parts << "\n";
  return 0;
}
Output
3
3.5

Formatting Decimals

Include <iomanip> to control how many digits are shown:

Example

cpp
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
  double bill = 1234.5;
  cout << fixed << setprecision(2) << bill << "\n";
  return 0;
}
Output
1234.50

Reading Input with cin

cin >> reads a value typed by the user:

Example

cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
  string name;
  int year;
  cout << "Your name: ";
  cin >> name;
  cout << "Birth year: ";
  cin >> year;
  cout << "Hi " << name << ", you are about " << 2026 - year << " years old.\n";
  return 0;
}
Output
Your name: Ayesha
Birth year: 2004
Hi Ayesha, you are about 22 years old.

cin >> stops reading at a space. To read a full line such as "Ayesha Khan", use getline(cin, name);.

Exercise

Exercise

Which type should you use to store the text "Karachi"?

Learn C++ with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp