Question #44308

Write a C-program that asks the user to type an integer N for finding the sum of the
numbers 2, 4, 6, 8, …, n

Expert's answer

#include <iostream>

int calculateSum(int *arr, int size)

{

int sum = 0;

for(int i = 0; i < size; ++i)

sum += arr[i];

return sum;

}

int main()

{

int size;

std::cout << "Enter size: " << std::endl;

std::cin >> size;

size /= 2;

int *arr = new int[size];

for(int i = 0; i < size; ++i)

{

arr[i] = (i + 1) * 2;

}

std::cout << "Sum: " << calculateSum(arr, size) << std::endl;

std::cin.get();

return 0;

}

int calculateSum(int *arr, int size)

{

int sum = 0;

for(int i = 0; i < size; ++i)

sum += arr[i];

return sum;

}

int main()

{

int size;

std::cout << "Enter size: " << std::endl;

std::cin >> size;

size /= 2;

int *arr = new int[size];

for(int i = 0; i < size; ++i)

{

arr[i] = (i + 1) * 2;

}

std::cout << "Sum: " << calculateSum(arr, size) << std::endl;

std::cin.get();

return 0;

}

## Comments

## Leave a comment