We've moved! — MindVault360 is now SrcForge. Better design, more content & premium notes.

Visit SrcForge →

MindVault360 has moved!

We've upgraded to SrcForge — a faster, more professional platform with better content, premium notes, and a modern design.

Visit us at SrcForge

Wednesday, January 15, 2025

Scope of Variable C++

 In C++, the area of the program where a variable is accessible is referred to as its scope. Depending on where and how they are declared, variables in C++ can have one of multiple scopes.

1. Local Scope

A variable that is declared inside a block (contained by {}) is only available within that block and has local scope.

example:

void example() {

    int x = 10; // Local scope

    std::cout << x; // Accessible here

}

// std::cout << x; // Error: x is not accessible here


2. Global Scope:

A global variable is one that is defined outside of all functions and classes. From the program's declaration point on, it is available throughout.

Example:

int globalVar = 20; // Global scope


void example() {

    std::cout << globalVar; // Accessible here

}


3. Function Scope

Function parameters and any variables declared inside a function are only available within that function.

Example:
void example(int param) { // param has function scope
    int x = 10;          // x has function scope
    std::cout << param + x;
}

4. Class Scope (Member Variables):

Declared variables inside a class are members of that class and can be accessed directly within member functions or through class objects.

Example:
class MyClass {
    int x; // Class scope (instance variable)
    static int y; // Class scope (static variable)
public:
    void setX(int val) { x = val; }
};


5. Namespace Scope:

Declared variables can be accessed within a namespace or by explicitly defining the namespace (or by using a using directive).

Example:
namespace MyNamespace {
    int x = 5;
}

int main() {
    std::cout << MyNamespace::x; // Access with namespace
}

6. File Scope (Static Variables):

File scope refers to the fact that a global variable declared with the static keyword can only be accessed within the file in which it is declared.

Example:
static int fileScopeVar = 10; // Accessible only in this file

7. Block Scope:

A variable that is declared inside a block (for example, inside conditionals or loops) can only be accessed inside that block.

Example:
if (true) {
    int y = 10; // Block scope
}
// std::cout << y; // Error: y is not accessible here

← Back Next →

Labels:

Monday, December 16, 2024

Dynamic memory

The application can allocate memory at runtime instead of compile time thanks to C++'s dynamic memory allocation feature. When you don't know how much memory is required until the program is running, this is helpful.

In C++, the new and delete operators are used to control dynamic memory:

Memory is allocated on the heap using new, which also returns a pointer to the memory that has been allocated.
To deallocate memory that was previously allocated with new, use delete.

A sample program on Dynamic memory:
#include <iostream>
using namespace std;

