Friday, April 3, 2026

Write a program that displays the position of a character ch in the string S or – 1 if S doesn’t contain ch. || C Lab Program

 WAP_E04: Write a C program that displays the position of a character ch in the string S or – 1 if S doesn’t contain ch. || Strings


WAP_E04: C Lab Program


//position of a character ch in the string S or - 1 if S doesn't contain ch.
#include <stdio.h>
#include <string.h>

int main() {
    char str[100], ch;
    char *position;

    // Input string and character
    printf("Enter the string: ");
    fgets(str, sizeof(str), stdin);

    printf("Enter the character to find: ");
    scanf("%c", &ch);

    // Use strchr to find the first occurrence of ch in string S
    position = strchr(str, ch);
   
    // Check if character is found
    if (position) {
        // Output the index of the character
        printf("Position of '%c' in string: %d\n", ch, position - str);
    } else {
        printf("-1\n");  // If the character is not found
    }

    return 0;
}



OUTPUT


Enter the string: HelloWorld!
Enter the character to find: W
Position of 'W' in string: 5


For all 2026 published articles list: click here

...till the next post, bye-bye & take care

Credit Card Validator || 16 Intermediate Level C++ Projects

 Summary: 

A high-precision C++ utility designed to verify the structural validity of credit card numbers using the Luhn checksum. This project demonstrates string manipulation, algorithmic logic, and robust input sanitization.

Learning Objectives:

  1. Algorithmic Mastery: Implement the Luhn Algorithm logic (doubling, digit-summing, and modulo-10).

  2. String Processing: Learn to handle numeric data stored as std::string to bypass long long overflow limits.

  3. Input Sanitization: Differentiate between "Invalid Format" (non-digits) and "Invalid Checksum" (bad math).

  4. OOP Encapsulation: Organize logic into a cohesive CCValidator class.

The Source Code (main.cpp)

This code is optimized for the MinGW compiler in Code::Blocks. It includes <limits> to prevent the "console closing immediately" bug and <iomanip> for clean output formatting.

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <limits> // Required for clearing input buffer in Code::Blocks

using namespace std;

class CCValidator {
private:
    // Helper: Sums digits of a number (e.g., 14 becomes 1+4=5)
    int getDigitSum(int n) {
        return (n < 10) ? n : (n / 10 + n % 10);
    }

public:
    bool isValid(string cardNo) {
        int nSum = 0;
        bool isSecond = false;

        // Iterate from right to left
        for (int i = cardNo.length() - 1; i >= 0; i--) {
            // Basic sanitization: check if character is a digit
            if (!isdigit(cardNo[i])) return false;

            int d = cardNo[i] - '0';

            if (isSecond == true) {
                d = d * 2;
                d = getDigitSum(d);
            }

            nSum += d;
            isSecond = !isSecond;
        }

        return (nSum % 10 == 0);
    }
};

int main() {
    CCValidator validator;
    string input;

    cout << "========================================" << endl;
    cout << "   ACADEMIC CREDIT CARD VALIDATOR       " << endl;
    cout << "========================================" << endl;

    while (true) {
        cout << "\nEnter card number (or 'exit' to quit): ";
        cin >> input;

        if (input == "exit") break;

        if (validator.isValid(input)) {
            cout << ">> Result: [VALID] The checksum is correct." << endl;
        } else {
            cout << ">> Result: [INVALID] Checksum mismatch or bad format." << endl;
        }

        // Professor's Note: Standard Code::Blocks/MinGW buffer clear
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }

    cout << "\nProgram terminated. Press Enter to close...";
    cin.get();
    return 0;
}

Execution Trace (Sample Session)

========================================
  ACADEMIC CREDIT CARD VALIDATOR      
========================================

-- Case 1: Happy Path (Valid Input) --
Enter card number (or 'exit' to quit): 79927398713
>> Result: [VALID] The checksum is correct.

-- Case 2: Checksum Mismatch (Invalid Card) --
Enter card number (or 'exit' to quit): 79927398710
>> Result: [INVALID] Checksum mismatch or bad format.

-- Case 3: Error Handling (Non-numeric Input) --
Enter card number (or 'exit' to quit): 1234-5678-ABCD
>> Result: [INVALID] Checksum mismatch or bad format.

Enter card number (or 'exit' to quit): exit


Academic "Learning Corner"

The String Over Long Long Debate

In many introductory courses, students try to use long long cardNum;. Warning: A standard credit card is 16 digits. While long long can technically hold up to $\approx 1.8 \times 10^{19}$, reading it via cin >> longLongVar often fails if the user enters spaces or dashes. Using std::string is the "Architect's Choice" because it allows us to iterate through digits easily and handle cards of any length (like 15-digit Amex or 19-digit specialty cards).

The MinGW cin.ignore() Trick

If you run this in Code::Blocks and the window vanishes instantly, it's because the trailing newline character from your last input is still in the buffer. The line cin.ignore(numeric_limits<streamsize>::max(), '\n'); effectively "flushes" the toilet, ensuring the final cin.get() actually waits for your keypress.

Logic Tip: The "Subtract 9" Shortcut

In the Luhn algorithm, if a doubled digit is $> 9$ (like $8 \times 2 = 16$), we add the digits ($1+6=7$). Mathematically, for any doubled single digit, $d \times 2 - 9$ yields the exact same result as adding the digits of the product. It’s a cleaner way to write the logic!


eBook ‘16 Intermediate Level C++ Projects’ purchase Link: Google Play Store  || Google Books

eBook ‘16 Intermediate Level C++ Projects’ Promotional Link: 

Level Up from Coder to Architect: Master 16 Intermediate C++ Management Systems 


For all 2026 published articles list: click here

...till the next post, bye-bye & take care