Chapter 2 — C++ Fundamentals: Variables, Types & I/O
📚 Chapter Overview
This chapter builds the foundation of C++ logic. You will learn how the computer stores data in memory using variables, the different types of data C++ can handle, and how to interact with the user via the console.
Learning Objectives:
- Master Variables and Primitive Data Types.
- Use
cinandcoutfor input and output. - Perform Arithmetic calculations.
2.1 Variables and Constants
Part 1 — Definition
A Variable is a named storage location in memory that holds a value. In C++, variables must be declared with a type. A Constant is a variable whose value cannot be changed once assigned, defined using the const keyword.
Part 2 — Syntax
int age = 20;
const float PI = 3.14;
Part 3 — Example
Problem: Store a student's marks and prevent them from being changed.
int marks = 85;
const int MAX_MARKS = 100;
cout << "Marks: " << marks << "/" << MAX_MARKS;
Output: Marks: 85/100
Part 4 — Video
Video: Coming Soon
2.2 Input and Output (cin/cout)
Part 1 — Definition
C++ uses Streams for I/O. cout (Character Output) displays data on the screen using the insertion operator (<<). cin (Character Input) reads data from the keyboard using the extraction operator (>>).
Part 2 — Syntax
cout << "Message";
cin >> variable;
Part 3 — Example
Problem: Ask for a user's age and display it back.
int userAge;
cout << "Enter your age: ";
cin >> userAge;
cout << "You are " << userAge << " years old.";
Part 4 — Video
Video: Coming Soon
🏆 Chapter Challenge
Challenge Objective
Build a "Rectangle Property Calculator" that takes inputs and performs calculations.
Requirements
- Take Length and Width as inputs (float).
- Calculate Area = Length * Width.
- Calculate Perimeter = 2 * (Length + Width).
- Display both results clearly.
Step-by-Step Process
- Declare float variables for L, W, A, P.
- Use
coutto prompt the user. - Use
cinto store values. - Apply the math formulas.
- Print the final results using
endlfor new lines.
Expected Deliverables
rect_calc.cppsource file.