int main() {
    // Dynamic memory allocation for an integer using 'new'
    int *ptr = new int;   // Allocate memory for an integer
    *ptr = 100;           // Assign a value to the allocated memory

    // Output the value stored in the dynamically allocated memory
    cout << "Value stored at ptr: " << *ptr << endl;

    // Dynamic memory allocation for an array of integers
    int *arr = new int[5]; // Allocate memory for an array of 5 integers

    // Assign values to the array
    for(int i = 0; i < 5; i++) {
        arr[i] = (i + 1) * 10;  // Assign multiples of 10 to the array
    }

    // Output the values stored in the array
    cout << "Values in the dynamically allocated array: ";
    for(int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    // Deallocate memory using 'delete' for a single variable
    delete ptr;  // Free the memory allocated for the single integer

    // Deallocate memory using 'delete[]' for the array
    delete[] arr; // Free the memory allocated for the array

    return 0;
}

Summary:
Allocation of a single variable (new int):
We use new int to allocate memory for a single integer.
Following allocation, we give the memory a value of 100.
The value that is stored in that memory is output.

Allocating an array (new int[5]):
We use new int[5] to allocate memory for an array of five integers.
We display the values that we have assigned to the array (multiples of 10).

Deallocation
To deallocate the memory for the single integer, use delete ptr.
delete[] arr; releases all of the array's memory. Note that arrays are deleted using delete[] whereas a single variable is deleted using delete

Points to remember:
Memory allocated by new is stored on the heap until it is specifically released using delete.
Whereas delete[] is used for arrays, delete releases the memory allotted for a single object.
To avoid memory leaks, deallocate memory whenever you're finished.

← Back Next →

Labels:

Tuesday, December 10, 2024

Basic Syntax and Structure of C++

#include <iostream>

int main() {
    // Print Hello, World! to the console
    cout << "Hello, World!";
    return 0;
}

//

#

 Directory

include

 should include this in the program

iostream

 Standard Input/Output header file

int

 datatype

main()

function name. It is the execution point of my program. i.e it is the place where my program begins.

{ } 

 Specifies a Block of code

return

It intimates to the compiler that the program has reached the end of the line

;

 Termination Statement


Example:

#include <iostream>

using namespace std; 

int main() {

     cout << "Hello, World!" << endl;  

        int a = 5, b = 3;

    int sum = a + b; 

      cout << "Sum of " << a << " and " << b << " is: " << sum << endl;

        return 0;

}


← Back Next →

Labels:

Friday, December 6, 2024

C++ Boolean

 Boolean (or bool) data types are used in C++ to represent logical values. One of two values can be stored in a boolean variable:

actual (logically correct, equal to 1)
false (equal to 0 in terms of reasoning)

Key attributes of the C++ data type bool include:
When declaring a boolean variable, the keyword bool is used.

Default Values:
Boolean values are represented by the reserved keywords true and false in C++.

Recollection:
Most implementations use one byte of memory for bools.

Use:
Common applications of boolean variables include logical operations and decision-making (for example, in if statements).

Declaration and Initialization

#include <iostream>
using namespace std;

int main() {
    bool isRaining = true;   // Declare and initialize
    bool isSunny = false;    // Another boolean variable

    cout << "Is it raining? " << isRaining << endl; // Outputs: 1
    cout << "Is it sunny? " << isSunny << endl;     // Outputs: 0

    return 0;
}

In conditional statements, Boolean values
If, while, and for loops are examples of conditional statements that frequently involve booleans.

For instance:
#include <iostream>
using namespace std;

int main() {
    bool isAdult = true;

    if (isAdult) {
        cout << "You are an adult!" << endl;
    } else {
        cout << "You are not an adult!" << endl;
    }

    return 0;
}

Boolean and Logical Operators

C++ provides several logical operators that work with boolean values:

OperatorNameExampleDescription
&&Logical ANDa && bReturns true if both a and b are true.
``Logical OR
!Logical NOT!aReturns true if a is false.


Example: Logical Operations
#include <iostream>
using namespace std;

int main() {
    bool isRaining = true;
    bool hasUmbrella = false;

    if (isRaining && !hasUmbrella) {
        cout << "You should stay indoors!" << endl;
    }

    if (isRaining || hasUmbrella) {
        cout << "You can go outside safely!" << endl;
    }

    return 0;
}

Boolean and Comparison Operators

Boolean expressions often involve comparison operators that return true or false.

OperatorNameExampleDescription
==Equal toa == bReturns true if a is equal to b.
!=Not equal toa != bReturns true if a is not equal to b.
>Greater thana > bReturns true if a is greater than b.
<Less thana < bReturns true if a is less than b.
>=Greater than or equal toa >= bReturns true if a is greater than or equal to b.
<=Less than or equal toa <= bReturns true if a is less than or equal to b.

Example:

#include <iostream>
using namespace std;

int main() {
    int x = 10, y = 20;

    bool result1 = (x > y);  // false
    bool result2 = (x <= y); // true

    cout << "Is x greater than y? " << result1 << endl;  // Outputs: 0
    cout << "Is x less than or equal to y? " << result2 << endl; // Outputs: 1

    return 0;
}

Loop Boolean
It is common practice to utilize boolean values as loop conditions.

For instance, a while loop
#include <iostream>
using namespace std;

int main() {
    bool isRunning = true;
    int counter = 0;

    while (isRunning) {
        cout << "Counter: " << counter << endl;
        counter++;

        if (counter >= 5) {
            isRunning = false; // Exit the loop
        }
    }

    return 0;
}





← Back Next →

Labels:

C++ math

🗖 The math library in C++ offers a large number of functions for carrying out mathematical calculations. These functions, which are included in the header (short for "C Math"), include trigonometric functions, power, square root, logarithms, rounding, and more.

Commonly Used Math Functions in <cmath>

Function

Description

Example

abs(x)

Returns the absolute value of x.

abs(-5) → 5

sqrt(x)

Returns the square root of x.

sqrt(16) → 4

pow(base, exp)

Returns base raised to the power exp.

pow(2, 3) → 8

sin(x)

Returns the sine of x (in radians).

sin(3.14 / 2) → 1.0

cos(x)

Returns the cosine of x (in radians).

cos(0) → 1.0

tan(x)

Returns the tangent of x (in radians).

tan(0) → 0

log(x)

Returns the natural logarithm of x.

log(1) → 0

log10(x)

Returns the base-10 logarithm of x.

log10(100) → 2

exp(x)

Returns e^x (exponential function).

exp(1) → 2.71828...

ceil(x)

Returns the smallest integer ≥ x.

ceil(3.2) → 4

floor(x)

Returns the largest integer ≤ x.

floor(3.7) → 3

round(x)

Rounds x to the nearest integer.

round(2.5) → 3

fmod(x, y)

Returns the remainder of x / y.

fmod(7, 3) → 1

hypot(x, y)

Returns sqrt(x^2 + y^2).

hypot(3, 4) → 5



Example 01:

#include <iostream>
#include <cmath> // Include the cmath header

using namespace std;

int main() {
    double num1 = -5.6, num2 = 16, base = 2, exp = 3;

    // Absolute value
    cout << "Absolute value of " << num1 << ": " << abs(num1) << endl;

    // Square root
    cout << "Square root of " << num2 << ": " << sqrt(num2) << endl;

    // Power
    cout << base << " raised to the power " << exp << ": " << pow(base, exp) << endl;

    // Trigonometric functions
    double angle = 3.14159 / 4; // 45 degrees in radians
    cout << "sin(45 degrees): " << sin(angle) << endl;
    cout << "cos(45 degrees): " << cos(angle) << endl;

    // Logarithm
    cout << "Natural logarithm of 2: " << log(2) << endl;
    cout << "Base-10 logarithm of 100: " << log10(100) << endl;

    // Rounding functions
    cout << "Ceiling of " << num1 << ": " << ceil(num1) << endl;
    cout << "Floor of " << num1 << ": " << floor(num1) << endl;
    cout << "Round of " << num1 << ": " << round(num1) << endl;

    // Hypotenuse
    cout << "Hypotenuse of a right triangle with sides 3 and 4: " << hypot(3, 4) << endl;

    return 0;
}

← Back Next →

Labels:

C++ String

 A string in C++ is a collection of characters that are used to represent text. There are two main approaches to dealing with it:

C style (char arrays)
C++ (std::string)

Compared to C-style strings, C++ strings, which are specified in the Standard Template Library (STL), are more flexible and simpler to use. They are safe to use, offer a variety of built-in string manipulation capabilities, and enable dynamic memory management.

. C-style Strings
C-style strings are simple arrays of characters terminated by a null character (\0).

Example:

#include <iostream>
#include <cstring> // For C-style string functions
using namespace std;

int main() {
    char str1[] = "Hello";    // Declare and initialize
    char str2[20];            // Declare with size

    // Copy and concatenate
    strcpy(str2, str1);       // str2 becomes "Hello"
    strcat(str2, " World!");  // str2 becomes "Hello World!"

    cout << "C-style String: " << str2 << endl;

    // String length
    cout << "Length: " << strlen(str2) << endl;

    return 0;
}

Essential Roles:
strlen(): Determines the string's length.
One string can be copied into another using strcpy().
Two strings are concatenated using strcat().
strcmp(): Performs a string comparison.

Restrictions:
fixed size (established at the time of declaration).
Memory management must be done by hand.
prone to mistakes (for example, unable to remember the null character).

2. C++ Strings (std::string)
C++'s std::string class offers a dynamic, high-level, and secure substitute for C-style strings. Concatenation, comparison, substring extraction, and other operations are supported by this function, which is defined in the <string> header.

Declaration and Initialization

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "Hello";           // Initialization
    string str2("World!");           // Another way to initialize
    string str3 = str1 + " " + str2; // Concatenation

    cout << str3 << endl; // Output: Hello World!
    return 0;
}

