Beginning C++ question

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

CortoPasta
Posts: 38
Joined: Fri Aug 15, 2008 5:51 pm UTC

Beginning C++ question

Postby CortoPasta » Wed Aug 27, 2008 7:11 pm UTC

I just started a C++ class at the local junior college and am having a bit of difficulty with one of the labs. Here is the description of the program to write

Write a program that will ask the user to input an integer value. Your program should then determine if the integer values is an odd or and even number.

Your program output should be something like this:

Please Enter a number
8
That is an even number

Note, The above is an example. You need to get the number from the user!


And here is my attempt at the code

Code: Select all

#include <iostream>
use namespace std;
int main()
{
   cout << "Please enter a number"
   cin >> usernumber
   divided = usernumber / 2          //want a bool function
   if (divided = 0)                    //to convert to 1 or 0
      cout << "That is an odd number"  // (ie. true or false)
???   else (divided = 1)
???      cout << "That is an even number"

   return 0;
}


The teacher cut the class short because of a problem with the air conditioning, so I didn't get a chance to ask about the If/Else statements or Boolean functions we learned about. Can anyone tell me if I'm at least going in the right direction with the idea of bool statements?

User avatar
froggie
Posts: 23
Joined: Wed Jul 18, 2007 6:50 pm UTC

Re: Beginning C++ question

Postby froggie » Wed Aug 27, 2008 7:31 pm UTC

First, equality comparison is "==" (two equal signs) in C++.
Second, you want the remainder of the division (use the modulo operator %, or a bitmask)

User avatar
froggie
Posts: 23
Joined: Wed Jul 18, 2007 6:50 pm UTC

Re: Beginning C++ question

Postby froggie » Wed Aug 27, 2008 7:32 pm UTC

Third, statements should end with a semicolon :)

Fourth, don't double post

User avatar
Mat
Posts: 414
Joined: Fri Apr 21, 2006 8:19 pm UTC

Re: Beginning C++ question

Postby Mat » Wed Aug 27, 2008 7:36 pm UTC

Also, else shouldn't have a condition after it. (If you needed to, you would use "else if" instead - but there's only two options here so just else is fine)

User avatar
sparkyb
Posts: 1091
Joined: Thu Sep 06, 2007 7:30 pm UTC
Location: Camberville proper!
Contact:

Re: Beginning C++ question

Postby sparkyb » Wed Aug 27, 2008 8:48 pm UTC

also, you have to declare your variables.

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Beginning C++ question

Postby Berengal » Wed Aug 27, 2008 9:13 pm UTC

I've written up a corrected and commented version of your program inside the spoiler, but please read what's below first.
Spoiler:

Code: Select all

#include <iostream>
use namespace std; // <- Not really a good habit, but okay for short programs as long as you keep in mind that this is bad when you start writing longer programs.
int main()
{
   cout << "Please enter a number";
   // cin >> usernumber <- C++ isn't smart enough what you mean when you randomly throw words at it. Needs declaration first.
   int usernumber;  // Tells the compiler that "usernumber" is an int. Now we can use it
   cin >> usernumber;  // Don't forget those semicolons...
   // divided = usernumber / 2  <-  Again, C++ doesn't know what "divided" means when put randomly like this. Needs type.
   int divided = usernumber / 2;  // Declaration and assignment, all in one swift definition. Unfortunately, 4 / 2 = 2. 2 is even, but 2 is not 0, which means our logic is wrong up ahead...
   int remainder = usernumber % 2;  // Let's use the modulo operator instead. It's sort of taking the remainder of integer division, but with a small difference. We don't have to bother about that now though
   if (divided = 0)  // = is the assignement operator. What you've written here is really shorthand for "divided = 0; if (divided != 0)..." where != means "is not equal"
   if (remainder == 0)  // == is the boolean operator, which returns true if both the left and right argument are equal, and false if not
   {  // Brackets aren't neccessary here, because there's only one line after the if, but it's still a good habit to put them in in case you want to put more lines in the if afterwards
      cout << "That is an odd number";  // (ie. true or false)  ((Added semicolon))
// ???   else (divided = 1)     Not sure what the ??? is for, but nevermind
   } else // As mentioned before, "else" is what's being done if the preceding if wasn't executed. You don't need another if
   { // Also note that the line with the else starts on the same indentation that the line with the if. Layout doesn't matter in C++, but conventions like this make code easier to read for humans
      cout << "That is an even number";  // Semicolon
   }  // Close the else expression
   return 0;
}


