c++
Write a program that calls a function calculateSum to calculate the sum from -1 to N. The function calculateSum has one parameter N of type integer and returns an integer which represents the sum from -1 to N, inclusive.
Write another function calculateAverage that calculates an average. This function will have two parameters: the sum and the number of items. It returns the average (of type float).
The main function should be responsible for all inputs and outputs. Your functions will only calculate and return the values and NOT print anything. N is provided by the user; user input must be asked for repeatedly until a non-negative integer is provided.
#include <iostream> using namespace std; int calculateSum(int N){ int sum = 0; for(int i = -1;i<=N;i++){ sum += i; } return sum; } float calculateAverage(int sum, int n){ return 1.0*sum/n; } int main(){ int N; cout<<"Enter a number: "; cin>>N; while(N<=0){ cout<<"Enter a number: "; cin>>N; } cout<<"Sum: "<<calculateSum(N)<<endl; cout<<"Average: "<<calculateAverage(calculateSum(N),N+2)<<endl; return 0; }
Get Answers For Free
Most questions answered within 1 hours.