Common String Operations
Length of a String

Use .length() or .size() to find the number of characters in the string.

string str = "Hello";
cout << "Length: " << str.length() << endl; // Output: 5

Accessing Characters

Use array-style indexing ([]) or .at()

string str = "Hello";
cout << str[0] << endl;   // Output: H
cout << str.at(1) << endl; // Output: e

Concatenation

Use + or .append() to combine strings.

string str1 = "Hello";
string str2 = " World!";
string result = str1 + str2;
cout << result << endl; // Output: Hello World!

Substring Extraction

Use .substr(position, length) to extract part of the string.

string str = "Hello World!";
string sub = str.substr(6, 5); // Extract "World" starting at index 6
cout << sub << endl; // Output: World

Finding Substrings

Use .find() to locate a substring or character.

string str = "Hello World!";
size_t pos = str.find("World");
if (pos != string::npos) {
    cout << "Found at index: " << pos << endl; // Output: Found at index: 6
}

Replace

Use .replace(startIndex, length, newString) to modify part of a string.

string str = "Hello World!";
str.replace(6, 5, "C++");
cout << str << endl; // Output: Hello C++!

Erasing Characters

Use .erase(startIndex, length) to remove part of a string.

string str = "Hello World!";
str.erase(5, 6); // Removes " World"
cout << str << endl; // Output: Hello!