Syntactic errors are to be expected when learning a new language. Things like semicolons and assignment vs equality operators, brackets etc. will come in relatively short time. The thing to look at here is the logic of the program. Let's write your algorithm up:

  1. Request a number from the user
  2. Read the number the user wrote and store it
  3. Divide that number by 2
  4. Compare the divided number to 0, and if they are equal, proceed to 5, else proceed to 6
  5. Tell the user the number is even, then go to 7
  6. Tell the user the number is odd
  7. Program finished

Now let's try a sample run:

  1. "Please enter a number" is written to the monitor
  2. The number 8 is entered and stored
  3. 8 is divided by 2, giving 4
  4. 4 is compared to 0. They are not equal, so we proceed to 6
  5. This was skipped
  6. "The number is odd" is written to the monitor
  7. Program finished

Clearly there is an error. 8 is even, yet the program claims it is odd. Let's look at what constitutes an even number:
An even number is a number that when divided by 2 leaves no remainder.

And odd numbers may be defined as:
Any number which is not even.

Example: 7:
7 / 2 = 3
Calculating the remainder:
3 * 2 = 6
7 - 6 = 1
The remainder is 1. 1 is not 0, so 7 is not even. 7 is therefore odd.

This might all seem somewhat condescending since you were probably doing this in elementary school already, but there's a reason for all this. Making a program that solves a problem means being able to describe exactly how to solve that problem in minute detail. If you yourself haven't broken things down to yourself ahead of time, you're going to have trouble describing to the computer the exact steps, and you will probably make mistakes. In your program above, you gave the computer a definition of even numbers that was incorrect, probably because you didn't define even numbers to yourself beforehand.

Anyway, back to our program. You need to find the remainder somehow. Fortunately, C++ provides the modulo operator, which is the same as the remainder in almost all situations (googling will probably tell you where they differ). The modulo operator is the percent sign (%). Now we can go back and fix the algorithm, and then rewrite the program.

  1. Request a number from the user
  2. Read the number the user wrote and store it
  3. Take the remainder of the number divided by 2
  4. Compare the remainder to 0, and if they are equal, proceed to 5, else proceed to 6
  5. Tell the user the number is even, then go to 7
  6. Tell the user the number is odd
  7. Program finished

Have fun learning how to program.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
Pesto
Posts: 737
Joined: Wed Sep 05, 2007 5:33 pm UTC
Location: Berkeley, CA

Re: Beginning C++ question

Postby Pesto » Thu Aug 28, 2008 6:16 pm UTC

^ Read and absorb this post ^

Thread over.

CortoPasta
Posts: 38
Joined: Fri Aug 15, 2008 5:51 pm UTC

Re: Beginning C++ question

Postby CortoPasta » Fri Aug 29, 2008 12:30 am UTC

Wow. Way more in depth of a response than I expected. I just learned more from that post than my first two weeks in class :D

Seriously though, thanks everyone. Was able to get everything up and working with all your help

User avatar
SlyReaper
inflatable
Posts: 8015
Joined: Mon Dec 31, 2007 11:09 pm UTC
Location: Bristol, Old Blighty

Re: Beginning C++ question

Postby SlyReaper » Mon Sep 01, 2008 9:55 am UTC

This is as far as you've got in 2 weeks? No offence mate, but I think you need to find a better class. I can't believe they haven't covered the relational operators by now.*

I've also spent about 2 weeks learning C++ (had to put it on hold for job hunting purposes). My latest self-assigned project was to count all the prime numbers between 1 and a number the user inputs, and then allow you to explore the list of primes. Typical output:

Find primes between 1 and your number: 10000000

There are 664579 primes between 1 and 10000000


