Home > OS >  How to display and add all even numbers?
How to display and add all even numbers?

Time:11-11

How can I display and add all even numbers? The current code displays numbers between 2 numbers in an ascending manner.

#include <stdio.h>

main() {
  int a;
  int b;

  printf("Enter integer a:");
  scanf("%d", &a);

  printf("Enter integer b:");
  scanf("%d", &b);

 if(b > a)
  {
      do {
        printf("Result: %d\n", b);
        b--;
      } while (a <= b);
  }
  else
  {
      do {
        printf("Result: %d\n", a);
        a--;
      } while (a >= b);
  }
  
  }

CodePudding user response:

To check if an integer is even you can check if the least significant bit is zero.

To check if an integer is odd you can check if the least significant bit is one.

You can do that using bitwise AND (&).

Something like:

if(b > a)
{
    if (b & 1) b--;  // Make b even
    if (a & 1) a  ;  // Make a even
    int sum = 0;
    do 
    {
        sum  = b;
        printf("b is %d, sum is %d\n", b, sum);
        b = b - 2;
      } while (b >= a);
  }

CodePudding user response:

All even numbers are divisible by 2. You need to check if the remainder of division by 2 is equal to zero. In order to do it, you can use the modulo operator (%). To display only even numbers:

if ((b%2) == 0) {
  printf("Result: %d\n", b);
}

CodePudding user response:

you can use modulo operation(%) it gives the remainder of a number. thus you modulo each number with 2 if the remainder is 0 then the number is even and if it is 1 the number is odd.

CodePudding user response:

I'd write a function which I could test for different possible combinations of the extremes:

#include <stdio.h>

void evens(int a, int b)
{
    // Make sure to always start from the greatest value.
    if ( a > b ) {
        int tmp = a;
        a = b;
        b = tmp;
    }

    // Make sure to always start from an EVEN value.
    if ( b % 2 != 0 ) { 
        --b; 
    }

    int sum = 0;
    while ( a <= b ) {
        printf("%d ", b);
        sum  = b;
        b -= 2;    // Jump directly to the previous even number.
    }
    printf("\nSum: %d\n", sum);
}

int main(void)
{
    // Those should all print "10 8 6 4 2 \nSum: 30\n"  
    evens(1, 10);
    evens(10, 1);
    evens(2, 11);
    evens(11, 1);
    evens(2, 10);
}
  •  Tags:  
  • c
  • Related