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

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

Ex1: Write a C++ program, using function, to counts uppercase letter in a 20 letters entered by the user in the main program.

Sol//

برنامج C++ لحساب الأحرف الكبيرة في سلسلة مكونة من 20 حرفًا يدخلها المستخدم:


#include <iostream>
#include <string>

using namespace std;

int countUppercase(string str) {
  int count = 0;
  for (char c : str) {
    if (isupper(c)) {
      count++;
    }
  }
  return count;
}

int main() {
  char input[21]; // Array to store 20 letters + null terminator

  cout << "Enter 20 letters: ";
  cin.getline(input, 21); // Read entire line with maximum 20 characters

  int uppercaseCount = countUppercase(input);
  cout << "Number of uppercase letters: " << uppercaseCount << endl;

  return 0;
}


Ex2: Write a C++ program, using function, that reads two integers (feet and inches) representing distance, then converts this distance to meter.

Note: 1 foot = 12 inch

1 inch = 2.54 Cm

Input: feet: 8 or inches: 9

Sol//

برنامج C++ لتحويل القدم والبوصة إلى متر باستخدام الوظائف:


#include <iostream>

using namespace std;

float convertDistance(int feet, int inches) {
  const float INCHES_PER_FOOT = 12.0f;
  const float CM_PER_INCH = 2.54f;
  // Convert feet to inches and add inches
  float totalInches = feet * INCHES_PER_FOOT + inches;
  // Convert total inches to meters
  return totalInches * CM_PER_INCH / 100.0f;
}

int main() {
  int feet, inches;

  cout << "Enter feet: ";
  cin >> feet;

  cout << "Enter inches: ";
  cin >> inches;

  float meters = convertDistance(feet, inches);
  cout << feet << " feet and " << inches << " inches is equal to " << meters << " meters." << endl;

  return 0;
}


Ex3: Write a C++ program, using function, which reads an integer value (T)representing time in seconds, and converts it to equivalent hours (hr),

minutes (mn), and seconds (sec), in the following form: hr : mn : sec

i.e .:

Input: 4000

Output: 1:6:40

Sol//

برنامج C++ لتحويل الثواني إلى ساعات ودقائق وثواني باستخدام دالة:

#include <iostream>

using namespace std;

void convertSeconds(int seconds, int& hours, int& minutes, int& remainingSeconds) {
  // Calculate hours
  hours = seconds / 3600;
  // Calculate remaining seconds after removing hours
  remainingSeconds = seconds % 3600;

  // Calculate minutes from remaining seconds
  minutes = remainingSeconds / 60;
  // Calculate remaining seconds after removing minutes
  remainingSeconds = remainingSeconds % 60;
}

int main() {
  int totalSeconds;

  cout << "Enter time in seconds: ";
  cin >> totalSeconds;

  int hours, minutes, seconds;
  convertSeconds(totalSeconds, hours, minutes, seconds);

  cout << hours << " : " << minutes << " : " << seconds << endl;

  return 0;
}


Ex4: Write a C++ program, using function, to see if a number is an integer (odd or even) or not an integer.

Sol//

برنامج C++ للتحقق مما إذا كان الرقم عددًا صحيحًا (فرديًا أو زوجيًا) أو ليس عددًا صحيحًا باستخدام الوظائف:

#include <iostream>

using namespace std;

bool isInteger(float number) {
  // Check if the decimal part is zero (within a small tolerance)
  return (abs(number - floor(number)) < 1e-6);
}

bool isOdd(int number) {
  return (number % 2 != 0);
}

int main() {
  float number;

  cout << "Enter a number: ";
  cin >> number;

  if (isInteger(number)) {
    cout << number << " is an integer." << endl;
    if (isOdd(static_cast<int>(number))) {
      cout << number << " is odd." << endl;
    } else {
      cout << number << " is even." << endl;
    }
  } else {
    cout << number << " is not an integer." << endl;
  }

  return 0;
}


Ex5: Write a C++ program, using function, to represent the permutation of n.

Sol//

برنامج C++ يستخدم وظائف لتمثيل التباديل لـ n:

#include <iostream>
#include <vector>

using namespace std;

void permute(vector<int>& data, int start, int end, vector<vector<int>>& permutations) {
  if (start == end) {
    permutations.push_back(data); // Base case: add the current arrangement
    return;
  }

  for (int i = start; i <= end; i++) {
    swap(data[start], data[i]); // Swap elements to generate permutations
    permute(data, start + 1, end, permutations); // Recursively permute remaining elements
    swap(data[start], data[i]); // Backtrack: swap back to original order
  }
}

vector<vector<int>> generatePermutations(vector<int>& data) {
  vector<vector<int>> permutations;
  permute(data, 0, data.size() - 1, permutations);
  return permutations;
}

int main() {
  vector<int> numbers = {1, 2, 3}; // Example data
  vector<vector<int>> permutations = generatePermutations(numbers);

  cout << "Permutations of {1, 2, 3}: " << endl;
  for (const vector<int>& permutation : permutations) {
    for (int num : permutation) {
      cout << num << " ";
    }
    cout << endl;
  }

  return 0;
}


Ex6: Write a C++ program, using function, to inputs a student's average and returns 4 if student's average is 90-100, 3 if the average is 80-89, 2 if the

average is 70-79, 1 if the average is 60-69, and 0 if the average is lower than 60.

