حل اسئلة امتحان البرمجة المهيكلة بلغة C++ - قسم الحاسوب - الجامعة التكنولوجيا - جامعة بغداد

codinglabsolution


أسئلة امتحان البرمجة المهيكلة تهدف إلى تقييم فهم الطلاب للمفاهيم الأساسية للبرمجة ومهاراتهم في تطبيقها باستخدام لغة البرمجة C++. تتنوع هذه الأسئلة بين تطبيقات عملية وتمارين نظرية، وتشمل مواضيع مثل الحلقات، والشروط، والدوال، وأنواع البيانات المختلفة، والهياكل البيانية المتعددة، والمزيد.

سيتم تقديم الحلول بطريقة مفصلة ومنهجية، مما يساعد الطلاب على فهم الأسئلة وحلها بكفاءة. سنسلط الضوء على الخطوات الرئيسية لحل كل سؤال ونقدم شرحًا وافيًا للكود المستخدم، بالإضافة إلى توضيح الأفكار والمفاهيم الأساسية التي تحتاج إلى فهمها لحل السؤال بنجاح.

نأمل أن تكون هذه الحلول مفيدة لكم في استعدادكم لامتحاناتكم، وأن تساهم في تعزيز فهمكم للبرمجة المهيكلة باستخدام لغة C++.


Q1: Answer two of the following:

a: Write C++ program to calculate the summation of the following series. Sum = (-1)^4 +(-4)^4 + ... + (-25)^4 + (-28)^4.

Sol//

برنامج C++ لحساب مجموع المتسلسلة التالية:

#include <iostream>
#include <cmath> // For pow() function

using namespace std;

int main() {
  int n = 7; // Number of terms (from -1^4 to -28^4)
  long long sum = 0; // Use long long to handle larger sums

  for (int i = 1; i <= n; i++) {
    int power = pow(i, 4); // Calculate the fourth power of the current term
    int sign = (i % 2 == 0) ? -1 : 1; // Alternate signs for even and odd terms
    sum += sign * power;
  }

  cout << "Summation of the series: " << sum << endl;

  return 0;
}

b: Write C++ program to print the following figure:

1

333

55555

7777777

999999999

7777777

55555

333

1



Sol//

برنامج C++ لطباعة الشكل الماسي بالارقام:

#include <iostream>

using namespace std;

int main() {
  int rows = 5; // Number of rows (can be adjusted for a larger diamond)

  // Print the upper half of the diamond
  for (int i = 1; i <= rows; i++) {
    // Print leading spaces
    for (int j = 1; j <= rows - i; j++) {
      cout << " ";
    }

    // Print the number (repeated i times)
    for (int j = 1; j <= 2 * i - 1; j++) {
      cout << i;
    }

    cout << endl;
  }

  // Print the lower half of the diamond (excluding the middle row)
  for (int i = rows - 1; i >= 1; i--) {
    // Print leading spaces
    for (int j = 1; j <= rows - i; j++) {
      cout << " ";
    }

    // Print the number (repeated i times)
    for (int j = 1; j <= 2 * i - 1; j++) {
      cout << i;
    }

    cout << endl;
  }

  return 0;
}


C: Write C++ program using function named "sum from_to" that takes two integer arguments, call them "first" and "last", and returns as its value the sum of all the integers between first and last inclusive. Thus, for example,

cout << sum_from_to(4,7) << endl; // will print 22 because 4+5+6+7=22 .


Sol//

برنامج C++ مع دالة اسمها sum_from_to تحسب مجموع الأعداد الصحيحة بين رقمين (ضمنا):

#include <iostream>

using namespace std;

// Function to calculate the sum of integers from 'first' to 'last' (inclusive)
int sum_from_to(int first, int last) {
  if (first > last) {
    return 0;  // Handle invalid case (empty range)
  }

  // Use the arithmetic series formula for efficiency
  int n = last - first + 1;
  return n * (first + last) // 2 / n * (a1 + an)
}

int main() {
  int first, last;

  cout << "Enter the first number (inclusive): ";
  cin >> first;

  cout << "Enter the last number (inclusive): ";
  cin >> last;

  int sum = sum_from_to(first, last);

  cout << "Sum of integers from " << first << " to " << last << " (inclusive): " << sum << endl;

  return 0;
}


