C++ Programming Notes
Lesson 1: Introduction to C++
C++ is a high-level, general-purpose programming language widely used for system/software
development, game development, and applications requiring high performance.
Basic Structure of a C++ Program:
Every C++ program has at least three parts:
1. Preprocessor Directives: Code that runs before the actual program starts.
2. Main Function: The starting point of every C++ program.
3. Statements: Instructions that tell the computer what to do.
Example Program:
#include <iostream> // Preprocessor Directive
// Main Function: The entry point of the program
int main() {
// Output statement: Display "Hello, World!" on the screen
std::cout << "Hello, World!" << std::endl;
return 0; // Exit the program
Breaking Down the Code:
- #include <iostream>: This line tells the program to include the iostream library, which is needed to
handle input and output (like printing text on the screen).
- int main(): This is the main function where the program starts. Every C++ program needs a main()
function.
- std::cout: This is used to output text to the console (screen). std::endl adds a new line.
- return 0;: This indicates that the program ran successfully.
Lesson 2: Variables and Data Types
In C++, variables are used to store data. A variable needs a type (what kind of data it holds) and a
name.
Common Data Types:
- int: Integer numbers (e.g., 1, 100, -5).
- float: Floating-point numbers (e.g., 3.14, -0.01).
- double: Double precision floating-point numbers (more precise than float).
- char: A single character (e.g., 'a', '1', '$').
- string: A sequence of characters (e.g., "Hello").
Declaring Variables:
You need to declare a variable before you use it. Here's how you declare different types:
Example Code:
#include <iostream>
#include <string> // for string data type
int main() {
int age = 25; // integer
float weight = 72.5f; // floating point
double height = 1.75; // double precision
char grade = 'A'; // character
std::string name = "John"; // string
// Displaying the values of the variables
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "Weight: " << weight << std::endl;
std::cout << "Height: " << height << std::endl;
std::cout << "Grade: " << grade << std::endl;
return 0;
Exercise 1:
Try writing a program that:
1. Declares variables for your name, age, and favorite number.
2. Prints out the values of these variables.