Showing posts with label cpp. Show all posts
Showing posts with label cpp. Show all posts

Saturday

Newton-Raphson Method in C++

The Newton Raphson Method is an open method used to find the roots of a function.
It employs the technique of linear approximation and involves using the tangent line to approximate the roots.
The method is highly efficient and converges rapidly, providing robust solutions in fewer iterations.

File content:

{{{{{

#include <iostream>

#include <cmath>

using namespace std;


const double EPS = 0.000001;


double function(double x0)

{

    // x0^2 - 3*x0 + 2 = (x0 - 1)(x0 - 2)

    return x0*x0 - 3*x0 + 2;

}


double derivative_of_the_function(double x0)

{

    return 2*x0 - 3;

}


int main()

{

    int max;

    int i = 0;

    double x1, x0;


    cout << "Newton-Raphson Method in C++" << endl;

    cout << "Maximum number of iterations: ";

    max = 100;

    cout << max << endl;

    cout << "The first approximation: ";

    x0 = 0; // you get the root 1

    //x0 = 3; // you get the root 2

    cout << x0 << endl;


    bool flagStopLoop = false;

    do

    {

        x1 = x0 - (function(x0) / derivative_of_the_function(x0));

        i++;


        if( fabs(x1 - x0) <= EPS )

        {

            flagStopLoop = true;

        }

        else if( i > max )

        {

            flagStopLoop = true;

        }

        else

        {

            x0 = x1;

        }

    } while( !flagStopLoop );

    cout << "The root of the function after " << i << " iteration is "

         << x1 << endl;


    return 0;

}

}}}}}

Safe C++ example using array data structure and at member function

The safe C++ at() member function automatically checks whether array index is within the bounds of valid elements in the container, throwing an out_of_range exception if the array index is not, i.e. if the array index is greater than or equal to its array size.
The member function at() does check against bounds.
Here's a C++ program that uses the array data structure and at() member function.

#include <iostream>

#include <array>

using namespace std;


int main()

{

    array<string, 12> month_names = { "January",

                                      "February",

                                      "March",

                                      "April",

                                      "May",

                                      "June",

                                      "July",

                                      "August",

                                      "September",

                                      "October",

                                      "November",

                                      "December",

                                    };


    cout << "month_names.at(11): " << month_names.at(11) << endl;



    // terminate called after throwing an instance of std::out_of_range exception

    cout << "month_names.at(13): " << month_names.at(13) << endl;


    return 0;

}

Safe C++ example: stack data structure implementation

Safe C++ programming practices aim to prevent common programming errors, such as memory leaks, buffer overflows, and undefined behavior. This is often achieved through techniques like RAII (Resource Acquisition Is Initialization), smart pointers, and range-based for loops.

Example: Implementing a Stack data structure Using vector

Here's a C++ program that implements a stack using the vector container. This approach leverages RAII to automatically manage memory, making it safer than a manual stack implementation.

#include <iostream>

#include <vector>

using namespace std;


template <typename T>

class Stack {

private:

    vector<T> data;


public:

    void push(const T& value) {

        data.push_back(value);

    }


    void pop() {

        if (!isEmpty()) {

            data.pop_back();

        }

    }


    T top() const {

        return data.back();

    }


    bool isEmpty() const {

        return data.empty();

    }

};


int main() {

    Stack<int> myStack;


    myStack.push(10);

    myStack.push(20);

    myStack.push(30);


    myStack.pop();


    cout << "Top element: " << myStack.top() << endl;


    cout << "Stack empty? " << boolalpha << myStack.isEmpty() << endl;


    return 0;

}


Explanations:
* vector: This container is used to store the elements of the stack. It automatically manages memory allocation and deallocation, preventing memory leaks.
* RAII (Resource Acquisition Is Initialization): The vector's destructor is called automatically when it goes out of scope, ensuring that the memory it allocated is freed.
* Template: The Stack class is a template, making it versatile for different data types.
* Safe Operations: The push, pop, and top functions are designed to be safe. They check for empty conditions before performing operations to avoid undefined behavior.

C++ Key Safety Features:
* Memory Management: vector handles memory allocation and deallocation automatically.
* Exception Safety: The Stack class can be made exception-safe by using techniques like RAII and proper exception handling.
* Range-Based For Loops: Consider using range-based for loops for iterating over elements in a safer and more concise manner.
* Move Semantics: For performance, especially with large objects, consider using move semantics to avoid unnecessary copies.
* Custom Allocators: For specific memory management needs, you can provide a custom allocator to vector.

By following these practices, you can write more safe and more reliable C++ code.

Multiple Languages in Spoken Words

Lax lah. - English, Malay.   Sik Zo Mei, Chi1, Simi Lay. = Chinese1, Chinese2, Chinese3. This barang is cikai one lah. = English, Malay, Chi...