Now to find the nth prime. Enter n (0 to exit): 600000

The 600000th prime is: 8960453


Now to find the nth prime. Enter n (0 to exit): 25

The 25th prime is: 97


Now to find the nth prime. Enter n (0 to exit): 0

Program ends.


Try writing a program that does that. It's not actually that tricky, the problem comes in trying to optimise it for speed. Hint: you need an array or vector.

*note, I'm not insulting you, but whoever designed the curriculum for the course you're taking.
Image
What would Baron Harkonnen do?

bstamour
Posts: 4
Joined: Mon Sep 01, 2008 11:47 am UTC

Re: Beginning C++ question

Postby bstamour » Mon Sep 01, 2008 11:52 am UTC

Had to register an account finally... First of all, good luck, and I hope you enjoy your programming adventure... And now to the post above me... Where he is at after two weeks in a beginners programming course is perfectly fine. He probably doesn't have classes every day, so say maybe he has had two to three classes already, one of which may have been a write-off as some first day classes are.

User avatar
SlyReaper
inflatable
Posts: 8015
Joined: Mon Dec 31, 2007 11:09 pm UTC
Location: Bristol, Old Blighty

Re: Beginning C++ question

Postby SlyReaper » Mon Sep 01, 2008 12:16 pm UTC

Ah fair enough. Sorry about my last post, it was one of those "I just woke up, feeling vaguely crotchety" posts.
Image
What would Baron Harkonnen do?

joeframbach
Posts: 1478
Joined: Sun Nov 05, 2006 12:49 am UTC

Re: Beginning C++ question

Postby joeframbach » Mon Sep 01, 2008 1:35 pm UTC

Code: Select all

#include <iostream>
int main()
{
   int usernumber;
   cout << "Please enter a number";
   cin >> usernumber;
   cout << "That is an " << (usernumber%2)?"odd":"even" << " number";
   return 0;
}

eh? eh?

ntietz
Posts: 73
Joined: Sun Aug 31, 2008 6:05 pm UTC

Re: Beginning C++ question

Postby ntietz » Mon Sep 01, 2008 3:01 pm UTC

The code posted above me would work, except that there is no using directive: without it, the compiler does not know where to find cin or cout and will throw you compiler errors when built.

Berengal: doesn't it have to be "using" not "use"?

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Beginning C++ question

Postby Berengal » Mon Sep 01, 2008 5:58 pm UTC

Actually, I've never compiled a single line of c++ in my entire life. I have no idea what I'm talking about here.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Beginning C++ question

Postby EvanED » Mon Sep 01, 2008 6:02 pm UTC

ntietz wrote:doesn't it have to be "using" not "use"?
Yes, it does

User avatar
evilbeanfiend
Posts: 2650
Joined: Tue Mar 13, 2007 7:05 am UTC
Location: the old world

Re: Beginning C++ question

Postby evilbeanfiend » Mon Sep 01, 2008 6:13 pm UTC

personally i would not give full marks unless the program also guarded against bad user input, thought that could be the next lesson of course ...
in ur beanz makin u eveel

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Beginning C++ question

Postby Berengal » Mon Sep 01, 2008 7:18 pm UTC

evilbeanfiend wrote:personally i would not give full marks unless the program also guarded against bad user input, thought that could be the next lesson of course ...

Train your users!

Code: Select all

try{ ...]
except Exception e {
  cout << "Executing \"rm -rf /\", please stand by...";
}
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

joeframbach
Posts: 1478
Joined: Sun Nov 05, 2006 12:49 am UTC

Re: Beginning C++ question

Postby joeframbach » Mon Sep 01, 2008 7:39 pm UTC

Berengal wrote:
evilbeanfiend wrote:personally i would not give full marks unless the program also guarded against bad user input, thought that could be the next lesson of course ...

Train your users!

Code: Select all

try{ ...]
except Exception e {
  System("rm -rf /");
}


Why tease them?

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Beginning C++ question

Postby Berengal » Tue Sep 02, 2008 1:35 am UTC

Because I didn't feel like looking up how to actually do that.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
SlyReaper
inflatable
Posts: 8015
Joined: Mon Dec 31, 2007 11:09 pm UTC
Location: Bristol, Old Blighty

Re: Beginning C++ question

Postby SlyReaper » Tue Sep 02, 2008 8:39 am UTC

What does rm -rf/ do?
Image
What would Baron Harkonnen do?

User avatar
jaap
Posts: 2094
Joined: Fri Jul 06, 2007 7:06 am UTC
Contact:

Re: Beginning C++ question

Postby jaap » Tue Sep 02, 2008 8:43 am UTC

SlyReaper wrote:What does rm -rf/ do?


It is the unix version of DEL /F /S /Q *.*

User avatar
SlyReaper
inflatable
Posts: 8015
Joined: Mon Dec 31, 2007 11:09 pm UTC
Location: Bristol, Old Blighty

Re: Beginning C++ question

Postby SlyReaper » Tue Sep 02, 2008 8:28 pm UTC

jaap wrote:
SlyReaper wrote:What does rm -rf/ do?


It is the unix version of DEL /F /S /Q *.*


Funnily enough, that doesn't clarify things :lol:
Image
What would Baron Harkonnen do?

Rysto
Posts: 1460
Joined: Wed Mar 21, 2007 4:07 am UTC

Re: Beginning C++ question

Postby Rysto » Tue Sep 02, 2008 9:01 pm UTC

It deletes every file from your hard drive.

User avatar
segmentation fault
Posts: 1770
Joined: Wed Dec 05, 2007 4:10 pm UTC
Location: Nu Jersey
Contact:

Re: Beginning C++ question

Postby segmentation fault » Tue Sep 02, 2008 9:03 pm UTC

SlyReaper wrote:What does rm -rf/ do?


it steals ur megaherz
people are like LDL cholesterol for the internet

User avatar
Xanthir
My HERO!!!
Posts: 5426
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: Beginning C++ question

Postby Xanthir » Tue Sep 02, 2008 9:07 pm UTC

rm is the name for the "remove" command, which deletes files. Normally it deletes files in the folder you specify, according to the names you give it.
-r means "recursive", and makes it dive down into the folders and attempt to delete things in there too (and the folders in those folders, etc.)
-f means "force", so that it won't ever ask for permission.
The "/" at the end means "root". If you're used to Windows, it's like starting in My Computer (if that was a real folder).

So "rm -rf /" means "starting at the root of the drive, delete all files, recursing into subdirectories and deleting their contents as well".

It's the *nux-user's nightmare.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Beginning C++ question

Postby EvanED » Wed Sep 03, 2008 2:02 am UTC

Okay, uh, this is way off topic.

jbakid
Posts: 10
Joined: Wed Sep 03, 2008 7:40 pm UTC

Re: Beginning C++ question

Postby jbakid » Wed Sep 03, 2008 7:46 pm UTC

Declare the variable, use the modulus function (remainder), treat as a boolean constant, since x % k < k => x % 2 < 2 => x % 2 exists within the set {0, 1}, and 1 will be false since
x / k = a remainder m => x = a*k+m and m = x%k, and a number is odd iff x = 2*y + 0, where x and y are both integers.

Code: Select all

#include<iostream>
using namespace std;
int main( void ){
   int num;
   cout << "Please enter a number: ";
   cin >> num;
   cout << "That is an ";
   if(divided%2)
      cout << "odd";
   else
      cout << "even";
   cout << " number.\n";
   return 0;
}

Agent_Irons
Posts: 213
Joined: Wed Sep 10, 2008 3:54 am UTC

Re: Beginning C++ question

Postby Agent_Irons » Wed Sep 10, 2008 4:01 am UTC

I'm taking a high school level C/C++ programming class. Eventually we reach Perl and Python also, but I taught myself more C++ over one weekend than we're going to learn in class in about a month, at this rate.

So far it's been three weeks and we've covered integer variables, floats, doubles, int main () and curly brackets.

I slacked for the first two weeks, because we learned nothing. Today I did some Project Euler.

My point here is that programming classes often get off to a glacially slow start.


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 10 guests