Sol//

برنامج C++ يستخدم دالة لتحديد درجة الطالب على أساس المتوسط:

#include <iostream>

using namespace std;

int getGrade(float average) {
  if (average >= 90.0f) {
    return 4; // A
  } else if (average >= 80.0f) {
    return 3; // B
  } else if (average >= 70.0f) {
    return 2; // C
  } else if (average >= 60.0f) {
    return 1; // D
  } else {
    return 0; // F
  }
}

int main() {
  float studentAverage;

  cout << "Enter student's average: ";
  cin >> studentAverage;

  int grade = getGrade(studentAverage);

  cout << "Student's grade: " << grade << endl;
  switch (grade) {
    case 4:
      cout << " (Excellent)";
      break;
    case 3:
      cout << " (Good)";
      break;
    case 2:
      cout << " (Average)";
      break;
    case 1:
      cout << " (Pass)";
      break;
    case 0:
      cout << " (Fail)";
      break;
  }

  return 0;
}


Ex7: The Fibonacci Series is: 0, 1, 1, 2, 3, 5, 8, 13, 21, ... It begins with the terms 0 and land has the property that each succeeding term is the

sum of the two preceding terms. Write a C++ program, using function, to calculate the nth Fibonacci number.

Sol//

برنامج C++ يستخدم دالة لحساب رقم فيبوناتشي n:


#include <iostream>

using namespace std;

int fibonacci(int n) {
  if (n <= 1) {
    return n;
  } else {
    return fibonacci(n - 1) + fibonacci(n - 2);
  }
}

int main() {
  int n;

  cout << "Enter the nth term for Fibonacci sequence: ";
  cin >> n;

  int nthFibonacci = fibonacci(n);

  cout << "The " << n << "th Fibonacci number is: " << nthFibonacci << endl;

  return 0;
}


Ex8: Write a C++ program, using function, to calculate the factorial of an integer entered by the user at the main program.

Sol//

برنامج C++ يستخدم دالة لحساب مضروب العدد الصحيح الذي أدخله المستخدم:


#include <iostream>

using namespace std;

// Function to calculate factorial (using non-negative integer validation)
long long factorial(int number) {
  if (number < 0) {
    throw invalid_argument("Factorial is not defined for negative numbers.");
  } else if (number == 0) {
    return 1;
  } else {
    long long result = 1;
    for (int i = 1; i <= number; i++) {
      result *= i;
    }
    return result;
  }
}

int main() {
  int num;

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

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

  return 0;
}


Ex9: Write a C++ program, using function, to evaluate the following equation:

z = x! - y! / (x - y)!

Sol//

برنامج C++ يستخدم وظائف لتقييم المعادلة

#include <iostream>

using namespace std;

// Function to calculate factorial (using non-negative integer validation)
long long factorial(int number) {
  if (number < 0) {
    throw invalid_argument("Factorial is not defined for negative numbers.");
  } else if (number == 0) {
    return 1;
  } else {
    long long result = 1;
    for (int i = 1; i <= number; i++) {
      result *= i;
    }
    return result;
  }
}

// Function to evaluate the equation z = x! - y! / (x - y)!
long long evaluateEquation(int x, int y) {
  if (x < y) {
    throw invalid_argument("x must be greater than or equal to y.");
  }
  long long xFactorial = factorial(x);
  long long yFactorial = factorial(y);
  int denominator = x - y;
  if (denominator == 0) {
    throw invalid_argument("Division by zero is not allowed.");
  }
  long long denominatorFactorial = factorial(denominator);
  return xFactorial - yFactorial / denominatorFactorial;
}

int main() {
  int x, y;

  cout << "Enter x (non-negative integer): ";
  cin >> x;

  cout << "Enter y (non-negative integer, less than or equal to x): ";
  cin >> y;

  try {
    long long result = evaluateEquation(x, y);
    cout << "z = " << x << "! - " << y << "! / (" << x << " - " << y << ")! = " << result << endl;
  } catch (const invalid_argument& e) {
    cerr << "Error: " << e.what() << endl;
  }

  return 0;
}


Ex10: Write a C++ program, using function, to test the year if it's a leap or not.

Note: use  y %4 == 0 && y % 100 != 0 : y % 400 == 0

Sol//
برنامج C++ يستخدم دالة للتحقق مما إذا كانت السنة سنة كبيسة:
#include <iostream>

using namespace std;

bool isLeapYear(int year) {
  // Check for divisibility by 4 (excluding multiples of 100)
  if (year % 4 == 0 && year % 100 != 0) {
    return true;
  }
  // Check for divisibility by 400 (century years)
  else if (year % 400 == 0) {
    return true;
  } else {
    return false;
  }
}

int main() {
  int year;

  cout << "Enter a year: ";
  cin >> year;

  if (isLeapYear(year)) {
    cout << year << " is a leap year." << endl;
  } else {
    cout << year << " is not a leap year." << endl;
  }

  return 0;
}

Ex11:Write a C++ program, using function, to find X^y Note: use pow instruction with math.h library.

Sol//

برنامج C++ يستخدم الدالة pow من مكتبة <math.h> لحساب X ^ y:

#include <iostream>
#include <math.h> // For the pow function

using namespace std;

double calculatePower(double x, double y) {
  """Calculates x raised to the power of y."""
  return pow(x, y);
}

int main() {
  double base, exponent;