حل lab2 برمجة1 جامعة الامام
- جامعة الامام محمد بن سعود الاسلامية
- Computer Programming CS107 - برمجة 1
- برمجة سي بلس بلس | C++ programming
- 2025-10-01
توصيف
Lab 2 (1 page, 6 Exercises)
Exercise 1
Write a C++ program that computes the sum of numbers less than or equal to n where n is given by the user.
#include <iostream>
using namespace std;
int main() {
int n, sum = 0;
cout << "Enter a number: ";
cin >> n;
for (int i = 1; i <= n; i++)
sum += i;
cout << "Sum = " << sum << endl;
return 0;
}
Exercise 2
Write a C++ program that computes the sum of even numbers less than or equal to n where n is given by the user.
#include <iostream>
using namespace std;
int main() {
int n, sum = 0;
cout << "Enter a number: ";
cin >> n;
for (int i = 2; i <= n; i += 2)
sum += i;
cout << "Sum of even numbers = " << sum << endl;
return 0;
}
Exercise 3
Write a C++ program that computes the sum of even numbers that are in the range [a, b] where a and b are given by the user.
2.3
#include <iostream>
using namespace std;
int main() {
int a, b, sum = 0;
cout << "Enter two numbers (a and b): ";
cin >> a >> b;
for (int i = a; i <= b; i++) {
if (i % 2 == 0)
sum += i;
}
cout << "Sum of even numbers = " << sum << endl;
return 0;
}
Exercise 4
Write a C++ program that computes the minimum of n numbers given by the user.
#include <iostream>
using namespace std;
int main() {
int n, num, min;
cout << "How many numbers? ";
cin >> n;
cout << "Enter number 1: ";
cin >> min;
for (int i = 2; i <= n; i++) {
cout << "Enter number " << i << ": ";
cin >> num;
if (num < min)
min = num;
}
cout << "Minimum number is: " << min << endl;
return 0;
}
Exercise 5
Write a C++ program that prints a number n given by the user in the reverse order (7163 => 3617).
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;
if (n < 0) {
cout << "Please enter a non-negative integer." << endl;
return 1;
}
cout << "Reversed number: ";
if (n == 0) {
cout << 0;
}
while (n > 0) {
cout << n % 10; // Print the last digit
n = n / 10; // Remove the last digit
}
cout << endl;
return 0;
}
Exercise 6
Write a C++ program that computes the least common multiplier (LCM) of two numbers n and p given by the user.
#include <iostream>
using namespace std;
int main() {
int n, p;
cout << "Enter the first number (n): ";
cin >> n;
cout << "Enter the second number (p): ";
cin >> p;
if (n <= 0 || p <= 0) {
cout << "INAVLID ENTRY, Please enter positive integers only." << endl;
}
else{
//int maxVal = (n > p) ? n : p;
int maxVal;
if(n>p)
maxVal=n;
else maxVal=p;
// Start from max(n, p) and find the first number divisible by both
while (true) {
if (maxVal % n == 0 && maxVal % p == 0) {
cout << "The Least Common Multiple (LCM) of " << n << " and " << p << " is: " << maxVal << endl;
break;
}
maxVal++;
}
}
return 0;
}