Assistance with WHILE

Write a program to sum up either all the even numbers or all the odd numbers from 0 to N where you will prompt the user for the word 'even' or 'odd' and the value of N. Test your program with 'even values to 180' then with 'odd values to 160', by reading in the data. You will enter the word 'even' or 'odd' and a value for N. Print result to file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
    ofstream range;
    range.open("EvenOrOdd.out");

   int i=160,//even
       n=190,//odd
       sum=0;
    string c;

    cout << "Enter even or odd: ";
     cin >> c;
    cout << "Enter the number: ";
     cin >> n;


    if(c=="even")
    {
        i=0;
        while(i<=n)
    {
      sum+=i;
        i+=2;
    }
    }

       if(c=="odd")
        {
            i=1;
            while(i<n)
            {
                sum+=i;
                i+=2;
            }
        }
    range << "The total is:" << sum;
    range.close();
    return 0;
}


I have gotten this far with the program and it works fine, but I need help knowing if this is how the problem is being asked? I know I can't use cin and cout but I'm unsure how to go around it. Also, I can use %2, but unsure how to use it.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int main()
{
    ofstream range;
             range.open("EvenOrOdd.out");

    int number1 = 180, number2 = 160, sum1 = 0, sum2 = 0, even, odd;

        range << " EVEN VALUE\t\t\t ODD VALUE\n";


    if(even = 0)
    {
        number1 = 0;
        while(number1 >= number2)
        {
            sum1 += number1;
            number1 += 2;
        }
    }

    if(odd = 1)
    {
        number2 = 1;
        while(number1 > number2)
        {
            sum2 += number2;
            number2 += 2;
        }
    }

    range << "\n The total is: " << sum1
          << "\n SUM2 " <<sum2;

    range.close();
    return 0;
}


This is a second attempt at altering the code. I'm not 100% what is going wrong with this one.
Think first, code second.
What you have looks like it might work, but I did not go looking for problems, because you did not ask about any problems or explain what is going wrong etc.
why not try it with some small #s? 1-5 odd is 1+3+5 = 9, 1-10 even is 2+4+6+8+10 is 30 ...
do those work??

%2 is remainder when divided by 2, which happens to be even/odd indicator: 3%2 = 1, 10%2 = 0, 51%2 = 1, 100000000092%2 = 0 ... (I see no use for this today, but you asked).

ok, so lets think. both even and odd are +2.
all that changes is where you start.
to sum evens, start at 0 and add 2 every time:
0,2,4,6,8,10,... //adding 0 does nothing
and to sum odds, start at 1: 1,3,5,7....
so a single loop will do it.

all you need, then, is one loop and a starting condition:
i = 0;
if(c == "odd")
i = 1;
while(i < n) //assignment unclear, this could be <= ??!!
{
sum+= i;
i += 2;
}

the above still works if you want a sum over a range that starts anywhere.. that would need the %. you need to figure out if start is even or odd, and then adjust accordingly. want to give it a try?

you can open a file in the constructor
ofstream ofs(filename); //don't need .open() ... its not wrong, just wordy.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
using namespace std;

int sumOdd( int N )
{
   if ( !(N % 2) ) return sumOdd( N - 1 );
   return ( N + 1 ) * ( N + 1 ) / 4;
}

int sumEven( int N )
{
   if ( N % 2 ) return sumEven( N - 1 );
   return N * ( N + 2 ) / 4;
}

int main()
{
   string parity;
   int N;
   cout << "Input parity (even or odd) and N: ";   cin >> parity >> N;
   cout << ( parity == "even" ? sumEven( N ) : sumOdd( N ) ) << '\n';
}
> you will prompt the user for the word 'even' or 'odd' and the value of N.
> (...) I know I can't use cin and cout but I'm unsure how to go around it.
¿how did you reach that conclusion?
You're overthinking the problem. Your first version works fine. Still, it could use improvement.

Indent your code consistently. I cannot stress the importance of this. No bug is harder to find and easier to avoid than putting { and } in the wrong place.

Ideally, you'd use the math formula for an arithmetic series like lastchance. Why make the computer do this with a loop when we've known for hundreds of years that problems like this can be solved with a simple calculation?

If you really want to use a loop then
- recognize that the only difference between the "even" and "odd" cases is the starting value for the loop.
- prefer a for loop to a while loop. For loops usually produce clearer code.

Here is your code, still using a loop but with the other changes:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int
main()
{
    ofstream range;
    range.open("EvenOrOdd.out");

    int i = 160,		//even
	n = 190,		//odd
	sum = 0;
    int startVal = 0;
    string c;

    cout << "Enter even or odd: ";
    cin >> c;
    cout << "Enter the number: ";
    cin >> n;

    if (c == "even") {
	startVal = 0;
    } else if (c == "odd") {
	startVal = 1;
    }

    for (i = startVal; i <= n; i += 2) {
	sum += i;
    }
    range << "The total is:" << sum;
    range.close();
}

@ne555, The professor has these preprinted sheets that have the assignments on them. I have no idea where he gets them or if he created them. But we, as a class, can not use cin or cout on our codes. everything has to write to a file. I know the assignment says one thing, but the professor says another.

@dhayden, thank you for your input, as of right now we can't use FOR loops yet. We were just caught about WHILE.

My hardest learning curve on these programs is thinking of how to write these codes. Once completed they aren't that difficult but the beginning is my hardest issue.

@Jonin, the second code wasn't properly running, I wasn't able to get any value other than 0 for sum 1. Then sum 2 would always be a lot larger of a number that isn't the value I needed. Also, on the first code, How would I alleviate the cin and cout, so I don't have any inputs, that the program just begins with the two values I am searching for?
Last edited on
can not use cin or cout on our codes.

Fine, then rewrite the code others give you using std::cin and std::cout to use file stream input/output. I already showed you how easy it is to do:

http://www.cplusplus.com/forum/beginner/262917/#msg1135364

Instead of
10
11
ofstream range;
range.open("EvenOrOdd.out");

Prefer doing it as a single statement: std::fstream ofs("output.txt", std::ofstream::out);
Opening a file for input could be: std::fstream ifs("input.txt", std::ofstream::in);

Avoid using namespace std; if you can.

https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice

https://www.geeksforgeeks.org/using-namespace-std-considered-bad-practice/
what you have is fine if you want a for loop (which is correct for the problem)
as a while loop, you can't use i anymore (the for loop overrides the i you already have)
I was not sure about what the variables were supposed to be initially, so I used i above

1
2
3
4
5
6
7
8
 if (c == "odd")  //its already zero.      
	  startVal = 1;  
		
    while(startVal <= n)
    {		
	  sum += startVal;
	  startVal +=2;
    }


not sure what you want. you want to hard code 160 and 180?
... the duh (this the direct approach) version of that, assuming you don't have a function:
1
2
3
4
5
6
7
8
9
10
11
12
  int startVal = 1;
  for(int duh = 160; duh <= 180; duh+= 20) 
  {     
    sum = 0;
    while(startVal <= duh)
	{		
	  sum += startVal;
	  startVal +=2;
    }
    cout << "The total for " <<duh << " is: " << sum << endl; //change to file after debugging
	startVal = 0; 	
  }


Last edited on
Topic archived. No new replies allowed.