This is not my homework. I dont have a teacher since my studies are through distance education. I got some questions from previous years' question papers. |
You do have a teacher that has assigned a task for you, and that teacher is
you. Homework is something that you do by yourself in order to learn.
Is this a correct program to find the sum of squares from 1 to 100?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include<iostream>
using namespace std;
int i, d, sum;
int main()
{
for(int i=1; i <= 100; ++i)
{
d = i * i;
sum += d;
}
cout << "Sum of squares from 1 to 100 is " << sum;
return 0;
}
|
|
First, please post code with code tags and intuitive indentation. They make reading and commenting easier.
chicofeo wrote: |
---|
Does it compile? Are you getting errors? Does it perform like you want to? |
These are essential questions. Syntactic errors prevent compilation.
However, a faulty program can produce seemingly correct results by a fluke. The compiler spits out both errors and warnings. The warnings do not stop compilation, but point to dubious constructs.
One can have logical errors that produce no warnings.
When you have both syntactically and logically correct program, you can still have style issues. There is more than one correct way to achieve the result, and some may have (debatable) advantage.
For example, the sum does not require a loop. See
http://www.trans4mind.com/personal_development/mathematics/series/sumNaturalSquares.htm
On line 3 you have
using namespace std;
which is counter-productive. There is a reason why the standard library has been moved into namespace of its own.
The only place, where you do need the std is on line 13, where you can write
std::cout
. If you had
cout
in multiple places in main(), you could add
using std::cout;
into the main() to save a bit of typing.
The style of declaring multiple variables within one statement, like you do on line 4, may seem compact, but it is more clear to have separate statement for each, particularly if there are pointer types and/or initializers.
You do declare those three variables outside of any function. They are
global variables. Globals are a bit tricky and restrictive and better used only when they are really needed. (The std::cout is a global variable ... )
You do declare variable
i
on line 4.
You do declare variable
i
on line 8.
Can you describe the lifetime and visibility of the two?
You do not need both.
You don't actually need the
d
either, because you can chain operators:
sum += (i * i);
Now a big one: What is the value of
sum
before the loop starts?
Undefined. The sum must have a known value before the loop. It has to be set.
Initialized.
Your program does not initialize the sum. That makes the program
incorrect. It is rather unfortunate that in your environment the result appears to be correct. This time.