Tuesday, 14 July 2020

Compute the sum of odd numbers

Q: Compute the sum of odd numbers up to a given odd number n.
Input: n
Function: oddsum(n) = 1 + 3 + ...+ (n-2) + n.
Output: oddsum (n)
Examples: oddsum(3) = 4, oddsum(5)=9; oddsum(7)=16.
You may assume the number n is odd.
Use the iterative algoithm such as;
      sum = 0;
      counter = 1;
      while (counter <= n) {
          sum =sum + counter;
          counter= counter + 2;
      }

Solution:

#include <iostream>
using namespace std;

void oddsum(int n)
{
	int sum = 0; // variable initialized to compute the sum
	int counter = 1; // variable to counter loop
	while (counter <= n)
	{
		sum = sum + counter;
		counter = counter + 2;
	}
	cout << "The sum is " << sum;
}

int main()
{
	int n;
	cout << "Enter a number: ";
	cin >> n;
	oddsum(n);

	return 0;
}

Screenshot




No comments:

Post a Comment