the output is attached hereAs a teacher had assigned us to find the sum of N even numbers using while loop,the code executes but does not give a proper sum.Can anyone tell me where am i going wrong??
#include <iostream>
using namespace std;
int
main ()
{
int i, n, z, sum;
i = 1;
cout << "enter the number till which even numbers are to be displayed:";
cin >> n;
cout << "the first " << n << " even numbers are:" << endl;
while (i <= n)
{
z = i * 2;
cout << " " << z << endl;
sum = z;
}
cout << "the sum is :" << sum;
return 0;
}
CodePudding user response:
From your output, it's clear that you haven't initialized sum
before using it. Add this line:
sum = 0;
somewhere before the loop and it'll all work out fine.
CodePudding user response:
using namespace std;
int
main ()
{
int i, n, z, sum=0;
i = 1;
cout << "enter the number till which even numbers are to be displayed:";
cin >> n;
cout << "the first " << n << " even numbers are:" << endl;
while (i <= n)
{
Z=i *2;
cout << " " << z << endl;
sum = z;
}
cout << "the sum is :" << sum;
return 0;
}```
CodePudding user response:
It is because you haven't initialized sum in variable declaration. So by default sum will take garbage value.
So you have to initialize sum variable with 0.
int sum = 0;
int i,n,z;