Write a program that reads in a positive integer N and calculates and displays the sum of the first N even integers. For example if N is 6, the program should display the value 42, which is: 2+4+6+8+10+12=42.
Caution: You need to write a program to do the addition. If you happen to know that the answer is always N*(N+1) and then just output the result, you will get 0 credit.

thank you.

Recommended Answers

All 3 Replies

Seems like a simple for loop should do the trick, no? Show us what you've tried and we can help if you get stuck.

David

It seems like I have correctly finished the problem, see below:

#include "stdafx.h"
#include "simpio.h"
#include "genlib.h"


int _tmain(int argc, _TCHAR* argv[])
{
	int num,nom,i,nam;
	printf("Enter a even integer: ");
	num=GetInteger();
	nom=0;
	for(i=2;i<=num*2;i+=2)
	{
		nam=i;
		nom=nom+nam;
	}
	printf("The sum of the first %d even integers is %d.\n",num,nom);
	return 0;
}

---------------------------------------------------------------------------
I would greatly appreciate it if anybody can catch some small errors in this problem.

The variable nam seems to be unneeded. You can replace the lines

nam=i;
nom=nom+nam;

in the for loop with simply

nom+=i;

Besides that, it seems fine (though I'm not sure why you're using printf instead of cout in a c++ program)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.