C++ Loops For Even and Odd Numbers

Write a program that asks the user for non-negative integers X and Y. Using a loop, alternate between adding and multiplying integers starting at X and finishing at Y. If the number is even, add it to the total. If the number is odd, multiply it. For example, if X=5 and Y=10, your program should calculate ((5+6)*7+8)*9+10=775. If X=2 and Y = 5, calculate (2*3+4)*5=50.

I know how to split the even and odd number, but I have no idea how to put it together.

3 answers

  • answered 2017-06-17 18:43 KyrSt

    Assuming you are looping though X to Yand i is the iterator / current number in your loop and tot is the total number that you will output, inside your loop,
    when i is even:

    tot += i;
    

    and when i is odd:

    tot *= i;
    

    You also have to choose the appropriate starting value for tot.

    I would post the full code but it seems this is an assignment.

  • answered 2017-06-17 18:43 Vivick

    Proper explanations :
    First step is checking that input is correct (y is greater than x and both values are positive).

    Then you initialize the variable that you'll use for returning the result to x (because we always start from x according to the examples you gave us) : int res = x;.

    The you have the looping : Since we start from x, just loop from x+1 to y (included, again accordingly with the examples you gave us) : for(int i = x+1 ; i <= y; i+=1)

    In this loop you have the current value, if this current value is even, add it to the result variable (res += i;), else (it is odd) you multiply the result by the current value (res *= i).

    After the loop you can return the result variable and the job is done.



    /!\SPOILER : complete code below



    Here is the complete code

       int func(int x, int y){
          if(y>x && x>0){
            int res = x;
            for(int i = x+1 ; i <= y ; i+=1){
              if(i%2==0)
                res += i;
              else
                res *= i;
            }
            return res;
          }
          return -1;
        }
    

    I just added the fact that it returns -1 if the input isn't "valid".

  • answered 2017-06-17 18:43 Jiten Sadhwani

    First, check whether y is greater than X or not. If greater, run a loop starting at X and ending at Y. Take a variable which stores the total. If the loop variable is even add the value to the total variable and if the loop variable is odd multiply the value with the value of total variable.

    int total=0;
    if(y>x)
    {
       for(int i=x;i<=y;i++)
       {
           if(i%2==0)       //if even
           {
               total += i;
           }
           else         //if odd
           {
               total *= i;  
           }
      }
    }
    cout<<total;