حل اسئلة امتحان البرمجة المهيكلة بلغة 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