Q2: A program to find the factorial (n!) of the given number using the recursive function. It's the product of all integers from 1 to n (n is non negative)(so n != 1 if n=0 and n != n(n-1) if n>0).

Sol//

برنامج C++ للعثور على المضروب (n!) لعدد صحيح غير سالب 'n' باستخدام دالة عودية:

#include <iostream>

using namespace std;

// Function to calculate the factorial (n!) of a non-negative integer 'n'
unsigned long long factorial(unsigned int n) {
  if (n < 0) {
    throw invalid_argument("Factorial is not defined for negative numbers");
  } else if (n == 0) {
    return 1;
  } else {
    return n * factorial(n - 1);
  }
}

int main() {
  unsigned int number;

  cout << "Enter a non-negative integer: ";
  cin >> number;

  try {
    unsigned long long result = factorial(number);
    cout << "The factorial of " << number << " is: " << result << endl;
  } catch (const invalid_argument& e) {
    cerr << e.what() << endl;
  }

  return 0;
}


Q3: Answer one of the following: (10 marks)

a: Write C++ program which input the values of 2-dimensional array A(3,4) and perform the following:

1. Replace each element in the first row by the constant (3).

2. Exchange the values of the second column with the values of the last column.

Sol//

#include <iostream>

using namespace std;

int main() {
  const int rows = 3;
  const int cols = 4;
  int A[rows][cols];

  // Read elements for the 2D array
  cout << "Enter elements for the 3x4 array:\n";
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      cin >> A[i][j];
    }
  }

  // Replace elements in the first row with 3
  for (int j = 0; j < cols; j++) {
    A[0][j] = 3;
  }

  // Swap elements between the second and last columns
  for (int i = 0; i < rows; i++) {
    swap(A[i][1], A[i][cols - 1]);
  }

  // Print the modified array
  cout << "\nModified array:\n";
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      cout << A[i][j] << " ";
    }
    cout << endl;
  }

  return 0;
}


b: Write C++ program to read two integer numbers, and read the operation to perform on these numbers (using switch).

Sol//

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

using namespace std;

int main() {
    int num1, num2;
    char operation;

    cout << "Enter two integer numbers: ";
    cin >> num1 >> num2;

    cout << "Enter the operation (+, -, *, /): ";
    cin >> operation;

    double result; // Use double for potentially floating-point division results

    switch (operation) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            if (num2 == 0) {
                cout << "Error: Division by zero." << endl;
                return 1; // Indicate error
            }
            result = static_cast<double>(num1) / num2; // Cast to double for division
            break;
        default:
            cout << "Invalid operation." << endl;
            return 1; // Indicate error
    }

    cout << "Result: " << num1 << " " << operation << " " << num2 << " = " << result << endl;

    return 0;
}


Q4: a: Write C++ program to compute the number of zeros in 1-dimensional array a[10].

Sol//

برنامج C++ لحساب عدد الأصفار في مصفوفة أحادية البعد a[10]:

#include <iostream>

using namespace std;

int main() {
  const int size = 10; // Array size
  int a[size];
  int countZeros = 0;

  // Read elements for the array
  cout << "Enter elements for the array a[10]:\n";
  for (int i = 0; i < size; i++) {
    cin >> a[i];
  }

  // Count the number of zeros
  for (int i = 0; i < size; i++) {
    if (a[i] == 0) {
      countZeros++;
    }
  }

  // Print the result
  cout << "Number of zeros in the array: " << countZeros << endl;

  return 0;
}


b: Develop a program in C++ to read the following information using structure case_name, case_code, case_age, case_illness, date of entering to the hospital (dd,mm, yyyy) for 100 patient and print the date entered to the hospital and name of the patient that entered with code between (50-90).

Sol//

برنامج C++ لقراءة معلومات المريض باستخدام هيكل وتخزينها لـ 100 مريض وطباعة تاريخ وأسماء المرضى برموز تتراوح بين 50 و90:

#include <iostream>
#include <string>

using namespace std;

struct Patient {
  string case_name;
  int case_code;
  int case_age;
  string case_illness;
  struct {
    int dd;
    int mm;
    int yyyy;
  } date_admitted;
};

int main() {
  const int num_patients = 100;
  Patient patients[num_patients];

  // Read patient information
  cout << "Enter information for 100 patients:\n";
  for (int i = 0; i < num_patients; i++) {
    cout << "Patient " << i + 1 << ":" << endl;
    cout << "  Name: ";
    getline(cin, patients[i].case_name);
    cout << "  Code: ";
    cin >> patients[i].case_code;
    cout << "  Age: ";
    cin >> patients[i].case_age;
    cin.ignore(); // Consume newline character after age input
    cout << "  Illness: ";
    getline(cin, patients[i].case_illness);
    cout << "  Date admitted (DD MM YYYY): ";
    cin >> patients[i].date_admitted.dd >> patients[i].date_admitted.mm >> patients[i].date_admitted.yyyy;
    cin.ignore(); // Consume newline character after date input
  }

  // Print patients with code between 50 and 90
  cout << "\nPatients with code between 50 and 90:\n";
  for (int i = 0; i < num_patients; i++) {
    if (patients[i].case_code >= 50 && patients[i].case_code <= 90) {
      cout << "  Name: " << patients[i].case_name << endl;
      cout << "  Date admitted: " << patients[i].date_admitted.dd << "/"
           << patients[i].date_admitted.mm << "/" << patients[i].date_admitted.yyyy << endl;
    }
  }

  return 0;
}


Q5: a: Write the output of the following programs with trace (Only One):

1:

#include<iostream.h>

void main ()

int *x, *p,*q;

int c=200,a;

x=&c;

p=x+10;

q=x-10;

a=p-q;

cout << "The address of x :" << x << endl;

cout << "The address of p after incrementing x by 2: " << p << endl;

cout << "The address of q after decrementing x by 2: " << q << endl;

cout << "The value of a is: " << a << endl;

Sol//
The address of x :0x22ff14 The address of p after incrementing x by 2: 0x22ff38 The address of q after decrementing x by 2: 0x22fee0 The value of a is: 90


2:

#include <iostream.h>

int main( )

int n;

cout << (n=4) << endl;

cout << (n=4) << endl;

cout << (n>3) << endl;

cout << (n<4) << endl;

cout << (n=0) << endl;

cout << (n == 0) << endl;

cout << (n>0) << endl;

cout << (n && 4) << endl;

cout << (n || 4) << endl;

cout << (!n) << endl;

return 0;

Sol//

4

4

1

0

0

1

0

0

1

b: Correct and find the output for the following program.
#include<iostream.h>
main()
int i=1;
if(i<>1) cout << ' **;
cout << '*';
else
cout << '+';

Sol//

#include <iostream>

int main() {
    int i = 1;
    if (i != 1)
        cout << " **";
        cout << '*';
    else
        cout << '+';
    return 0;
}



C: Draw a flowchart to print odd numbers from 33 to 55.
Sol//

+---------------------+
|    Start            |
+---------------------+
           |
           v
+---------------------+
|    Initialize       |
|      num = 33       |
+---------------------+
           |
           v
+---------------------+
|      Loop           |
|   num <= 55 ?       |
+---------------------+
           |
           |
           v
+---------------------+
|   Is num odd?       |
|  (num % 2 != 0) ?   |
+---------------------+
     |         |
     |         |
     v         |
+---------------------+
| Print num           |
+---------------------+
           |
           |
           v
+---------------------+
|     Increment num   |
|       by 2          |
+---------------------+
           |
           |
           v
+---------------------+
|     End loop        |
+---------------------+
           |
           v
