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.

Dani AI

Generated

Good approach — a simple loop is exactly what this assignment expects. A few small, practical fixes will make the program clearer and more robust: the prompt should ask for a positive integer N (not an "even integer"), drop the unnecessary temporary variable (as noted) and use meaningful names like N and sum, prefer standard main/cin/cout for portability instead of Stanford's GetInteger() and stdafx.h, and validate that the input is nonnegative.

Use a 64-bit accumulator if you expect larger N. With 32-bit signed int the sum overflows when N > 46340; with signed 64-bit long long the safe upper bound is about 3037000499. Test edge cases: N = 0 -> 0, N = 1 -> 2, N = 6 -> 42, and a value near the chosen overflow threshold.

A concise, portable implementation pattern:

#include <iostream>

int main() {
    long long N;
    if (!(std::cin >> N) || N < 0) return 1;
    long long sum = 0;
    for (long long k = 1; k <= N; ++k) {
        sum += 2 * k;
    }
    std::cout << sum << '\n';
    return 0;
}

As implied, a for-loop is fine — but follow the assignment rule: compute the sum by iteration rather than just printing N*(N+1). You may compute the formula only as a debug assertion to verify your loop during development.

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.