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

Time:12-29

#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.

CodePudding user response:

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

CodePudding user response:

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

Let's step through this. Imagine we're on the loop where i = 2 and you've entered N = 5. In that case...

while(i <= N)

2 <= 5 is true, so we loop

if(i%2 == 0)

2 % 2 == 0 is true, so we enter this branch

sum = sum   i;

Update sum, then head back to the top of the loop

while(i <= N)

Neither i nor N have changed, so 2 <= 5 is still true. We still loop

if(i%2 == 0)

2 % 2 == 0 is still true, so we enter this branch again...


Do you see what's happening here? Since neither i nor N are updated, you'll continue entering the same branch and looping indefinitely. Can you think of a way to prevent this? What would need to change?

Also note that int sum; means that sum will have a garbage value (it's uninitialized). If you want it to start at 0, you'll need to change that to

int sum = 0;

CodePudding user response:

You're looping infinitly when i is even because you don't increase it. Better option would be this if you want to use that while loop :

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

If you don't need to do anything when the condition is false, just don't use an else.

CodePudding user response:

No loops are necessary and sum can be evaluated at compile time if needed too

// use unsigned, the whole excercise is pointless for negative numbers
// use const parameter, is not intended to be changed
// constexpr is not needed, but allows for compile time evaluation (constexpr all the things)
// return type can be automatically deduced
constexpr auto sum_of_even_numbers_smaller_then(const unsigned int n)
{
    unsigned int m = (n / 2);
    return m * (m   1);
}

int main()
{
    // compile time checking of the function
    static_assert(sum_of_even_numbers_smaller_then(0) == 0);
    static_assert(sum_of_even_numbers_smaller_then(1) == 0);
    static_assert(sum_of_even_numbers_smaller_then(2) == 2);
    static_assert(sum_of_even_numbers_smaller_then(3) == 2);
    static_assert(sum_of_even_numbers_smaller_then(7) == 12);
    static_assert(sum_of_even_numbers_smaller_then(8) == 20);

    return 0;
}

CodePudding user response:

int main(){

int input;                  //stores the user entered number
int sum=0;                  //stroes the sum of all even numbers
repeat:
cout<<"Please enter any integer bigger than one: ";
cin>>input;
if(input<1)                 //this check the number to be bigger than one means must be positive integer.
    goto repeat;            // if the user enter the number less than one it is repeating the entry.
for(int i=input; i>0; i--){ // find all even number from your number till one and than totals it.
    if(i%2==0){
        sum=sum i;
        int j=0;
        j=j 1;
        cout<<"Number is: "<<i<<endl;
    }
}
cout<<endl<<"The sum of all even numbers is: "<<sum<<endl;}

Copy this C code and run it, it will solve your problem.

CodePudding user response:

There are 2 problems with your program.

Mistake 1

The variable sum has not been initialized. This means that it has(holds) a garbage value. And using this garbage value like you did when you wrote sum = sum i; is undefined behavior.

Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has undefined behavior.

This is why it is advised that:

always initialize built in types in local/block scope.

Mistake 2

The second problem is that you're not updating the value of variable i.

Solution

You can solve these problems as shown below:

int main(){
    int i = 1;
    int sum = 0; //INITIALIZE variable sum to 0
    int N;
    cout << "Enter a number N: ";
    cin >> N;
    while(i<=N)
    {
        if(i%2 == 0)
        {
            sum = sum   i;
        }
        
        i = i   1; //update(increase i)
       
    }
    cout << sum;
}

1For more reading(technical definition of) on undefined behavior you can refer to undefined behavior's documentation which mentions that: there are no restrictions on the behavior of the program.

  • Related