Uploaded by peanboy99

C++ Programming Basics: A Comprehensive Guide for Beginners

advertisement
C++ Programming Basics
Introduction to C++
C++ is a general-purpose programming language created by Bjarne Stroustrup as an extension of
C.
It supports both procedural and object-oriented programming.
Basic Structure of a C++ Program
#include
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
Data Types
Common data types in C++:
- int: for integers (e.g., 5, -3)
- float: for decimals (e.g., 3.14)
- double: for large decimals
- char: for single characters (e.g., 'A')
- string: for text (e.g., "Hello")
- bool: for true or false values
Variables
Syntax: data_type variable_name = value;
Example:
int age = 19;
double price = 10.5;
char grade = 'A';
Input and Output
Input: cin >> variable;
Output: cout << "message" << variable;
Example:
int age;
cout << "Enter your age: ";
cin >> age;
cout << "You are " << age << " years old.";
Operators
1. Arithmetic: +, -, *, /, %
2. Comparison: ==, !=, >, <, >=, <=
3. Logical: &&, ||, !
4. Assignment: =, +=, -=, *=, /=
Control Statements
if(condition) {
// code
} else if(condition) {
// code
} else {
// code
}
switch(expression) {
case value:
// code
break;
default:
// code
}
Loops
1. for loop:
for(int i = 0; i < 5; i++) {
cout << i;
}
2. while loop:
int i = 0;
while(i < 5) {
cout << i;
i++;
}
3. do-while loop:
int i = 0;
do {
cout << i;
i++;
} while(i < 5);
Functions
Functions allow code reuse.
Syntax:
return_type functionName(parameters) {
// code
return value;
}
Example:
int add(int a, int b) {
return a + b;
}
Arrays
int numbers[5] = {1, 2, 3, 4, 5};
Access elements using index: numbers[0], numbers[1], etc.
Pointers
A pointer stores the memory address of a variable.
int x = 10;
int *ptr = &x;
cout << *ptr; // prints 10
Object-Oriented Programming (OOP)
C++ supports OOP concepts like:
- Classes and Objects
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
Example:
class Student {
public:
string name;
int age;
void display() {
cout << name << " is " << age << " years old." << endl;
}
};
int main() {
Student s1;
s1.name = "Ali";
s1.age = 20;
s1.display();
}
File Handling
#include
ofstream outFile("data.txt");
outFile << "Hello File!";
outFile.close();
ifstream inFile("data.txt");
string text;
getline(inFile, text);
cout << text;
inFile.close();
Conclusion
C++ is a powerful language widely used in systems programming, game development, and
performance-critical applications.
Mastering the basics prepares you for advanced topics such as templates, STL, and memory
management.
Download