Search code examples
c++loopsvisual-c++error-handlingsum

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.


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;
    }