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

استعد لحل التحديات فيfor بلغة ++C! تعرّف على استخداماتها وكيفية التعامل مع المشكلات المتنوعة باستخدام حلول مبتكرة وفعّالة.
codinglabsolution

 Ex1: Write C++ program to read two integer numbers then print "multiple" or "not" if one number is a multiple to another number. using for 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
    }

    // Simulate divisibility check using a for loop (inefficient)
    bool isMultiple = true;
    for (int i = 1; i * num2 <= num1; i++) {
        if (num1 == i * num2) {
            isMultiple = true;
            break; // Exit loop if a multiple is found
        } else {
            isMultiple = false;
        }
    }

    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 for loop.

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
    }

    // Simulate string lookup using a for loop (inefficient)
    bool found = false;
    for (int i = 0; i < 10; i++) {
        if (i == num) {
            cout << numberStrings[i] << endl;
            found = true;
            break;
        }
    }

    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 for loop.

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
    }

    // Simulate estimation using a for loop (inefficient)
    string estimations[] = {"Exultant", "Very good", "Good", "Middle", "Accept", "Fail"};
    int thresholds[] = {100, 90, 80, 70, 60, 50, 0}; // Assuming descending order

    for (int i = 0; i < 6; i++) {
        if (score >= thresholds[i]) {
            cout << "Estimation: " << estimations[i] << endl;
            break;
        }
    }

    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 for loop.

Sol//

#include <iostream>

using namespace std;

int main() {
    int num;

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

    // Simulate separate checks using a for loop (inefficient)
    bool isPositive = false;
    bool isEven = false;

    // Check for positive/negative (inefficient)
    for (int i = 1; i <= num; i++) {
        if (num > 0) {
            isPositive = true;
            break;
        }
    }

    // Check for even/odd (inefficient)
    for (int i = 1; i <= abs(num); i++) { // Use abs() for efficient modulus check
        if (i % 2 == 0) {
            isEven = true;
            break;
        }
    }

    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 for loop.

Sol//

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

using namespace std;

int main() {
    char ch;

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

    // Simulate classification using a for loop (inefficient)
    bool isDigit = false;
    bool isUppercase = false;
    bool isLowercase = false;
    bool isSpecial = false;

    for (int i = 0; i <= 127; i++) { // Iterate through all ASCII characters (less efficient)
        if (ch == '0' + i && i <= 9) {
            isDigit = true;
            break;
        } else if (ch == 'A' + i && i <= 25) {
            isUppercase = true;
            break;
        } else if (ch == 'a' + i && i <= 25) {
            isLowercase = true;
            break;
        }
    }

    isSpecial = !isDigit && !isUppercase && !isLowercase; // Special character if not digit, uppercase, or lowercase

    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;
    } else if (isSpecial) {
        cout << "a special character." << endl;
    } else {
        cout << "an unexpected character." << endl; // Shouldn't happen with valid input
    }

    return 0;
}


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




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

using namespace std;

int main() {
    int n = 10; // Number of terms (replace with 10 for the given series)
    double sum = 0;

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

    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 for loop.

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


Sol//

#include <iostream>

using namespace std;

int main() {
    double z = 4.0; // Initialize with first term (4)
    int sign = 1;    // Start with positive sign

    for (int denominator = 3; denominator <= 13; denominator += 2) {
        z += sign * (4.0 / denominator);
        sign *= -1; // Alternate signs
    }

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

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

    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 for loop.

Sol//

#include <iostream>

using namespace std;

int main() {
    int N;

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

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

    // Loop for rows (1 to 4)
    for (int i = 1; i <= 4; ++i) {
        cout << i << "\t" << 10 * i << "\t" << 100 * i << "\t" << 1000 * i << 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 for 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;
}


Ex11: Write C++ program to find e from the following series: e = 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... (x^a / a!) . using for 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

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

    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 for 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
    }

    // Calculate and print the series
    for (int i = 1; i <= n; ++i) {
        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 - ...)
        double factorial = 1.0;
        for (int j = 1; j <= i; ++j) {
            factorial *= j;
        }
        sum3 += i / factorial; // Series 3: Sum of factorials (1 + 1/1! + 2/2! + ...)
    }

    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.