Friday, September 27, 2024

File-Based Sorting of Integer Data Using Selection Sort in C++

 #include <iostream>

#include <fstream>


using namespace std;


// Function to sort an array of integers using Selection Sort

void sortData(int arr[], int size) {

    for (int i = 0; i < size - 1; ++i) {

        for (int j = i+1; j < size; ++j) {

            if (arr[i] > arr[j]) {

                // Swap the elements

                int temp = arr[i];

                arr[i] = arr[j];

                arr[j] = temp;

            }

        }

    }

}


int main() {

    ifstream inputFile("input.txt");

    ofstream outputFile("output.txt");


    if (!inputFile) {

        cerr << "Error opening input file!" << endl;

        return 1;

    }


    if (!outputFile) {

        cerr << "Error opening output file!" << endl;

        return 1;

    }


    const int MAX_SIZE = 1000; // Maximum number of integers to handle

    int numbers[MAX_SIZE];

    int count = 0;


    // Read numbers from the input file

    while (inputFile >> numbers[count]) {

        count++;

        if (count >= MAX_SIZE) {

            cerr << "Too many numbers in input file. Max allowed is " << MAX_SIZE << endl;

            return 1;

        }

    }


    // Sort the data

    sortData(numbers, count);


    // Write the sorted numbers to the output file

    for (int i = 0; i < count; ++i) {

        outputFile << numbers[i] << endl;

    }


    // Close the files

    inputFile.close();

    outputFile.close();


    cout << "Data sorted and written to output.txt" << endl;


    return 0;

}

____________________

This C++ program reads a list of integers from a file named input.txt, sorts the numbers using the Selection Sort algorithm, and then writes the sorted numbers to a file named output.txt. Here's a breakdown of what the program does:

Include Libraries:

The program includes <iostream> for input/output operations and <fstream> for file handling.
Function to Sort Data (Selection Sort):

sortData(int arr[], int size) is a function that performs Selection Sort on the input array arr[] of size size. It repeatedly finds the smallest element in the unsorted part of the array and swaps it with the element at the beginning of the unsorted part.
Main Function:

File Handling:
ifstream inputFile("input.txt"); opens the input file for reading.
ofstream outputFile("output.txt"); opens the output file for writing.
It checks whether the files are opened successfully. If not, it prints an error message and terminates.
Reading Data from File:

The program defines a constant MAX_SIZE of 1000 to limit the number of integers it can handle. It reads the integers from input.txt into the array numbers[] until either the file ends or it reaches the limit of MAX_SIZE.
If more than 1000 numbers are present in the input file, an error message is printed, and the program exits.
Sorting the Data:

Once the integers are loaded into the array, the sortData() function is called to sort them using the Selection Sort algorithm.
Writing Data to Output File:

After sorting, the program writes the sorted integers to the output file output.txt.
Closing Files:

The input and output files are properly closed at the end.
Program Completion:

A success message Data sorted and written to output.txt is displayed on the console, indicating that the task was completed.
Key Components:
Input/Output: Reading from input.txt, writing to output.txt.
Selection Sort: Sorting algorithm to arrange the numbers in ascending order.
Error Handling: Checks if files are opened correctly and handles excessive input.
This program efficiently handles sorting and file I/O with simple error handling and basic sorting logic.

Sunday, November 12, 2023

N-point Star in Microsoft Visual Studio Console App

#include <windows.h>
#include <cmath>
#include <iostream>

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

int main() {
    int numberOfPoints;
    std::cout << "Enter the number of points for the star: ";
    std::cin >> numberOfPoints;

    const wchar_t CLASS_NAME[] = L"StarWindowClass";

    WNDCLASS wc = {};
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = GetModuleHandle(nullptr);
    wc.lpszClassName = CLASS_NAME;

    RegisterClass(&wc);

    HWND hwnd = CreateWindowEx(
        0,
        CLASS_NAME,
        L"Star Window",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 800, 600,
        nullptr,
        nullptr,
        GetModuleHandle(nullptr),
        nullptr
    );

    if (hwnd == nullptr) {
        return 0;
    }

    SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(&numberOfPoints));

    ShowWindow(hwnd, SW_SHOWNORMAL);

    MSG msg = {};
    while (GetMessage(&msg, nullptr, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

void DrawStar(HDC hdc, int centerX, int centerY, int radius, int numPoints) {
    const double PI = 3.14159265358979323846;

    double angle = 2 * PI / numPoints;


    // Create a yellow pen for lines
    HPEN hPen = CreatePen(PS_SOLID, 1, RGB(255, 255, 0));
    SelectObject(hdc, hPen);

    // Calculate the points of the star
    POINT points[1000]; // Assuming a maximum of 10 points for simplicity
    for (int i = 0; i < 1000; i++) {
        points[i].x = static_cast<int>(centerX + radius);
        points[i].y = static_cast<int>(centerY);
    }

    for (int i = 0; i < 3*numPoints; i+=3) {
        points[i].x = static_cast<int>(centerX + radius / 3. * cos(i * angle));
        points[i].y = static_cast<int>(centerY + radius / 3. * sin(i * angle));

        points[i+1].x = static_cast<int>(centerX + radius  * cos((i+0.5) * angle));
        points[i+1].y = static_cast<int>(centerY + radius  * sin((i+0.5) * angle));

        points[i + 2].x = static_cast<int>(centerX + radius/3. * cos((i + 1) * angle));
        points[i + 2].y = static_cast<int>(centerY + radius/3. * sin((i + 1) * angle));

    }

    // Draw the star outline
    Polygon(hdc, points, 3*numPoints);

    // Cleanup: delete created objects
    DeleteObject(hPen);
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch (uMsg) {
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;

    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hwnd, &ps);

        // Fill the background with blue color
        SetDCBrushColor(hdc, RGB(0, 0, 255));
        FillRect(hdc, &ps.rcPaint, (HBRUSH)GetStockObject(DC_BRUSH));

        int numberOfPoints = *reinterpret_cast<int*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));

        DrawStar(hdc, 400, 300, 100, numberOfPoints);

        EndPaint(hwnd, &ps);
    }
    return 0;

    default:
        return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
}

