تحديات while في لغة ++C: حلول مبتكرة لأسئلة متنوعة

codinglabsolution

 Q: Write C++ program to read two integer numbers then print "multiple" or "not" if one number is a multiple to another number. using while loop.

Sol//

#include <iostream>

using namespace std;

int main() {
    int num1, num2, counter;

    cout << "Enter the first integer: ";
    cin >> num1;

    cout << "Enter the second integer: ";
    cin >> num2;

    // Check for division by zero first
    if (num2 == 0) {
        cout << "Error: Division by zero." << endl;
        return 1; // Indicate error
    }

    counter = 1;
    bool isMultiple = false;

    while (counter * num2 <= num1) {
        if (counter * num2 == num1) {
            isMultiple = true;
            break;
        }
        counter++;
    }

    if (isMultiple) {
        cout << num1 << " is a multiple of " << num2 << endl;
    } else {
        cout << num1 << " is not a multiple of " << num2 << endl;
    }

    return 0;
}


Ex2: Write C++ program to read integer number and print the equivalent string. e.a: 0 ->zero 1-> one 2-> Two .

using while.

Sol//

#include <iostream>
#include <string>

using namespace std;

int main() {
    int num;
    string numberStrings[] = {"zero", "one", "two", "three", "four", "five",
                             "six", "seven", "eight", "nine"};

    cout << "Enter an integer between 0 and 9: ";
    cin >> num;

    // Input validation (optional)
    if (num < 0 || num > 9) {
        cout << "Invalid input. Please enter a number between 0 and 9." << endl;
        return 1; // Indicate error
    }

    int index = 0;
    bool found = false;

    while (index < 10 && !found) {
        if (index == num) {
            cout << numberStrings[index] << endl;
            found = true;
        }
        index++;
    }

    if (!found) {
        cout << "An unexpected error occurred." << endl; // Should never reach here with proper input validation
    }

    return 0;
}


Ex3: Write C++ program to read a score of student and print the estimation to refer it. e.a: 100 - 90 7 Exultant 89 - 80 ➔ Very good 79- 70 ➔ Good 69 - 60 7 Middle 59 - 50 ➔ Accept 49 - 0 ➔ Fail . using while.

Sol//

#include <iostream>

using namespace std;

int main() {
    int score;

    cout << "Enter the student's score (0-100): ";
    cin >> score;

    // Input validation (optional)
    if (score < 0 || score > 100) {
        cout << "Invalid score. Please enter a value between 0 and 100." << endl;
        return 1; // Indicate error
    }

    string estimations[] = {"Exultant", "Very good", "Good", "Middle", "Accept", "Fail"};
    int thresholds[] = {100, 90, 80, 70, 60, 50, 0}; // Assuming descending order

    int i = 0;
    while (i < 6 && score >= thresholds[i]) {
        i++;
    }

    cout << "Estimation: " << estimations[i - 1] << endl;

    return 0;
}


Ex4: Write C++ program to read an integer number and check if it is positive or negative, even or odd, and write a suitable messages in each case. using while loop.

Sol//

#include <iostream>

using namespace std;

int main() {
    int num;

    cout << "Enter an integer: ";
    cin >> num;

    string positiveNegative = (num >= 0) ? "positive" : "negative";
    string evenOdd = (num % 2 == 0) ? "even" : "odd";

    cout << num << " is " << positiveNegative << " and " << evenOdd << "." << endl;

    return 0;
}

