C++ for beginners, part 3

In the previous post, we turned an R function into a C++ function. Problem is, you have to compile and run it each time you want to get the answer. On top of that, the code only works on one set of factors, over one range of numbers. Balls to that. Let’s add a little flexibility to the system.

Meet Michael. He’s a function that returns the sum of multiples of 3 or 5 in the range of 1-1000:

Michael function

Meet George: He’s a function that returns the sum of multiples of 5 and 7, in the range of 1-2000:

George function

white michael chiklis

“You guys are talking about the same person. He’s biracial, his name is David, and he’s a human being.”

So, how do we let the user define the variables from the outside, and put a rest to Michael’s/George’s multiple-personality disorder? Well, we already have cout<< (c-output). For user-input, we have ‘cin>>’. Makes sense. And, according to the cplusplus site, equally straightforward to use. [Note: I remember which way round the symbols are because << is shaped like traffic-cone loudspeakers (output), and >> is shaped like one of those barbed animal penises (input). Yup.] Anyway, you just use ‘cin>>your-variable’ after you’ve declared your variable (e.g. int n1), but before it needs to be used (i.e. the for-loop). When you compile and run it, it won’t give you the answer unless you type in your variables. Like so:

Pic1

Now, a nice little detail that makes your code look tidier: when declaring variables of the same type, or requesting multiple inputs from a user at the same time, you don’t need to have the code on separate lines. For declaring variables, separate them with a comma. For multiple inputs, separate them with >> like so:

Pic2

Note: when you actually run the function, you can type your input on the same line or on different lines regardless of how your code is formatted.

So, now we’ve gotten it to take arbitrary inputs, but we still need to run the program each time we want an answer. Wouldn’t it be nice to call the function as many times as we wanted without needing to run the program each time? Also, here we only have three inputs (two factors and an upper bound, in that order). It’s  little trickier to remember which order the variables are in if you need, say, ten inputs. Let’s deal with the latter problem first.

Turns out it’s really simple. We just use ‘cout<<‘ to tell the user what the next input should be:

Pic3

Swish.

As for reusing the function again and again, we essentially want our code to state: “while the user wants to keep reusing the function, do this highlighted stuff

Pic4

and only stop when the user says so”. How do we do that? The answer is the very first word of the statement, while. It’s just a case of: while (a particular condition is true) { do all this crap }

It’s so easy even a man as inept as Gob Bluth:

can write a while-loop:

All we do is declare a new variable, let’s say ‘useranswer’, and make it of the type ‘char’ (character, a single letter/number that the user can input. these are in single quotes, unlike the double quotes used for cout). We initialize it to ‘y’ (yes), and say that while useranswer is ‘y’, we run the function. After outputting the answer, the code asks the user if it wants to run again, and requests an input. The moment the input is no longer ‘y’, the condition no longer holds and the function stops:

Pic5

Let’s do two other simple things. If you’re running the function many times and want to look back over the answers, you may wanna be able to identify the answers quicker, so we can easily put “The answer is” before the answer:

Pic6

And lastly, what if the user mistypes? Maybe they wanted to run it again, maybe they didn’t. Let’s code up that consideration with a short if-statement:

Pic7

  • Line 26: ‘!=’ means ‘NOT equal to’.
  • Line 26: ‘&&’ means both conditions must be met.
  • So if useranswer is not equal to ‘y’ AND not equal to ‘n’, the if-statement gets executed. More on logical operators here.
  • Line 28: We reset useranswer to ‘y’, meaning the useranswer==’y’ condition is still met when we exit the if-statement code, and the while-loop can continue as normal.
  • Lines 29 & 30: Feel free to make these warnings as passive-aggressive as you want.

A quick note: if the user mistypes and enters more than one letter, the code crashes, because useranswer is no longer a ‘character’, it’s a ‘string’.

Pic8

I don’t know how to get around this, yet. We’ll leave it for now, because I have no doubt we’ll encounter strings in detail when we get to problem 4 (palindromic numbers!). In the meantime, the next post will be turning the other two R functions from problem 1 into C++ functions. That will be quick and painless (I promise!), and then we’ll use these to write a C++ program that includes all 3 functions which you can choose between.

I will try and get that post up as soon as possible because I really want to move on to problem 2 (hello Fibonacci numbers!). Like problem 1, there’s a brute force approach, and an elegant* mathematical approach. The latter is a powerhouse of proof, a smörgåsbord of solutions, a tour-de-force of technique, a buffet of brilliance, and other alliterative approaches. It’s one hell of a scenic route, taking in such logical landmarks as: generating functions, partial fractions, the factor theorem, equating coefficients, and infinite series analysis. And it is fucking awesome.

*Your mileage may vary on the degree of ‘elegance’ you see in the proof. Which is likely why pages like this exist. Anyway, ’till next time:

blackmikewhitegeorge2

Advertisements
This entry was posted in C++, Problem 1 and tagged , . Bookmark the permalink.

2 Responses to C++ for beginners, part 3

  1. Pingback: C++ for beginners, part 8a (finishing the project) | hercles

  2. Pingback: C++ for beginners, part 8b (the end) | hercles

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s