+---------------------+
|        End          |
+---------------------+
```




Q1: Write a C++ to read an integer number x. Answer One only. (10 Marks)
1. Find and print the result of y = 1+3+5+ ... +(2x+1)
2. Find and print the result of y = x + 3x + 5x + ... +(2x+1)x
Sol//

I'd be glad to provide the C++ code that incorporates both functionalities you requested:

C++
#include <iostream>

using namespace std;

int main() {
    int x;

    // Prompt the user to enter an integer
    cout << "Enter an integer: ";

    // Read the input from the user
    cin >> x;

    // Calculate the sum of the series y = 1 + 3 + 5 + ... + (2x + 1)
    int y1 = x * (x + 1);

    // Calculate the sum of the series y = x + 3x + 5x + ... + (2x + 1)x
    int y2 = x * x * (x + 1);

    // Print the results
    cout << "The sum of the series 1 + 3 + 5 + ... + (2x + 1) is: " << y1 << endl;
    cout << "The sum of the series x + 3x + 5x + ... + (2x + 1)x is: " << y2 << endl;

    return 0;
}


Q2: Write a C++ program to read an array of n elements. Answer Two only. (10 Marks)

1. Find the factorial of the smallest number.

2. Find their average.

3. Find the average of even numbers.

Sol//

برنامج C++ يقرأ مصفوفة من العناصر n، ويجد مضروب أصغر رقم، ويحسب متوسط جميع العناصر، ويجد متوسط الأرقام الزوجية:

#include <iostream>

using namespace std;

// Function to calculate factorial (works for non-negative integers)
long long factorial(int n) {
    if (n < 0) {
        return -1; // Handle negative input (optional)
    } else if (n == 0) {
        return 1;
    } else {
        long long result = 1;
        for (int i = 1; i <= n; ++i) {
            result *= i;
        }
        return result;
    }
}

int main() {
    int n;

    // Prompt the user to enter the size of the array
    cout << "Enter the size of the array: ";
    cin >> n;

    if (n <= 0) {
        cout << "Invalid array size (must be positive)." << endl;
        return 1; // Indicate error
    }

    int arr[n];

    // Read the elements of the array
    cout << "Enter the elements of the array: ";
    for (int i = 0; i < n; ++i) {
        cin >> arr[i];
    }

    // Find the smallest number
    int smallest = arr[0];
    for (int i = 1; i < n; ++i) {
        if (arr[i] < smallest) {
            smallest = arr[i];
        }
    }

    // Calculate the factorial of the smallest number
    long long smallestFactorial = factorial(smallest);

    // Calculate the sum and average of all elements
    double sum = 0.0;
    for (int i = 0; i < n; ++i) {
        sum += arr[i];
    }
    double average = sum / n;

    // Count and sum even numbers for their average (optional check for 0)
    int evenCount = 0;
    double evenSum = 0.0;
    for (int i = 0; i < n; ++i) {
        if (arr[i] % 2 == 0 && arr[i] != 0) { // Check for even and non-zero
            evenCount++;
            evenSum += arr[i];
        }
    }
    double evenAverage = evenCount > 0 ? evenSum / evenCount : 0.0; // Avoid division by zero

    // Print the results
    cout << "Factorial of the smallest number: " << smallestFactorial << endl;
    cout << "Average of all elements: " << average << endl;
    cout << "Average of even numbers (excluding 0): " << evenAverage << endl;

    return 0;
}


Q3: Write a C++ program to read a 2D array of n x m elements. Answer Two only. (10 Marks)

1. Print all elements of the even indexed rows.

2. Print all elements of the odd indexed columns.

3. Print all even elements.

4. Print all odd elements dividable by 3.

Sol//

برنامج C++ لقراءة مصفوفة ثنائية الأبعاد من عناصر nxm وتنفيذ العمليات المحددة:

#include <iostream>

using namespace std;

int main() {
    int n, m;

    // Prompt the user to enter the dimensions of the array
    cout << "Enter the number of rows (n): ";
    cin >> n;
    cout << "Enter the number of columns (m): ";
    cin >> m;

    if (n <= 0 || m <= 0) {
        cout << "Invalid array dimensions (must be positive)." << endl;
        return 1; // Indicate error
    }

    int arr[n][m];

    // Read the elements of the array
    cout << "Enter the elements of the array (row-wise):" << endl;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            cin >> arr[i][j];
        }
    }

    // 1. Print all elements of the even indexed rows
    cout << "\nElements of even indexed rows:\n";
    for (int i = 0; i < n; i += 2) { // Iterate by even indices
        for (int j = 0; j < m; ++j) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }

    // 2. Print all elements of the odd indexed columns
    cout << "\nElements of odd indexed columns:\n";
    for (int i = 0; i < n; ++i) {
        for (int j = 1; j < m; j += 2) { // Iterate by odd indices
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }

    // 3. Print all even elements
    cout << "\nAll even elements:\n";
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            if (arr[i][j] % 2 == 0) {
                cout << arr[i][j] << " ";
            }
        }
    }
    cout << endl;

    // 4. Print all odd elements dividable by 3
    cout << "\nAll odd elements dividable by 3:\n";
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            if (arr[i][j] % 2 != 0 && arr[i][j] % 3 == 0) {
                cout << arr[i][j] << " ";
            }
        }
    }
    cout << endl;

    return 0;
}


Q4: Answer One only. (10 Marks)

1. Convert the "for" loop to "while" and run Code 1.

Code 1

int A[]={13, 1,-5, 20, -5, -100};

int i, j, temp, index;

for(i=0; i < 5; i++){

temp = A[i];

for(j=i+1;j<6; j++)

if(a[j] <= temp)

index = j;

A[i] = A[index];

A[index] = temp;
}


Sol//

#include <iostream>

using namespace std;

int main() {
    int A[] = {13, 1, -5, 20, -5, -100};
    const int n = sizeof(A) / sizeof(A[0]); // Array size (avoid hardcoding)

    int i = 0;
    while (i < n - 1) {
        int temp = A[i];
        int index = i + 1;

        while (index < n) {
            if (A[index] <= temp) {
                temp = A[index];
                index = i + 1; // Reset inner loop index if a smaller element is found
            }
            index++;
        }

        A[i] = temp; // Swap with the minimum element found
        i++;
    }

    // Print the sorted array (optional)
    cout << "Sorted array: ";
    for (int i = 0; i < n; i++) {
        cout << A[i] << " ";
    }
    cout << endl;

    return 0;
}


2. Correct and run Code 2.

Code 2

A[]=[50, 23, 0, 14, -1, 90, 85, 74, 0, 10];


for(i=0; i < 9; i++)

temp= B(i);

for(j=i+1;j<10; j++)

if(a(j)<temp)

index = j;

A[I] = A[index]

A[index] = temp
]

Sol//


#include <iostream>

using namespace std;

int main() {
    int A[] = {50, 23, 0, 14, -1, 90, 85, 74, 0, 10};
    int B[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Assuming B is another array

    for (int i = 0; i < 9; i++) { // Iterate 9 times (excluding the last element)
        int temp = B[i]; // Access element from array B

        for (int j = i + 1; j < 10; j++) { // Iterate from i+1 to 9 (within bounds)
            if (A[j] < temp) { // Compare elements of A
                int index = j;
                A[i] = A[index]; // Swap elements in A
                A[index] = temp;
            }
        }
    }

    // Print the sorted array (optional)
    cout << "Sorted array: ";
    for (int i = 0; i < 10; i++) {
        cout << A[i] << " ";
    }
    cout << endl;

    return 0;
}


Q5: Write a C++ program to read a sequence of n marks. Print the largest, smallest and average of all marks. (10 Marks)

Sol//

إليك برنامج C++ لقراءة سلسلة من العلامات n، والعثور على أكبر وأصغر ومتوسط جميع العلامات:


#include <iostream>

using namespace std;

int main() {
    int n;

    // Prompt the user to enter the number of marks
    cout << "Enter the number of marks: ";
    cin >> n;

    if (n <= 0) {
        cout << "Invalid number of marks (must be positive)." << endl;
        return 1; // Indicate error
    }

    double marks[n]; // Use double for potentially decimal marks

    // Read the marks
    cout << "Enter the marks (separated by spaces): ";
    for (int i = 0; i < n; ++i) {
        cin >> marks[i];
    }

    // Initialize variables
    double largest = marks[0];
    double smallest = marks[0];
    double sum = 0.0;

    // Find the largest and smallest marks
    for (int i = 1; i < n; ++i) {
        if (marks[i] > largest) {
            largest = marks[i];
        }
        if (marks[i] < smallest) {
            smallest = marks[i];
        }
    }

    // Calculate the sum for average
    for (int i = 0; i < n; ++i) {
        sum += marks[i];
    }

    // Calculate the average
    double average = sum / n;

    // Print the results
    cout << "Largest mark: " << largest << endl;
    cout << "Smallest mark: " << smallest << endl;
    cout << "Average of marks: " << average << 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.