Ex5: Write C++ program to reads a character and print if it is digit (0 .. 9), capital letter (A,B, ... ,Z), small letter (a, b, ... ,z), special character ( +, !, @, #, ~ {, >, ... ).  using while.

Sol//

 #include <iostream>
#include <cctype> // For character classification functions

using namespace std;

int main() {
    char ch;

    cout << "Enter a character: ";
    cin >> ch;

    bool isDigit = false;
    bool isUppercase = false;
    bool isLowercase = false;

    while (!isdigit(ch) && !isupper(ch) && !islower(ch)) {
        // No need to explicitly check for special characters here
        cout << ch << " is a special character." << endl;
        break; // Exit the loop after printing the message for a special character
    }

    if (!isDigit && !isUppercase && !isLowercase) {
        // This shouldn't happen with valid input, but handle unexpected characters
        cout << "An unexpected error occurred." << endl;
    } else {
        isDigit = isdigit(ch);
        isUppercase = isupper(ch);
        isLowercase = islower(ch);

        cout << ch << " is ";
        if (isDigit) {
            cout << "a digit." << endl;
        } else if (isUppercase) {
            cout << "an uppercase letter." << endl;
        } else if (isLowercase) {
            cout << "a lowercase letter." << endl;
        }
    }

    return 0;
}


Ex6- Write C++ program  to find the following series: using while loop.

Ex6- Write C++ program  to find the following series: using while loop.




Sol//

#include <iostream>
#include <cmath> // for pow function

using namespace std;

int main() {
    int n = 10; // Number of terms (change to 10 for the specific series)
    double sum = 0;
    int i = 1;

    while (i <= n) {
        sum += pow(2, i); // Calculate 2 raised to the power of i and add to the sum
        i++;
    }

    cout << "The sum of the series 2^1 + 2^2 + ... + 2^" << n << " is: " << sum << endl;

    return 0;
}



Ex7- Write C++ program  to find the following series: using while loop.

Ex7- Write C++ program  to find the following series: using do-while loop.


Sol//

#include <iostream>

using namespace std;

int main() {
    double z = 0.0;
    int sign = 1; // Start with positive sign
    int denominator = 3; // Initialize denominator

    while (denominator <= 13) {
        z += sign * (4.0 / denominator);
        sign *= -1; // Alternate signs
        denominator += 2; // Increment denominator by 2 for next odd number
    }

    cout << "The sum of the series z = 4 - 4/3 + 4/5 - 4/7 + ... + 4/13 is: " << z << endl;

    return 0;
}


Ex8: Write C++ program to inverse an integer number. For example: 7 65432 ➔ 234567 .using while loop?

Sol//

#include <iostream>
#include <limits> // for numeric_limits

using namespace std;

int main() {
    long long int num; // Use long long to handle larger numbers

    cout << "Enter an integer: ";
    cin >> num;

    // Check for negative input and handle overflow
    if (num < 0) {
        cout << "Error: Negative input is not allowed." << endl;
        return 1; // Indicate error
    } else if (num > numeric_limits<long long int>::max() / 10) {
        cout << "Error: Number too large for inversion." << endl;
        return 1; // Indicate error
    }

    long long int reversed = 0;
    int digit;

    while (num != 0) {
        digit = num % 10;
        reversed = reversed * 10 + digit;
        num /= 10;
    }

    cout << "The reversed number is: " << reversed << endl;

    return 0;
}


Ex9: Write C++ program that utilize looping and the escape sequence \t to print the following table of value:

 N  , 1 0 * N ,100 * N ,1000 * N 

1        10        100        1000

2        20        200        2000

3        30        300        3000

4        40        400        4000

Hint\t to print six spaces. using while loop.

Sol//

#include <iostream>

using namespace std;

int main() {
    int N;
    int i = 1; // Initialize loop counter

    cout << "Enter a value for N: ";
    cin >> N;

    cout << "N\t10 * N\t100 * N\t1000 * N\n"; // Header row with labels

    // Loop while i is less than or equal to 4
    while (i <= 4) {
        cout << i << "\t" << 10 * i << "\t" << 100 * i << "\t" << 1000 * i << endl;
        i++; // Increment loop counter
    }

    return 0;
}


Ex10 : Write C++ program to find e from the following series: e = 1 + (1 /1 !) + (1 /2!) + (1 /3!) + ... + (1 /n!) . using while loop.

Sol//

#include <iostream>
#include <cmath> // for std::factorial

using namespace std;

int main() {
    int n;
    double e = 1.0; // Initialize with 1

    cout << "Enter the number of terms (higher n for better accuracy): ";
    cin >> n;

    // Input validation (optional)
    if (n <= 0) {
        cout << "Error: Please enter a positive number of terms." << endl;
        return 1;
    }

    double factorial = 1.0;
    for (int i = 1; i <= n; ++i) {
        factorial *= i; // Calculate factorial for each term
        e += 1.0 / factorial; // Add the term to the approximation
    }

    cout << "Approximation of e with " << n << " terms: " << e << endl;

    return 0;
}


Ex10 : Write C++ program to find e from the following series: e = 1 + (1 /1 !) + (1 /2!) + (1 /3!) + ... + (1 /n!) . using while loop.

Sol//


#include <iostream>
#include <cmath> // for std::factorial

using namespace std;

int main() {
    int n;
    double e = 1.0; // Initialize with 1

    cout << "Enter the number of terms (higher n for better accuracy): ";
    cin >> n;

    // Input validation (optional)
    if (n <= 0) {
        cout << "Error: Please enter a positive number of terms." << endl;
        return 1;
    }

    double factorial = 1.0;
    int i = 1;
    while (i <= n) {
        factorial *= i; // Calculate factorial for each term
        e += 1.0 / factorial; // Add the term to the approximation
        i++;
    }

    cout << "Approximation of e with " << n << " terms: " << e << endl;

    return 0;
}


Ex11: Write C++ program to find e from the following series: e = 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... (x^a / a!) . using while loop.

Sol//

#include <iostream>
#include <cmath> // for std::factorial

using namespace std;

int main() {
    double x, e = 1.0; // Initialize with 1
    int a;

    cout << "Enter the value of x: ";
    cin >> x;

    cout << "Enter the power a (positive integer): ";
    cin >> a;

    // Input validation (optional)
    if (a <= 0) {
        cout << "Error: Please enter a positive power a." << endl;
        return 1;
    }

    double term = 1.0, power = x; // Initialize term and power
    int i = 1;

    while (i <= a) {
        term *= power / i; // Calculate next term (x^i / i!)
        e += term;         // Add the term to the approximation
        power *= x;        // Update power for next term
        i++;
    }

    cout << "Approximation of e for x = " << x << " and a = " << a << " terms: " << e << endl;

    return 0;
}


Ex 12: Write C++ program to print the following searies: