Not sure if I got this right

Hi,
Here is my assignment question:

C++ Program
Write a program that adds the positive odd numbers you enter from the keyboard
while ignoring the even numbers, and stops when a negative number or zero are
entered.
Display the sum of the accepted odd numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int main()
{
	int find, odd, total;

	cout << “Enter a number” << endl;
	cin >> odd;
	if (odd <= 0)
	find = odd % 2;
	if (find = 1)
		total = total + odd;
	
	cout << “This is the total” << total << endl;
	return 0;
}


I am gettin a lot of squiggly lines and error messages.
The squiggly lines will tell you things if you hover over them, and the error messages tell what you errors are present.

If you're not sure how to interpret the error messages, paste them here and we can help explain them to you. Figuring out error messages is an important part of troubleshooting.

___________________

But, for the sake of me not wanting to wait, here's the error messages:

main.cpp:8:10: error: unexpected character <U+201C>
        cout << “Enter a number” << endl;
                ^

...
main.cpp:8:30: error: expected ';' at end of declaration
        cout << “Enter a number” << endl;
                                ^
                                

main.cpp:12:11: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
        if (find = 1)
            ~~~~~^~~


First,
You must've copy-pasted code or used a "fancy" text editor instead of a text editor meant for programming. Your double quotes are using the fancy curved unicode quotes instead of the normal ASCII quotes.

" is different from “
" is different from ”

Re-type your code manually within an IDE or text editor like Notepad++.


Second,
if (find = 1)

= is assignment
== tests for equality.
You meant to use ==.
Last edited on
ok
Here are the error codes. I tried to figure out what they mean.
Severity Code Description Project File Line Suppression State
Error C2059 syntax error: '=' Homework assignment 6 question 4 C:\C++ Code\Homework assignment 6 question 4\Homework assignment 6 question 4.cpp 18
Error (active) E0029 expected an expression Homework assignment 6 question 4 C:\C++ Code\Homework assignment 6 question 4\Homework assignment 6 question 4.cpp 18


By the way I changed if (find == 1) and I still have these two errors.
THanks
why is odd expected to be negative, did you mean that?

bools are 1 or 0 numerically, where 0 is false. You can, then, use bool expressions as index in a lookup table or as a number.

you should initialize values. total could be 52137 when the program starts without setting it to 0 initially!

going back to your requirements, then, you need a loop, until it is negative.
all that looks something like

1
2
3
4
5
6
7
8
9
int odd{1};
int total{0};
do
{
  cin >> odd;
  if(odd > 0)
  total += odd%2; //you can roll odd>0 here with && but its confusing looking and does not help anything beyond space saving. 
//NOTE that adding 0 is fine, skipping the addition of 0 doesn't actually save any time.  You do NOT need more if statements. 
} while (odd >=0);

Last edited on
Post your exact new code with current, exact error messages.
And what version of Visual Studio is that?
Last edited on
as for your errors, its telling you that your current line 18 has a problem. you don't have 18 lines above, so we can't say what exactly you did there, but this is a basic syntax error, so just check that line against c++ semantics or if you can't figure it out, repost the current code.
Odd numbers are to be added together.
Here is the assignment I am working on:

C++ Program
Write a program that adds the positive odd numbers you enter from the keyboard
while ignoring the even numbers, and stops when a negative number or zero are
entered.
Display the sum of the accepted odd numbers.
I have copied my code from visual studio community 2022:

// Homework assignment 6 question 4.cpp : This file contains the 'main' function.
// Program execution begins and ends there.
//
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

int main()
{
	int find, odd, total; // setting up variables

	cout << "Enter a number" << endl;
	cin >> odd;
	if (odd <= 0)
		cout << "This number is skipped" << endl;

	find = odd % 2;

	if (find = = 1)
		total = total + odd; //adding odd numbers together
	
	cout << "This is the total" << total << endl;
	return 0;
}



code copied from vs community
Last edited on
I think it's giving the end of the program as the line because it's given up trying to figure out the wrong syntax. It's not clear that the issue of using the wrong quotes has been fixed.
Write a program that adds the positive odd numbers you enter from the keyboard
while ignoring the even numbers, and stops when a negative number or zero are
entered.
Display the sum of the accepted odd numbers.


1
2
3
4
5
6
7
8
9
#include <iostream>

int main() {
	int total {};

	for (int odd {}; (cin >> odd) && (odd > 0); total += odd * (odd % 2));

	std::cout << total << '\n';
}

I need to add odd numbers to the total. Skipping negative numbers and even numbers.
Last edited on
OK the following code works but I cannot enter a number into the console.


// Homework assignment 6 question 4.cpp : This file contains the 'main' function.
// Program execution begins and ends there.
//
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

#include <iostream>
using namespace std;

int main()
{
	int find = 0, odd, total = 0;

	cout << "Enter a number" << endl;
	cin >> odd;
	if (odd <= 0)
		cout << "This number is skipped" << endl;
	find = odd % 2;

	if (find =  1)
		total = total + odd;
	
	cout << "This is the total" << total << endl;
	return 0;
}


Does anyone have any ideas on how I can fix the problem with not being able to enter a number?

Mark
Look REAL close at line 15. Are you sure you want to assign 1 to find instead of checking for equality?

The "logic" of assigning a value in a control statement like if means your if statement will always evaluate as true. IIRC it is because the assignment is a not-zero value. By Boolean logic zero equates to false, any non-zero value equates to true.
Does anyone have any ideas on how I can fix the problem with not being able to enter a number?

You can enter a number. A single number, no more than one. Because you are not using some form of a loop to control input. A while or do/while loop would work wonders.
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
#include <iostream>

int main( )
{
   int total = 0;

   std::cout << "Keep entering numbers one at a time, 0 or less to stop.\n\n";

   while ( true ) // this will always loop
   {
      // enter a number
      std::cout << ": ";
      int num2enter;
      std::cin >> num2enter;

      // if this is zero or less let's end the loop
      if ( num2enter <= 0 ) { break; }

      // if this is a positive even number continue
      if ( num2enter % 2 == 0 )
      {
         std::cout << "Not an odd number!\n";
         continue;
      }

      // the entered number is odd, so add it to the total
      total += num2enter;
   }

   std::cout << "The total is: " << total << '\n';
}
Keep entering numbers one at a time, 0 or less to stop.

: 1
: 2
Not an odd number!
: 3
: 4
Not an odd number!
: 5
: 0
The total is: 9

George P,
Good explanation :)
Hopefully that's made things clearer.
Last edited on
@Ganado, if'n you are referring to my last comment, thank you.

I try to make something simple enough for me to understand. :Þ

I know I've been where mathman54 and others have been, just starting out learning C++ and at times even the simplest "this isn't working as expected" or possible errors can get frustrating.

I am still very much learning C++/WinAPI by doing it myself. Badly.
I need to add odd numbers to the total. Skipping negative numbers and even numbers.


Yeah - see my code above. All you need is a one-liner for statement. If you want (and it's usually useful) you can display a prompt at the start and enlarge the final cout statement to also indicate what is being displayed.

odd % 2 can only have 2 values (if odd > 0) - 0 if even or 1 if odd.

What do you get if multiply a number by 0? and by 1? What do you get if you add 0 to a number?
Last edited on
@mathman54,

Relying on whitespace indentation to indicate blocks of code is one day gonna bite you in the tuchas. The C++ compiler/preprocessor ignores that type of whitespace. Here's an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main()
{
   std::cout << "Enter a number less than 10 or greater than 100: ";
   int x { };
   std::cin >> x;
   std::cout << '\n';

   if (x >= 10)
      if (x > 100)
         std::cout << "More than 100, Thanks!\n";
   else // not the else intended!
      std::cout << "Less than 10, Thanks!\n";
}

Here's what the code looks like when properly formatted, this is how the preprocessor/compiler interprets the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main( )
{
   std::cout << "Enter a number less than 10 or greater than 100: ";
   int x { };
   std::cin >> x;
   std::cout << '\n';

   if ( x >= 10 )
      if ( x > 100 )
         std::cout << "More than 100, Thanks!\n";
      else // not the else intended!
         std::cout << "Less than 10, Thanks!\n";
}

Your code could be "badly formatted" with/without whitespace and to the compiler the code is still the same:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main()
{
std::cout << "Enter a number less than 10 or greater than 100: ";
int x { };
std::cin >> x;
std::cout << '\n';

if (x >= 10)
if (x > 100)
std::cout << "More than 100, Thanks!\n";
else // not the else intended!
std::cout << "Less than 10, Thanks!\n";
}

Explicitly using matching braces to indicate code blocks can serve a dual purpose.

1. they define properly where block(s) of code start and end.
2. If you want to add more lines of code in a block already having braces ensures your block is properly handled when compiled. Adding code to a block without braces puts the line(s) outside the block.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int main()
{
   std::cout << "Enter a number less than 10 or greater than 100: ";
   int x { };
   std::cin >> x;
   std::cout << '\n';

   if (x >= 10)
   {
      if (x > 100)
      {
         std::cout << "More than 100, Thanks!\n";
      }
   }
   else // fixed!
   {
      std::cout << "Less than 10, Thanks!\n";
   }
}

The Moral of the Story is relying on whitespace alone to define blocks of code is fraught with peril. "There Be Dragons There" that can make debugging your code more trouble than it needs to be.

Compiler suites can format code for you, Visual Studio is one. You can set up the formatting options so you can format existing code and format code automatically when pasting chunks of code into your project's files.

I use the formatting option on my code a lot in Visual Studio. Code I write and "found" code from the internet or in books.

As you saw even with simple program requirements such as you have there are multiple ways to write effective code. As you gain more knowledge and experience in writing C/C++ code taking simple and effective shortcuts such as seeplus shows can be a time/keystroke saver, especially when there's a deadline involved.

The tradeoff is one of potential readability. Code written can look like Sanskrit when looking at it after putting it aside and ignoring it for days/weeks/months.

The two bits of code, seeplus' and mine, essentially do the same thing, per your program requirements.

I'm not a professional programmer, merely a self-taught hobbyist, so my code tends to be more verbose than code written by someone who makes a living at crufting code. I personally prefer more verbose code most of the time.
Last edited on
Oh, something to remember. You know what the code is supposed to do, what input[s] if any are required. The hypothetical user doesn't have a clue. That includes us.

Staring at a blank console window with a blinking cursor without any explanation of what to expect can be annoying and frustrating. Including copious output statements can be helpful to the "idiot" user, and a good way to spot possible problems with program flow during development.
Topic archived. No new replies allowed.