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

استعد لحل التحديات في do-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 do-while loop.

Sol//

#include <iostream>

using namespace std;

int main() {
    int num1, num2;

    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
    }

    int counter = 1;
    bool isMultiple = false;

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

    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 do-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 i = 0;
    bool found = false;

    do {
        if (i == num) {
            cout << numberStrings[i] << endl;
            found = true;
            break;
        }
        i++;
    } while (i < 10);

    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 do-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;
    bool found = false;

    do {
        if (score >= thresholds[i]) {
            cout << "Estimation: " << estimations[i] << endl;
            found = true;
            break;
        }
        i++;
    } while (i < 6 && !found);

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

    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 do-while loop.

Sol//

#include <iostream>

using namespace std;

int main() {
    int num;

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

    bool isPositive = true; // Assume positive initially (for do-while loop)
    bool isEven = true;     // Assume even initially (for do-while loop)

    int i = 1;
    do {
        if (num < 0) {
            isPositive = false;
            break;
        }
        i++;
    } while (i <= abs(num)); // Check for positive/negative

    i = 1; // Reset counter for even/odd check
    do {
        if (i % 2 != 0) {
            isEven = false;
            break;
        }
        i += 2;  // Only check even numbers for efficiency
    } while (i <= abs(num)); // Check for even/odd

    cout << num << " is ";
    if (isPositive) {
        cout << "positive";
    } else {
        cout << "negative";
    }

    cout << " and ";
    if (isEven) {
        cout << "even." << endl;
    } else {
        cout << "odd." << 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 do-while.

Sol//

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

using namespace std;

int main() {
    char ch;

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

    bool isFound = false;

    do {
        if (isdigit(ch)) {
            cout << ch << " is a digit." << endl;
            isFound = true;
            break;
        } else if (isupper(ch)) {
            cout << ch << " is an uppercase letter." << endl;
            isFound = true;
            break;
        } else if (islower(ch)) {
            cout << ch << " is a lowercase letter." << endl;
            isFound = true;
            break;
        }
        // No need to explicitly check for special characters here
    } while (!isFound);

    return 0;
}


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

Ex6- Write C++ program  to find the following series: using do-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;

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

    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 do-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

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

    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 do-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;

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

    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 do-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 do-while (executes at least once)
    do {
        cout << i << "\t" << 10 * i << "\t" << 100 * i << "\t" << 1000 * i << endl;
        i++; // Increment loop counter
    } while (i <= 4);

    return 0;
}


Ex10 : Write C++ program to find e from the following series: e = 1 + (1 /1 !) + (1 /2!) + (1 /3!) + ... + (1 /n!) . using do-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;

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

    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 do-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;

    do {
        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++;
    } while (i <= a);

    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: 

1. Sum=1+2^2 +4^2 + ... +n^2 

2. Sum=1-3^x+5^x-... +n^x 

3. Sum=1 + 1/1! +2/2!+3/3! + ... +n/n!   where n!=1 *2*3* ... *n ..using do-while  loop.

Sol//

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

using namespace std;

int main() {
    int n;
    double sum1 = 0, sum2 = 0, sum3 = 0;
    double x; // for series 2

    cout << "Enter the number of terms (n): ";
    cin >> n;

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

    cout << "Enter the value of x for series 2 (optional, enter 0 for default 1): ";
    cin >> x;
    if (x == 0) {
        x = 1; // Set default value for x
    }

    int i = 1;
    double factorial = 1.0;

    // Calculate and print the series using do-while loops
    do {
        sum1 += pow(i, 2);  // Series 1: Sum of squares (1^2 + 2^2 + ... + n^2)
        sum2 += pow(-1, i + 1) * pow(x, i); // Series 2: Alternating series (1 - 3x + 5x^2 - ...)

        // Calculate factorial for series 3 within the loop for efficiency
        factorial *= i;
        sum3 += i / factorial; // Series 3: Sum of factorials (1 + 1/1! + 2/2! + ...)

        i++;
    } while (i <= n);

    cout << "Series 1 (Sum of squares): " << sum1 << endl;
    cout << "Series 2 (Alternating series): " << sum2 << endl;
    cout << "Series 3 (Sum of factorials): " << sum3 << endl;

    return 0;
}




إرسال تعليق

ملفات تعريف الارتباط
نستخدم ملفات تعريف الارتباط (Cookies) لفهم كيفية استخدامك لموقعنا وتحسين تجربتك في المحتوى والإعلانات. باستمرارك في تصفح الموقع، فإنك توافق على استخدامنا لملفات تعريف الارتباط وفقًا لسياسة الخصوصية لدينا.
أُووبس!
يبدو أن هناك خطأ ما في اتصالك بالإنترنت. يرجى الاتصال بالإنترنت وبدء التصفح مرة أخرى.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.