C++ Program BASICS Revision


✅ First C++ Program

#include <iostream>  // Standard I/O library
using namespace std;

int main() {  // Main function
    cout << "Hello, World!";  // Output statement
    return 0;  // Return statement
}

🔹 Explanation:

  • #include <iostream> → Header file for input/output.

  • using namespace std; → Allows using standard namespace (removes need for std:: prefix).

  • cout → Prints output to console.

  • return 0; → Indicates successful execution.


✅ Tokens in C++

Tokens are the smallest units in a C++ program.

🔹 Types of Tokens:

  1. Keywords → Reserved words (e.g., int, return, if, else, while)

  2. Identifiers → Names for variables, functions, classes (e.g., main, age, total)

  3. Constants → Fixed values (5, 3.14, 'A')

  4. Operators → Symbols for operations (+ , - , * , /)

  5. Special Symbols{ } , ; ( ) [ ]

  6. Strings → Text enclosed in "" (e.g., "Hello")


✅ Functions in C++

A function is a block of code designed to perform a specific task.

🔹 Syntax:

return_type function_name(parameters) {
    // Function body
}

🔹 Example:

#include <iostream>
using namespace std;

void greet() {  // Function without return type
    cout << "Welcome to C++ Programming!\n";
}

int main() {
    greet();  // Function call
    return 0;
}

✅ Scope of Variables in C++

Scope determines where a variable is accessible.

🔹 Types:

  1. Local Variable → Declared inside a function, accessible only there.

  2. Global Variable → Declared outside functions, accessible everywhere.

  3. Static Variable → Retains its value between function calls.

  4. Register Variable → Stored in CPU registers (rarely used today).

🔹 Example:

#include <iostream>
using namespace std;

int globalVar = 10;  // Global Variable

void func() {
    int localVar = 5;  // Local Variable
    static int staticVar = 1;
    staticVar++;
    cout << "Local: " << localVar << ", Static: " << staticVar << "\n";
}

int main() {
    func();
    func();
    cout << "Global: " << globalVar << "\n";
    return 0;
}

✅ Conditional Statements in C++

Used for decision-making in programs.

🔹 if Statement

int num = 10;
if (num > 0) {
    cout << "Positive Number";
}

🔹 if-else Statement

int num = -5;
if (num > 0) {
    cout << "Positive";
} else {
    cout << "Negative";
}

🔹 else-if Ladder

int marks = 75;
if (marks >= 90) {
    cout << "Grade A";
} else if (marks >= 75) {
    cout << "Grade B";
} else {
    cout << "Grade C";
}

✅ Nested if and switch in C++

🔹 Nested if

int num = 5;
if (num > 0) {
    if (num % 2 == 0) {
        cout << "Even Positive";
    } else {
        cout << "Odd Positive";
    }
}

🔹 switch Statement

int choice = 2;
switch (choice) {
    case 1:
        cout << "Option 1";
        break;
    case 2:
        cout << "Option 2";
        break;
    default:
        cout << "Invalid Option";
}

✅ Increment and Decrement Operators in C++

Used to increase or decrease values by 1.

Operator Meaning Example
++ Increment by 1 a++ or ++a
-- Decrement by 1 a-- or --a

🔹 Example:

int a = 5;
cout << a++ << "\n";  // Post-increment → prints 5, then a = 6
cout << ++a << "\n";  // Pre-increment → a = 7, then prints 7

✅ Operators in C++

🔹 Types of Operators:

  1. Arithmetic Operators+ , - , * , / , %

  2. Relational Operators== , != , > , < , >= , <=

  3. Logical Operators&& , || , !

  4. Assignment Operators= , += , -= , *= , /=

  5. Bitwise Operators& , | , ^ , ~ , << , >>

  6. Conditional (Ternary) Operatorcondition ? true : false

  7. Comma Operator, used to separate expressions.

  8. sizeof Operator → Returns the size of a variable.

🔹 Example:

int a = 10, b = 20;
cout << "Sum = " << a + b << "\n";  // Arithmetic
cout << (a > b) << "\n";        // Relational
cout << ((a < b) && (b > 15)) << "\n";  // Logical
a += 5;                         // Assignment
cout << "a = " << a << "\n";

✅ Loops in C++

Loops are used to execute a block of code multiple times.

🔹 Types of Loops:

  1. for Loop

  2. while Loop

  3. do-while Loop

🔹 for Loop

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 5; i++) {
        cout << i << " ";
    }
    return 0;
}

Output: 1 2 3 4 5

🔹 while Loop

#include <iostream>
using namespace std;

int main() {
    int i = 1;
    while (i <= 5) {
        cout << i << " ";
        i++;
    }
    return 0;
}

🔹 do-while Loop


#include <iostream>
using namespace std;

int main() {
    int i = 1;
    do {
        cout << i << " ";
        i++;
    } while (i <= 5);
    return 0;
}

----------------------------------------------------------------

✅ Arrays in C++

An array is a collection of similar data elements stored at contiguous memory locations.

🔹 Declaring an Array

int arr[5];  // Declares an array of size 5

🔹 Initializing an Array

int arr[5] = {1, 2, 3, 4, 5};

🔹 Accessing Elements

#include <iostream> using namespace std; int main() { int arr[5] = {10, 20, 30, 40, 50}; cout << "First element: " << arr[0] << endl; return 0; }

🔹 Looping Through an Array

