Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to know the error in my code. This is to print sum of all even numbers till 1 to N

#include<iostream>
using namespace std;

int main(){
    int i = 1;
    int sum;
    int N;
    cout << "Enter a number N: ";
    cin >> N;
    while(i<=N)
    {
        if(i%2 == 0)
        {
            sum = sum + i;
        }
        else
        {
            i = i + 1;
        }
    }
    cout << sum;
}

This is to print the sum of all even numbers till 1 to N.

As I try to run the code, I am being asked the value of N but nothing is being printed ahead.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For starters the variable sum is not initialized.

Secondly you need to increase the variable i also when it is an even number. So the loop should look at least like

while(i<=N)
{
    if(i%2 == 0)
    {
        sum = sum + i;
    }
    i = i + 1;
}

In general it is always better to declare variables in minimum scopes where they are used.

So instead of the while loop it is better to use a for loop as for example

for ( int i = 1; i++ < N; ++i )
{
    if ( i % 2 == 0 ) sum += i;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading