Return to the BobbyGriggs.com C++ Nook


Chapter 6 - Sum of sequence of numbers!
© 1998 by Bobby Griggs.



// Program name:  Sum

// Purpose:  To find the sum of the numbers from 1 to a number

// entered by the user.  The program uses brute force to achieve

// the sum rather than using the Gauss formula of n(n+1)/2.



// Win32 console application



#pragma hdrstop



#include < iostream.h >

#include < conio.h >

#include "myprocs.h"



int Enter_number();

int Calculate_sum(int n);

void Display_sum(int s);



void main()

{

	int num,sum;

	bool doagain = true;



	while (doagain)

	{

		num = Enter_number();

		sum = Calculate_sum(num);

		Display_sum(sum);

		doagain = Again();

	}

	return;

}



int Enter_number()

{

	int n;



	cout << "This program computes the sum of the numbers between "

		<< endl;

	cout << "1 and an integer entered by the user." << endl << endl;

	cout << "Enter an integer ... ";

	cin >> n;

	cout << endl;

	return n;

}



int Calculate_sum(int n)

{

	int i,s;



	s = 0;

	for (i = 1;i <= n;i++)

		s = s + i;

	return s;

}



void Display_sum(int s)

{

	cout << "The sum of the numbers is " << s << "!" << endl << endl;

	return;

}