Friday, October 4, 2013

C++ Tutorial #4: Your First C++ Program

Okay—this is where things are going to start getting a little confusing.  Really, the only way to learn the basics of a C++ program is to have one thrown right at you.  You won't understand a thing at first, but you'll learn as you dissect it.  And it will be a simple program, don't worry!

Tip: when you go to save the programs you write, BE SURE to save them in your designated programming folder.  In addition, now would be a good time to open up Command Prompt and use cd.. and cd to navigate to your programming folder.

Programming Project #1: Hello.cpp

Ready to write your first C++ program?  Good!  Let's go!

1) Open Dev-C++.
2) In the toolbar, click File > New > Source File.  (If you like keystrokes, you can also use Ctrl-N.)
3) Type out the following code exactly.  Any typo will result in an error when you go to compile it into machine code.

Note (this is not part of the code): in "int main()", those are two regular parentheses, with square brackets enclosing the other part of the program (the "cout" part and "return 0").  And for all indentations, I use a single tab, but it doesn't matter.  Just indent somehow (it looks neater).

#include <iostream>

using namespace std;

int main()
     cout << "Hello, world!" << endl;
     return 0;

4) In the toolbar, click Execute > Compile (keystroke: Ctrl-F9).  A "Save" box will pop up.  Make sure you're in your programming folder before you save.  Name your program Hello.cpp and hit Save.  It will then begin compiling.
     4a: If everything goes well, it'll compile nicely and say Done when it's done.
     4b: If something goes wrong, it'll give you an error message with the line number where a problem was found.  Go back and make sure you typed out everything correctly (C++ is a very finicky language).  Check other lines in addition to the line reported in the error.  Sometimes the error in one line is caused by a mistake in a completely different line (you can imagine how frustrating this gets in larger programs).

5) In the same folder where you saved Hello.cpp, you'll see another file called Hello.exe.  Remember how we talked about having two files for every program you write?  Hello.cpp is your source file (your original code in C++).  Hello.exe is the executable file, which is written in binary and can be understood by the computer.

6) At this point, you've created a fine, working program.  But there's one small issue: if you were to run Hello.exe, you'd see a black box appear for a split-second and then disappear.  This is because your computer runs fast, and all the program commanded it to do was flash "Hello, world!" on the screen for a split-second.  In order to get a good look at your work, you have to take a few extra steps:

6a) Open Command Prompt by searching for it or running "cmd.exe". 

6b) Navigate to the folder where you're keeping your programs by using cd.. and cd.

6c) Once you get to your designated folder, type "Hello.exe" and press Enter.

Your program will run and close, but since you were already in Command Prompt anyway when you ran it, the window won't close when the program stops.  This way, you'll have validation that the program worked exactly as intended.

Dissecting Hello.cpp
  • Why are there so many semicolons?  C++ is a language.  Therefore, it should be thought of as a language, no different from any other language.  Like other languages (for example, English), C++ has rules regarding its syntax (how the language is structured).  There's grammar, punctuation, and good structure vs. bad and difficult-to-understand structure.  Each line of code should be thought of as a sentence.  The semicolon (;) acts as a period for most "sentences".  The tricky thing is remembering where they go and where they don't.  That's something you'll get used to over time.  Generally, major lines such as #includes or starting functions (see below) don't have them, while more specific lines such as declaring variables and giving minor commands do.
  • #include <iostream>—this is something called the preprocessor.  There's a lot of code that needs to go into programs to make even small commands work—extra code that no programmer wants to have to write every single time he or she creates a new file.  When you downloaded Dev-C++, you also got a bunch of extra files with code that's commonly seen in programs.  These are called library files.  One of the most common library files is iostream.  Thus, #include <iostream> tells the computer, "Take the code from iostream and just stick it right here."  Really, all it does is copy-and-paste from another file, saving you time and aggravation.
  • using namespace std;—that's standard.  Namespaces are kind of complicated, and—to be perfectly honest—the introductory class I took really didn't go too far into them.  As I say in my "obligatory disclaimer" (see the tabs at the top of the page), I will not elaborate on any subject with which I am not appropriately familiar.  For now, just know that it's a line you have to include in all your programs in this tutorial, always after #include <iostream>.
  • int main()—programs in C++ are divided into functions.  A function is a chunk of code that does something; each function in a program has a different job or purpose.  Every program in C++ has at least one function.  In the beginning, you'll be writing one-function programs, and your single function will be entitled main.  Later, when you're writing programs with multiple functions, main will still be in charge of other functions.  The contents of functions must be enclosed in curly braces.  The int part will be discussed later.
  • cout—pronounced "see-out".  This basically means "output this on the screen".  You use two less-than signs (<<), type what you want to be displayed with quotation marks (the quotation marks won't be displayed), and then add two more less-than signs.
  • endl;—also referred to as an "endline".  This means "insert a line break and carriage return".  It's the C++ equivalent of hitting the Enter key after displaying "Hello world!"
  • return 0;—here's where int comes back.  Computers are really just big calculators, and they deal in numbers.  Therefore, all functions must end by reporting back some kind of number value to the program (which, in turn, reports a number back to the operating system before closing).  By declaring the main function as int main, we stated that the number to be returned would be an int, or integer.  Different numbers that are returned mean different things.  Returning 0 means the program completed and is closing without any issues or errors.  Returning 1 means the program is closing, but because of some kind of problem that occurred.  Get used to writing this line, because all functions must return some value, and main almost always returns a value of 0.
At this point, the function main is done, so we close it off with a curly brace.

I'm going to look in my old notebook for more examples of programs you can try out.  For now, if you want practice, you can write more programs outputting different things in the cout statements.  (You can even write more than one cout statement, if you want!  Just make sure they're on different lines, and write them all using the same syntax.)  And, as always, comment or email me with any questions.  I'll be happy to answer the best I can.  :-)


No comments:

Post a Comment