0% found this document useful (0 votes)
31 views5 pages

C++ Programming Exercises Solutions

Uploaded by

tubin14121997
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views5 pages

C++ Programming Exercises Solutions

Uploaded by

tubin14121997
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Câu 1

#include <stdio.h>
using namespace std;
int main() {
int n, tong = 0;
printf("Nhap so nguyen duong n : ");
scanf("%d", &n);
if (n <= 0) {
printf("Vui long nhap mot so nguyen duong.\n");
return 1; // Ket thuc chuong trinh neu ko hop le
}
for (int i = 2; i <= n; i += 2) {
tong += i;
}
printf("Tong cac so chan tu 1 den %d là: %d\n", n, tong);

return 0;
}
Câu 2

#include <stdio.h>
using namespace std;
int main() {
char str[100];
int count = 0;
printf("Nhap mot chuoi bat ky: ");
fgets(str, sizeof(str), stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == ' ') {
count++;
}
}
printf("So lan suat hien dau cach trong chuoi la: %d\n", count);
return 0;
}
Câu 3

#include <iostream>
#include <cmath>
using namespace std;
const float PI = 3.14159;
int main() {
float r, cv, dt;
cout << "Nhap do dai ban kinh r: ";
cin >> r;
cv = 2 * PI * r;
dt = PI * pow(r, 2);
cout << "Chu vi hinh tron: " << cv << endl;
cout << "Dien tich hinh tron: " << dt << endl;
return 0;
}
Bài 4

#include <iostream:>
#include <vector>
using namespace std;
int main() {
int n;
std::cout << "Nhap so luong phan tu mang: ";
std::cin >> n;
std::vector<int> a(n);
std::cout << "Nhap cac phan tu mang: " << std::endl;
for (int i = 0; i < n; ++i) {
std::cout << "Phan tu " << i + 1 << ": ";
std::cin >> a[i];
}
int k;
std::cout << "Nhap so nguyen k: ";
std::cin >> k;
int sum = 0;
int count = 0;
for (int i = 0; i < n; ++i) {
if (a[i] % k == 0) {
sum += a[i];
count++;
}
}
if (count > 0) {
double average = static_cast<double>(sum) / count;
std::cout << "Trung binh phan tu chia het cho k " << k << " là: " << average << std::endl;
} else {
std::cout << "Khong chia het cho k " << k << std::endl;
}

return 0;
}

You might also like