{"id":7903,"date":"2019-02-01T10:11:37","date_gmt":"2019-02-01T18:11:37","guid":{"rendered":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/?p=7903"},"modified":"2024-03-12T17:51:28","modified_gmt":"2024-03-13T00:51:28","slug":"developing-your-first-program","status":"publish","type":"post","link":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/developing-your-first-program\/","title":{"rendered":"1.11 &#8212; Developing your first program"},"content":{"rendered":"<p>The preceding lessons have introduced a lot of terminology and concepts that we&#8217;ll use in just about every program we create.  In this lesson, we&#8217;ll walk through the process of integrating this knowledge into our first simple program.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Multiply by 2<\/p>\n<p>First, let&#8217;s create a program that asks the user to enter an integer, waits for them to input an integer, then tells them what 2 times that number is.  The program should produce the following output (assume I entered 4 as input):<\/p>\n<pre>\r\nEnter an integer: 4\r\nDouble that number is: 8\r\n<\/pre>\n<p>How do we tackle this?  In steps.<\/p>\n<div class=\"cpp-note cpp-lightgreenbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Best practice<\/p>\n<p>New programmers often try to write an entire program all at once, and then get overwhelmed when it produces a lot of errors.  A better strategy is to add one piece at a time, make sure it compiles, and test it.  Then when you&#8217;re sure it&#8217;s working, move on to the next piece.\n<\/p><\/div>\n<p>We&#8217;ll leverage that strategy here.  As we go through each step, type (don&#8217;t copy\/paste) each program into your code editor, compile, and run it.<\/p>\n<p>First, create a new console project.<\/p>\n<p>Now let&#8217;s start with some basic scaffolding.  We know we&#8217;re going to need a main() function (since all C++ programs must have one), so if your IDE didn&#8217;t create a blank one when you created a new project, let&#8217;s create one:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int main()\r\n{\r\n\treturn 0;\r\n}<\/code><\/pre>\n<p>We know we&#8217;re going to need to output text to the console, and get text from the user&#8217;s keyboard, so we need to include iostream for access to std::cout and std::cin.<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n\r\nint main()\r\n{\r\n\treturn 0;\r\n}<\/code><\/pre>\n<p>Now let&#8217;s tell the user that we need them to enter an integer:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n\r\nint main()\r\n{\r\n\tstd::cout &lt;&lt; \"Enter an integer: \";\r\n\r\n\treturn 0;\r\n}<\/code><\/pre>\n<p>At this point, your program should produce this result:<\/p>\n<pre>\r\nEnter an integer:\r\n<\/pre>\n<p>and then terminate.<\/p>\n<p>Next, we&#8217;re going to get the user&#8217;s input.  We&#8217;ll use std::cin and <code>operator&gt;&gt;<\/code> to get the user&#8217;s input.  But we also need to define a variable to store that input for use later.<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n\r\nint main() \/\/ note: this program has an error somewhere\r\n{\r\n\tstd::cout &lt;&lt; \"Enter an integer: \";\r\n\r\n\tint num{ }; \/\/ define variable num as an integer variable\r\n\tstd::cin &lt;&lt; num; \/\/ get integer value from user's keyboard\r\n\r\n\treturn 0;\r\n}<\/code><\/pre>\n<p>Time to compile our changes&#8230; and&#8230;<\/p>\n<p>Uh oh!  Here&#8217;s what the author got on Visual Studio 2017:<\/p>\n<pre>\r\n1&gt;------ Build started: Project: Double, Configuration: Release Win32 ------\r\n1&gt;Double.cpp\r\n1&gt;c:\\vcprojects\\double\\double.cpp(8): error C2678: binary '&lt;&lt;': no operator found which takes a left-hand operand of type 'std::istream' (or there is no acceptable conversion)\r\n1&gt;c:\\vcprojects\\double\\double.cpp: note: could be 'built-in C++ operator&lt;&lt;(bool, int)'\r\n1&gt;c:\\vcprojects\\double\\double.cpp: note: while trying to match the argument list '(std::istream, int)'\r\n1&gt;Done building project \"Double.vcxproj\" -- FAILED.\r\n========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========\r\n<\/pre>\n<p>We ran into a compile error!<\/p>\n<p>First, since the program compiled before we made this latest update, and doesn&#8217;t compile now, the error <em>must<\/em> be in the code we just added (lines 7 and 8).  That significantly reduces the amount of code we have to scan to find the error.  Line 7 is pretty straightforward (just a variable definition), so the error probably isn&#8217;t there.  That leaves line 8 as the likely culprit.<\/p>\n<p>Second, this error message isn&#8217;t very easy to read.  But let&#8217;s pick apart some key elements: The compiler is telling us it ran into the error on line 8.  That means the actual error is probably on line 8, or possibly the preceding line, which reinforces our previous assessment.  Next, the compiler is telling you that it couldn&#8217;t find a &#8216;&lt;&lt;&#8216; operator that has a left-hand operand of type std::istream (which is the type of std::cin).  Put another way, operator&lt;&lt; doesn&#8217;t know what to do with std::cin, so the error must be either with our use of std::cin or our use of operator&lt;&lt;.<\/p>\n<p>See the error now?  If you don&#8217;t, take a moment and see if you can find it.<\/p>\n<p>Here&#8217;s the program that contains the corrected code:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n\r\nint main()\r\n{\r\n\tstd::cout &lt;&lt; \"Enter an integer: \";\r\n\r\n\tint num{ };\r\n\tstd::cin &gt;&gt; num; \/\/ std::cin uses operator &gt;&gt;, not operator &lt;&lt;!\r\n\r\n\treturn 0;\r\n}<\/code><\/pre>\n<p>Now the program will compile, and we can test it.  The program will wait for you to enter a number, so let&#8217;s enter 4.  The output should look like this:<\/p>\n<pre>\r\nEnter an integer: 4\r\n<\/pre>\n<p>Almost there!  Last step is to double the number.<\/p>\n<p>Once we finish this last step, our program will compile and run successfully, producing the desired output.<\/p>\n<p>There are (at least) 3 ways we can go about this.  Let&#8217;s go from worst to best.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">The not-good solution<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n\r\n\/\/ worst version\r\nint main()\r\n{\r\n\tstd::cout &lt;&lt; \"Enter an integer: \";\r\n\r\n\tint num{ };\r\n\tstd::cin &gt;&gt; num;\r\n\r\n\tnum = num * 2; \/\/ double num's value, then assign that value back to num\r\n\r\n\tstd::cout &lt;&lt; \"Double that number is: \" &lt;&lt; num &lt;&lt; '\\n';\r\n\r\n\treturn 0;\r\n}<\/code><\/pre>\n<p>In this solution, we use an expression to multiply <em>num<\/em> by 2, and then assign that value back to <em>num<\/em>.  From that point forward, <em>num<\/em> will contain our doubled number.<\/p>\n<p>Why this is a bad solution:<\/p>\n<ul>\n<li>Before the assignment statement, num contains the user&#8217;s input.  After the assignment, it contains a different value.  That&#8217;s confusing.\n<li>We overwrote the user&#8217;s input by assigning a new value to the input variable, so if we wanted to extend our program to do something else with that input value later (e.g. triple the user&#8217;s input), it&#8217;s already been lost.\n<\/ul>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">The mostly-good solution<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n\r\n\/\/ less-bad version\r\nint main()\r\n{\r\n\tstd::cout &lt;&lt; \"Enter an integer: \";\r\n\r\n\tint num{ };\r\n\tstd::cin &gt;&gt; num;\r\n\r\n\tint doublenum{ num * 2 }; \/\/ define a new variable and initialize it with num * 2\r\n\tstd::cout &lt;&lt; \"Double that number is: \" &lt;&lt; doublenum &lt;&lt; '\\n'; \/\/ then print the value of that variable here\r\n\r\n\treturn 0;\r\n}<\/code><\/pre>\n<p>This solution is pretty straightforward to read and understand, and resolves both of the problems encountered in the worst solution.<\/p>\n<p>The primary downside here is that we&#8217;re defining a new variable (which adds complexity) to store a value we only use once.  We can do better.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">The preferred solution<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n\r\n\/\/ preferred version\r\nint main()\r\n{\r\n\tstd::cout &lt;&lt; \"Enter an integer: \";\r\n\r\n\tint num{ };\r\n\tstd::cin &gt;&gt; num;\r\n\r\n\tstd::cout &lt;&lt; \"Double that number is: \" &lt;&lt;  num * 2 &lt;&lt; '\\n'; \/\/ use an expression to multiply num * 2 at the point where we are going to print it\r\n\r\n\treturn 0;\r\n}<\/code><\/pre>\n<p>This is the preferred solution of the bunch.  When std::cout executes, the expression <em>num * 2<\/em> will get evaluated, and the result will be double <em>num<\/em>&#8216;s value.  That value will get printed.  The value in <em>num<\/em> itself will not be altered, so we can use it again later if we wish.<\/p>\n<p>This version is our reference solution.<\/p>\n<div class=\"cpp-note cpp-lightgraybackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Author&#8217;s note<\/p>\n<p>The first and primary goal of programming is to make your program work.  A program that doesn&#8217;t work isn&#8217;t useful regardless of how well it&#8217;s written.<\/p>\n<p>However, there&#8217;s a saying I&#8217;m fond of: &#8220;You have to write a program once to know how you should have written it the first time.&#8221;  This speaks to the fact that the best solution often isn&#8217;t obvious, and that our first solutions to problems are usually not as good as they could be.<\/p>\n<p>When we&#8217;re focused on figuring out how to make our programs work, it doesn&#8217;t make a lot of sense to invest a lot of time into code we don&#8217;t even know if we&#8217;ll keep.  So we take shortcuts.  We skip things like error handling and comments.  We sprinkle debugging code throughout our solution to help us diagnose issues and find errors.  We learn as we go -- things we thought might work don&#8217;t work after all, and we have to backtrack and try another approach.<\/p>\n<p>The end result is that our initial solutions often aren&#8217;t well structured, robust (error-proof), readable, or concise.  So once your program is working, your job really isn&#8217;t done (unless the program is a one-off\/throwaway).  The next step is to cleanup your code.  This involves things like: removing (or commenting out) temporary\/debugging code, adding comments, handling error cases, formatting your code, and ensuring best practices are followed.  And even then, your program may not be as simple as it could be -- perhaps there is redundant logic that can be consolidated, or multiple statements that can be combined, or variables that aren&#8217;t needed, or a thousand other little things that could be simplified.  Too often new programmers focus on optimizing for performance when they should be optimizing for maintainability.<\/p>\n<p>Very few of the solutions presented in these tutorials came out great the first time.  Rather, they&#8217;re the result of continual refinement until nothing else could be found to improve.  And in many cases, readers still find plenty of other things to suggest as improvements!<\/p>\n<p>All of this is really to say: don&#8217;t be frustrated if\/when your solutions don&#8217;t come out wonderfully optimized right out of your brain.  That&#8217;s normal.  Perfection in programming is an iterative process (one requiring repeated passes).\n<\/p><\/div>\n<div class=\"cpp-note cpp-lightgraybackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Author&#8217;s note<\/p>\n<p>One more thing: You may be thinking, &#8220;C++ has so many rules and concepts.  How do I remember all of this stuff?&#8221;.<\/p>\n<p>Short answer: You don&#8217;t.  C++ is one part using what you know, and two parts looking up how to do the rest.<\/p>\n<p>As you read through this site for the first time, focus less on memorizing specifics, and more on understanding what&#8217;s possible.  Then, when you have a need to implement something in a program you&#8217;re writing, you can come back here (or to a reference site) and refresh yourself on how to do so.\n<\/p><\/div>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Quiz time<\/p>\n<div class=\"quiz\" style=\"clear: both\">\n<p class=\"quiz-header\">Question #1<\/p>\n<p>Modify the solution to the &#8220;best solution&#8221; program above so that it outputs like this (assuming user input 4):<\/p>\n<pre>\r\nEnter an integer: 4\r\nDouble 4 is: 8\r\nTriple 4 is: 12\r\n<\/pre>\n<p><a class=\"solution_link_show\" href=\"javascript:void(0)\" onclick=\"cppSolutionToggle(document.getElementById('cpp_solution_id_0'), this, 'Show Solution', 'Hide Solution')\">Show Solution<\/a><\/p>\n<div class=\"wpsolution\" id=\"cpp_solution_id_0\" style=\"display:none\">\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n\r\nint main()\r\n{\r\n\tstd::cout &lt;&lt; \"Enter an integer: \";\r\n\r\n\tint num{ };\r\n\tstd::cin &gt;&gt; num;\r\n\r\n\tstd::cout &lt;&lt; \"Double \" &lt;&lt; num &lt;&lt; \" is: \" &lt;&lt; num * 2 &lt;&lt; '\\n';\r\n\tstd::cout &lt;&lt; \"Triple \" &lt;&lt; num &lt;&lt; \" is: \" &lt;&lt; num * 3 &lt;&lt; '\\n';\r\n\r\n\treturn 0;\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<div class=\"prevnext\"><div class=\"prevnext-inline\">\n\t<a class=\"nav-link\" href=\"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/chapter-1-summary-and-quiz\/\">\n <div class=\"nav-button nav-button-next\">\n    <div class=\"nav-button-icon\"><i class=\"fa fa-chevron-circle-right\" aria-hidden=\"true\"><\/i><\/div>\n    <div class=\"nav-button-text\">\n      <div class=\"nav-button-title\">Next lesson<\/div>\n      <div class=\"nav-button-lesson\">\n        <span class=\"nav-button-lesson-number\">1.x<\/span>Chapter 1 summary and quiz\n      <\/div>\n    <\/div>\n  <\/div><\/a>\n  \t<a class=\"nav-link\" href=\"\/https\/www.learncpp.com\/\">\n  <div class=\"nav-button nav-button-index\">\n    <div class=\"nav-button-icon\"><i class=\"fa fa-home\" aria-hidden=\"true\"><\/i><\/div>\n    <div class=\"nav-button-text\">\n      <div class=\"nav-button-title\">Back to table of contents<\/div>\n    <\/div>\n<\/div><\/a>\n  \t<a class=\"nav-link\" href=\"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/introduction-to-expressions\/\">\n  <div class=\"nav-button nav-button-prev\">\n    <div class=\"nav-button-icon\"><i class=\"fa fa-chevron-circle-left\" aria-hidden=\"true\"><\/i><\/div>\n    <div class=\"nav-button-text\">\n      <div class=\"nav-button-title\">Previous lesson<\/div>\n      <div class=\"nav-button-lesson\">\n        <span class=\"nav-button-lesson-number\">1.10<\/span>Introduction to expressions\n      <\/div>\n    <\/div>\n  <\/div><\/a>\n  <\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>The preceding lessons have introduced a lot of terminology and concepts that we&#8217;ll use in just about every program we create. In this lesson, we&#8217;ll walk through the process of integrating this knowledge into our first simple program. First, let&#8217;s create a program that asks the user to enter an &hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[3],"tags":[],"_links":{"self":[{"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts\/7903"}],"collection":[{"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/comments?post=7903"}],"version-history":[{"count":20,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts\/7903\/revisions"}],"predecessor-version":[{"id":16771,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts\/7903\/revisions\/16771"}],"wp:attachment":[{"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/media?parent=7903"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/categories?post=7903"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/tags?post=7903"}],"curies":[{"name":"wp","href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/api.w.org\/{rel}","templated":true}]}}