C and C++ Notes — Beginner to Advanced
Combined notes with clear explanations and example codes
Generated by: ChatGPT — GPT-5 Thinking mini
Date: 2025-09-30
Contents
Part I — C Language
1. Introduction to C
2. Data types & Variables
3. Operators
4. Control Structures: if, switch, loops
5. Functions & Recursion
6. Arrays & Strings
7. Pointers (including swapping)
8. Structures, Nested & Unions
9. File Handling in C
10. Useful Patterns
Part II — C++ Language
11. Introduction & OOP Concepts
12. Classes & Objects (constructors/destructors)
13. Access Specifiers, this, const members, static
14. Function Overloading, Default Arguments
15. Operator Overloading
16. Inheritance & Polymorphism (virtual functions)
17. Templates (function & class)
18. Exception Handling
19. File streams in C++
20. Misc: Enum, Scope Resolution, Friend, Pointer to Object
Part I — C Language
1. Introduction to C
C is a procedural programming language developed by Dennis Ritchie in the early 1970s. It is close to the
hardware, fast, and widely used for system programming, embedded systems, and low-level tasks. C programs are
compiled into machine code by compilers like gcc.
2. Data types & Variables
Basic data types: int, char, float, double. You can modify sizes using short/long and sign using unsigned. Variables
store values in memory. Use proper type for correct range and memory use.
Example:
#include <stdio.h>
int main() {
int a = 10;
float b = 3.14;
char ch = 'A';
printf("a=%d, b=%.2f, ch=%c\n", a, b, ch);
return 0;
}
3. Operators
Operators are symbols that perform operations on operands. Categories: arithmetic (+,-,*,/,%), relational
(==,!=,>,<,...), logical (&&,||,!), bitwise (&,|,^,~,<<,>>), assignment (=,+=,...), and ternary (?:).
Example:
#include <stdio.h>
int main() {
int x = 7, y = 3;
printf("x+y=%d\n", x+y);
printf("x%%y=%d\n", x%y);
printf("x>y = %d\n", x>y); // prints 1 if true, 0 if false
return 0;
}
4. Control Structures: if-else, switch, loops
if: choose between branches. Use else if for multiple conditions. switch: select based on integer/char value. Loops:
for (known iterations), while (condition-first), do-while (run at least once). Use break to exit and continue to skip
iteration.
Examples:
#include <stdio.h>
int main() {
int n = 5;
if (n%2 == 0) {
printf("Even\n");
} else {
printf("Odd\n");
}
// switch
int choice = 2;
switch(choice) {
case 1: printf("One\n"); break;
case 2: printf("Two\n"); break;
default: printf("Other\n");
}
// loop examples
for (int i=0;i<3;i++) printf("for i=%d\n", i);
int j = 0;
while (j<3) { printf("while j=%d\n", j); j++; }
int k = 0;
do { printf("do-while k=%d\n", k); k++; } while(k<3);
return 0;
}
5. Functions & Recursion
Functions break code into reusable blocks. Declare prototypes before use or define earlier. Arguments are passed
by value in C. Recursion: a function calling itself. Ensure a base case to stop recursion.
Examples:
#include <stdio.h>
int add(int x, int y) { return x + y; }
int factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n-1); // recursive call
}
int main() {
printf("add(2,3)=%d\n", add(2,3));
printf("5! = %d\n", factorial(5));
return 0;
}
6. Arrays & Strings
Arrays hold multiple elements of same type. Strings in C are arrays of char ending with a null character '\0'.
Remember bounds: reading/writing outside array is undefined behavior.
Examples:
#include <stdio.h>
#include <string.h>
int main() {
int a[3] = {10,20,30};
printf("a[1]=%d\n", a[1]);
char name[20] = "Anisha";
printf("name=%s, length=%zu\n", name, strlen(name));
return 0;
}
7. Pointers
A pointer stores the memory address of a variable. Use & to get address and * to dereference. Pointers are powerful
for dynamic data, arrays, strings, and passing by reference.
Swap using pointers (pass-by-reference):
#include <stdio.h>
void swap(int *p, int *q) {
int temp = *p;
*p = *q;
*q = temp;
}
int main() {
int x = 5, y = 10;
swap(&x, &y);
printf("x=%d, y=%d\n", x, y); // x=10, y=5
return 0;
}
Pointer arithmetic: incrementing a pointer moves it by sizeof(pointed_type). Be careful with validity.
8. Structures, Nested Structures & Unions
struct groups different types under one name. Use typedef for convenience. Nested structs allow complex records.
union shares memory among members; only one member valid at a time (saves memory).
Example struct and nested:
#include <stdio.h>
#include <string.h>
typedef struct {
char street[50];
int number;
} Address;
typedef struct {
char name[30];
int age;
Address addr; // nested struct
} Person;
int main() {
Person p;
strcpy([Link], "Anisha");
[Link] = 23;
strcpy([Link], "MG Road");
[Link] = 10;
printf("%s, %d, %s %d\n", [Link], [Link], [Link], [Link]);
return 0;
}
Union example (memory shared):
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data d;
d.i = 10;
printf("i=%d\n", d.i);
d.f = 3.14; // now f is valid; i may be corrupted
printf("f=%f\n", d.f);
return 0;
}
9. File Handling in C
Use fopen to open files, fclose to close. Modes: "r", "w", "a", binary: "rb"/"wb". Use fprintf/fscanf or fread/fwrite for
binary.
Example (text file):
#include <stdio.h>
int main() {
FILE *fp = fopen("[Link]", "w");
if (!fp) { perror("fopen"); return 1; }
fprintf(fp, "Hello file\\n");
fclose(fp);
fp = fopen("[Link]", "r");
char buf[100];
if (fgets(buf, sizeof(buf), fp)) printf("Read: %s", buf);
fclose(fp);
return 0;
}
10. Useful Patterns (loops & patterns)
Pattern printing exercises help understand nested loops and indexing. Example: Print a simple star triangle.
#include <stdio.h>
int main() {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 0; j < i; j++) printf("* ");
printf("\n");
}
return 0;
}
Part II — C++ Language
11. Introduction & OOP Concepts
C++ is an extension of C that supports Object-Oriented Programming (OOP). Key OOP concepts: Encapsulation
(data + methods in classes), Abstraction (hide complexity), Inheritance (re-use), Polymorphism (same interface,
many forms).
12. Classes & Objects: constructors & destructors
class is a blueprint, object is an instance. Constructors initialize objects; destructor cleans up. Use initializer lists for
efficiency.
Example class:
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
string name;
int age;
Person(string n, int a) : name(n), age(a) { cout << "Created " << name << "\n"; }
~Person() { cout << "Destroyed " << name << "\n"; }
void info() const { cout << name << ", " << age << endl; }
};
int main() {
Person p("Anisha", 23);
[Link]();
return 0;
}
13. Access specifiers, this pointer, const members, static
Access specifiers: public, private, protected. 'this' is pointer to current object. const methods don't modify members.
static members belong to class, not object.
Example (static & const):
#include <iostream>
using namespace std;
class Counter {
static int count; // declaration
public:
Counter() { ++count; }
~Counter() { --count; }
static int getCount() { return count; }
};
int Counter::count = 0; // definition
int main() {
Counter a, b;
cout << Counter::getCount() << endl; // prints 2
return 0;
}
14. Function Overloading & Default Arguments
Overloading: same function name, different parameter types. Default arguments let caller omit trailing parameters.
Example:
#include <iostream>
using namespace std;
void print(int x) { cout << "int " << x << endl; }
void print(string s) { cout << "str " << s << endl; }
int add(int a, int b=5) { return a + b; }
int main() {
print(10);
print("hello");
cout << add(3) << endl; // uses default b=5
return 0;
}
15. Operator Overloading
You can define how operators work for user-defined types. Commonly overloaded: +, -, <<, >>, [], ().
Example: adding two complex numbers:
#include <iostream>
using namespace std;
class Complex {
public:
double r, i;
Complex(double _r=0, double _i=0): r(_r), i(_i) {}
Complex operator+(const Complex &o) const {
return Complex(r + o.r, i + o.i);
}
};
int main() {
Complex a(1,2), b(3,4);
Complex c = a + b;
cout << c.r << " + " << c.i << "i\n";
return 0;
}
16. Inheritance & Polymorphism
Inheritance lets a class (derived) reuse code from a base class. Virtual functions enable runtime polymorphism:
calling a derived version through a base pointer. Use virtual destructor to avoid resource leaks.
Example (virtual functions):
#include <iostream>
using namespace std;
class Animal {
public:
virtual void speak() { cout << "Animal\n"; }
virtual ~Animal() {}
};
class Dog : public Animal {
public:
void speak() override { cout << "Dog\n"; }
};
int main() {
Animal *a = new Dog();
a->speak(); // Dog's speak()
delete a;
return 0;
}
17. Templates (function & class)
Templates allow generic programming: write code for any type. Function templates and class templates are
common.
Example function template:
#include <iostream>
using namespace std;
template<typename T>
T add(T a, T b) { return a + b; }
int main() {
cout << add<int>(2,3) << endl;
cout << add<double>(2.5,3.1) << endl;
return 0;
}
18. Exception Handling
Use try, throw, catch to handle exceptions. C++ exceptions provide safer error handling than return codes. Avoid
throwing raw pointers.
Example:
#include <iostream>
#include <stdexcept>
using namespace std;
int divide(int a, int b) {
if (b == 0) throw runtime_error("division by zero");
return a / b;
}
int main() {
try {
cout << divide(4,0) << endl;
} catch (const exception &e) {
cout << "Error: " << [Link]() << endl;
}
return 0;
}
19. File streams in C++
Use fstream, ofstream, ifstream to work with files in a type-safe manner.
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream ofs("[Link]");
ofs << "Hello C++ file\\n";
[Link]();
ifstream ifs("[Link]");
string line;
if (getline(ifs, line)) cout << line << endl;
[Link]();
return 0;
}
20. Misc: Enum, Scope Resolution, Friend, Pointer to Object
enum: named integer constants. Scope resolution :: accesses global or class scopes. friend functions access
private members. Object pointers store addresses of objects; use -> to access.
Examples:
#include <iostream>
using namespace std;
enum Color { RED, GREEN, BLUE };
class B;
class A {
int x;
public:
A(int v):x(v) {}
friend void show(const A &a);
};
void show(const A &a) { cout << a.x << endl; }
int main() {
Color c = GREEN;
cout << c << endl; // prints 1 for GREEN
A a(10);
show(a);
return 0;
}
Compile & Run Tips
C: gcc file.c -o file (run: ./file) C++: g++ [Link] -o file (run: ./file) Use -Wall to show warnings and -g for debug
symbols.
Study Tips & FAQ
1. Practice by writing small programs for each topic (e.g., swap using pointers, simple class with constructor). 2.
Trace code by hand to understand pointer and memory behavior. 3. Use an online judge or local compiler to test
edge cases. 4. Read and understand compiler warnings — they help catch bugs early.
End of Notes — Good luck! If you want, I can add more examples, diagrams, or convert this into two separate PDFs.