#include <iostream> using namespace std; int main() { int arr[5] = {1, 2, 3, 4, 5}; for (int i = 0; i < 5; i++) { cout << arr[i] << " "; } return 0; }

✅ Working with 2D Arrays in C++

A 2D array is an array of arrays, commonly used to represent matrices.

🔹 Declaring a 2D Array

int matrix[3][3];

🔹 Initializing a 2D Array

int matrix[2][2] = {{1, 2}, {3, 4}};

🔹 Accessing 2D Array Elements

#include <iostream> using namespace std; int main() { int matrix[2][2] = {{1, 2}, {3, 4}}; cout << "Element at (1,1): " << matrix[1][1] << endl; return 0; }

🔹 Looping Through a 2D Array

#include <iostream> using namespace std; int main() { int matrix[2][2] = {{1, 2}, {3, 4}}; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { cout << matrix[i][j] << " "; } cout << endl; } return 0; }

✅ Strings in C++

A string is a sequence of characters stored in a character array.

🔹 Declaring a String

char str[10];

🔹 Initializing a String

char str[] = "Hello";

🔹 Input and Output of Strings

#include <iostream> using namespace std; int main() { char name[20]; cout << "Enter your name: "; cin >> name; // Reads string until space cout << "Hello, " << name; return 0; }

✅ String Library Functions in C++

C++ provides several built-in functions to work with strings (in string library).

FunctionDescription
strlen(str)              Returns the length of the string
strcpy(dest, src)Copies src to dest
strncpy(dest, src, n)Copies first n characters of src to dest
strcat(str1, str2)Concatenates str2 to str1
strncat(str1, str2, n)Appends first n characters of str2 to str1
strcmp(str1, str2)Compares two strings
strncmp(str1, str2, n)Compares first n characters of two strings
strchr(str, ch)Finds first occurrence of ch in str
strrchr(str, ch)Finds last occurrence of ch in str
strstr(str1, str2)Finds first occurrence of str2 in str1

🔹 Example: Using String Functions

#include <iostream> #include <cstring> using namespace std; int main() { char str1[] = "Hello"; char str2[] = "World"; char str3[20]; cout << "Length of str1: " << strlen(str1) << endl; strcpy(str3, str1); cout << "Copied string: " << str3 << endl; strcat(str1, str2); cout << "Concatenated string: " << str1 << endl; cout << "Comparison result: " << strcmp("abc", "abd") << endl; cout << "First occurrence of 'l': " << strchr(str1, 'l') << endl; cout << "Last occurrence of 'l': " << strrchr(str1, 'l') << endl; cout << "Finding 'or' in 'World': " << strstr(str2, "or") << endl; return 0; }

OUTPUT:
Length of str1: 5 Copied string: Hello Concatenated string: HelloWorld Comparison result: -1 First occurrence of 'l': lloWorld Last occurrence of 'l': lWorld Finding 'or' in 'World': or
--------------------------------------------------------------------------

Working with Structures in C++

A structure in C++ is a user-defined data type that groups together variables of different types.

Declaring and Using a Structure: #include #include using namespace std; struct Student { char name[50]; int age; float marks; }; int main() { Student student1; student1.age = 21; student1.marks = 85.5; strcpy(student1.name, "John Doe"); cout << "Name: " << student1.name << endl; cout << "Age: " << student1.age << endl; cout << "Marks: " << student1.marks << endl; return 0; }
Output: Name: John Doe Age: 21 Marks: 85.50
________________________________________________________________

Understanding Pointers in C++

A pointer in C++ is a variable that stores the memory address of another variable.
Example: #include using namespace std; int main() { int num = 10; int *ptr = # cout << "Value of num: " << num << endl; cout << "Address stored in ptr: " << ptr << endl; cout << "Value at ptr: " << *ptr << endl; return 0; }
Output: Value of num: 10 Address stored in ptr: [memory address] Value at ptr: 10 ----------------------------------------

Function Call in C++

A function in C++ is a block of code that performs a specific task.
Example: #include using namespace std; void greet() { cout << "Hello, World!" << endl; } int main() { greet(); // Function call return 0; }
Output: Hello, World!
______________________________________________________________

Files in C++

Files in C++ allow storing data permanently. File handling is done using `fstream`.
Example: Writing to a File
#include #include using namespace std; int main() { ofstream file("example.txt"); file << "Hello, File!" << endl; file.close(); cout << "Data written to file." << endl; return 0; }
Output:
Data written to file. Example: Reading from a File
#include <iostream> #include <fstream> // Include fstream for file handling using namespace std; int main() { ifstream file("example.txt"); // Open the file for reading string content; if (file.is_open()) { // Check if the file is successfully opened while (getline(file, content)) { // Read file line by line cout << "Read from file: " << content << endl; } file.close(); // Close the file after reading } else { cout << "Error opening file!" << endl; // Error message if file not found } return 0; }
Output:

If example.txt contains: Hello, File!

Read from file: Hello, File!

Comments

Post a Comment

Popular Posts

WRITING GOALS CHALLENGE ♥️#MAY

THE ANGEL FROM GOD

A1 & A2 SPANISH COMPLETION #2-WEEK CHALLENGE

A Journey Beyond Borders

THE BROKEN WING

Basic Greetings & Phrases - es

Here there's one, who is much faithful than ourselves, and will lead you till the end...

JavaScript Basic Revision

C Program BASICS Revision