Comparison

Use comparison operators (==, <, >) or .compare()

string str1 = "Hello";
string str2 = "World";
if (str1 < str2)
    cout << str1 << " comes before " << str2 << endl;

Iterating Through a String

Use a range-based for loop.

string str = "Hello";
for (char c : str) {
    cout << c << " ";
}
// Output: H e l l o

Example Program: C++ String Features:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "Hello";
    string str2 = "C++";

    // Concatenate strings
    string result = str1 + " " + str2;
    cout << "Concatenated string: " << result << endl;

    // Find and replace
    size_t pos = result.find("C++");
    if (pos != string::npos) {
        result.replace(pos, 3, "World");
    }
    cout << "After replacement: " << result << endl;

    // Substring extraction
    string sub = result.substr(6, 5);
    cout << "Substring: " << sub << endl;

    // Erase part of the string
    result.erase(5, 6);
    cout << "After erase: " << result << endl;

    return 0;
}

Advantages of std::string Over C-style Strings

FeatureC-style Stringsstd::string
Memory ManagementManual (programmer handles it)Automatic
Ease of UseLimited functionsRich built-in methods
SafetyProne to buffer overflowsException-safe, dynamic
Dynamic SizeFixed sizeAutomatically resizable



What Should I Use When?
For practically all situations, use std::string. It's more adaptable, simpler, and safer.
When working with legacy C code or for embedded systems with limited memory, use C-style strings.
You may take use of the ease and power of contemporary C++ by utilizing std::string!




← Back Next →

Labels: