Getting Started with C++
Introduction to C++
C++ is a powerful general-purpose programming language that supports procedural, object-oriented,
and generic programming. It was developed by Bjarne Stroustrup in 1983 as an extension of C.
Variables and Constants
Variable: A named memory location that stores data.
Example:
int age = 25;
float pi = 3.14;
Constant: A value that does not change during execution.
const int MAX = 100;
Expressions, Statements, and Comments
Expression: A combination of variables, constants, and operators.
Example: int sum = a + b * 5;
Statement: A complete instruction in a program.
int x = 10;
Comments: Used to add explanations in code.
// Single-line comment
/* Multi-line comment */
Keywords in C++
C++ has reserved words that cannot be used as variable names, such as int, float, double, char,
return, if, else, while, for, etc.
Operators in C++
Arithmetic Operators: +, -, *, /, %
Relational Operators: ==, !=, <, >
Logical Operators: &&, ||, !
Assignment Operators: =, +=, -=, *=
Increment/Decrement: ++, --
Conditional Operator: (condition ? true_value : false_value)
Precedence of Operators
Multiplication (*), Division (/), Modulus (%) have higher precedence than Addition (+) and
Subtraction (-). Parentheses () can be used to change precedence.
Example: int result = (5 + 3) * 2; // result = 16
Data Types
C++ supports various data types:
- int (Integer): int x = 10;
- float (Floating-point): float pi = 3.14;
- double (Double precision float): double d = 3.1415;
- char (Character): char grade = 'A';
- bool (Boolean): bool isHappy = true;
Type Conversion
Implicit Conversion: Automatically done by the compiler.
Example: int a = 5; float b = a; // 'a' is converted to float
Explicit Conversion (Type Casting):
float num = 9.8;
int x = (int) num; // Explicitly converting float to int
Input and Output Statements
cin (Input) and cout (Output) are used for handling user input and displaying output.
Example:
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter age: ";
cin >> age;
cout << "You entered: " << age;
return 0;
}
Preprocessor Directives
Preprocessor directives start with # and are processed before compilation.
Common Directives:
#include <iostream> // Includes standard I/O library
#define PI 3.14 // Defines a constant
Example:
#include <iostream>
#define PI 3.14
using namespace std;
int main() {
cout << "Value of PI: " << PI;
return 0;
}