Friday, November 10, 2023

Design Class Called Date

Programming Challenges

1. Date

Design a class called Date.

The class should store a date in three integers: month, day, and year.
There should be member functions to print the date in the following forms:
12/25/2014
December 25, 2014
25 December 2014
Demonstrate the class by writing a C++ complete program implementing it.
Input Validation:
Do not accept values for the day greater than 31 or less than 1.
Do not accept values for the month greater than 12 or less than 1.
a) Use program example Pr13-2.cpp as a template to create your own program.
b) Use program example 3: Pr13-3.cpp as a template to create your own program.

Solution "a"

https://onlinegdb.com/vQSP4S3nH

Friday, November 3, 2023

C++ program that reads words from a file, sorts them in alphabetical order, and then writes the sorted words to another file

#include <iostream>

#include <fstream>

#include <string>


using namespace std; // Using the std namespace


// Custom sorting function to sort an array of strings

void customSort(string arr[], int size) {

    for (int i = 0; i < size - 1; i++) {

        for (int j = i + 1; j < size; j++) {

            if (arr[i] > arr[j]) {

                string temp = arr[i];

                arr[i] = arr[j];

                arr[j] = temp;

            }

        }

    }

}


int main() {

    const int MAX_WORDS = 1000; // Maximum number of words, adjust as needed

    string inputFileName = "input.txt";     // Name of the input file

    string outputFileName = "output.txt";   // Name of the output file

    string words[MAX_WORDS];               // Array to store words

    int wordCount = 0;                     // Count of words read


    // Open the input file

    ifstream inputFile(inputFileName);

    if (!inputFile) {

        cerr << "Error: Unable to open the input file." << endl;

        return 1;

    }


    // Read words from the input file

    string word;

    while (inputFile >> word && wordCount < MAX_WORDS) {

        words[wordCount] = word;

        wordCount++;

    }


    // Close the input file

    inputFile.close();


    // Sort the words in alphabetical order using the customSort function

    customSort(words, wordCount);


    // Open the output file

    ofstream outputFile(outputFileName);

    if (!outputFile) {

        cerr << "Error: Unable to open the output file." << endl;

        return 1;

    }


    // Write the sorted words to the output file

    for (int i = 0; i < wordCount; i++) {

        outputFile << words[i] << endl;

    }


    // Close the output file

    outputFile.close();


    cout << "Words have been sorted and written to " << outputFileName << "." << endl;


    return 0;

}


This program uses an fstream object to write data to a file.

// This program uses an fstream object to write data to a file.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream dataFile;
cout << "Opening file...\n";
dataFile.open("demofile.txt", ios::out); // Open for output
cout << "Now writing data to the file.\n";
dataFile << "Jones\n"; // Write line 1
dataFile << "Smith\n"; // Write line 2
dataFile << "Willis\n"; // Write line 3
dataFile << "Davis\n"; // Write line 4
dataFile.close(); // Close the file
cout << "Done.\n";
return 0;
}

Sunday, October 15, 2023

Draw X Code

<button onclick="drawX()">Draw X</button> <!-- Button to call the 'drawX' function when clicked -->
<button onclick="eraseAll()">Erase all</button> <!-- Button to call the 'eraseAll' function when clicked -->
<canvas height="400" id="field1" width="500"></canvas> <!-- HTML5 canvas element with a specific width and height, given the id 'field1' -->
<script>
// Function to draw X
function drawX(){
const sketch1 = document.querySelector('#field1'); // Get the canvas element with the id 'field1'
if (!sketch1.getContext) { return; } // Check if the canvas is supported in the browser
const ctx = sketch1.getContext('2d'); // Get the 2D drawing context of the canvas
// Set line stroke and line width
ctx.strokeStyle = 'red'; // Set the line color to red
ctx.lineWidth = 5; // Set the line width to 5 pixels
// Draw a red X using lines
x1 = 0; y1 = 0;
x2 = 500; y2 = 400;
x3 = 500; y3 = 0;
x4 = 0; y4 = 400;
ctx.moveTo(x1, y1); // Move to the starting point
ctx.lineTo(x2, y2); // Draw a line to the ending point
ctx.moveTo(x3, y3); // Move to another point
ctx.lineTo(x4, y4); // Draw another line to the ending point
ctx.stroke(); // Display the lines on the canvas
}
// Function to erase all
function eraseAll(){
const sketch2 = document.querySelector('#field1'); // Get the same canvas element with the id 'field1'
if (!sketch2.getContext) { return; } // Check if the canvas is supported in the browser
const ctx2 = sketch2.getContext('2d'); // Get the 2D drawing context of the canvas
ctx2.clearRect(0, 0, sketch2.width, sketch2.height); // Clear the entire canvas
}
</script> 
// Contributor: GeneralAstronomy110@gmail.com

File-Based Sorting of Integer Data Using Selection Sort in C++

 #include <iostream> #include <fstream> using namespace std; // Function to sort an array of integers using Selection Sort void ...