C++ Code Examples: Arithmetic Mean, Sum, Product, Square
Classified in Computers
Written at on English with a size of 1.55 KB.
Arithmetic Mean
The following C++ code calculates the arithmetic mean of numbers from 1 to n:
int main() {
int n;
double suma = 0;
cout << "Vnesi broj: ";
cin >> n;
if (n <= 0) {
cout << "Brojot na elementi mora da bide pogolem od 0!" << endl;
return 1;
}
for (int i = 1; i <= n; i++) {
suma += i;
}
double sredina = suma / n;
cout << "Aritmetichkata sredina na broevite od 1 do " << n << " e: " << sredina << endl;
return 0;
}
Sum
The following C++ code calculates the sum of numbers from 1 to n:
int main() {
int n, sum = 0;
cout << "Vnesi broj n: ";
cin >> n;
for (int i = 1; i <= n; i++) {
sum += i;
}
cout << "Sumata e: " << sum << endl;
return 0;
}
Product
The following C++ code calculates the product of numbers from 1 to n:
int main()
{
int n, sum=1;
cout<<"Vnesi n"<>n;
for (int i=1; i<=n; i++ )
{
sum*=i;
}
cout<
Square
The following C++ code calculates x to the power of n:
int main() {
double x, rezultat = 1;
int n;
cout << "Vnesi x: ";
cin >> x;
cout << "Vnesi n: ";
cin >> n;
for (int i = 1; i <= n; i++) {
rezultat *= x;
}
cout << "Stepenot x^n e: " << rezultat << endl;
return 0;
}