Your First C++ Output Program, Explained with Code Examples

UPI Study › Courses › C++ Programming › Free lessons › Lesson 2.7 Free with a free account

Your First C++ Output Program

C++ Programming · Chapter 2: Getting Started with C++Section 2.7 · lesson 14 of 84video coming soon

← Putting Data Into VariablesNext lesson: Number Crunching in Code →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

In this lesson

Six lines, one command, and a message on the screen.

  • Explain every line of a minimal program
  • Send several items to the output stream
  • Use escape sequences inside string literals
  • Read a compiler error closely enough to act on it

Transcript

Everything said in the video, section by section (1,689 words). Read along, or search it.

Opening Question

The Smallest Complete Program

What's the smallest complete program that can make a computer say something? In C++, it's six lines of text, one command, and a message on the screen. It's the moment everything so far stops being description, and starts being something you operate. By the end, you'll be able to say what every line is for, and what happens when you take one away.

Program Overview

Every Remaining Line Is Load-Bearing

Here's the whole program, in a file named hello.cpp. Type it exactly as shown, punctuation included. First, a comment naming the file. Then, #include <iostream>. Then int main, with empty parentheses, and a pair of braces. Inside, one statement sends Hello, world, and a newline, to std::cout. Then, return 0. Notice what isn't here. Nothing announces the program's name, nothing sets it up, nothing closes it down. Every line that remains is load-bearing. Remove one, and the program either fails to build, or stops doing its job. That's exactly the experiment at the end of this video.

Line Explained

Include Pastes In the Library

The language itself has no idea how to print. Printing isn't built in, the way addition is. It comes from the standard library, and a program must ask for it by name. That's the job of line 2. The hash marks an instruction to the preprocessor, which runs before compilation, and edits the text. When it meets #include, it finds the named file, and pastes its entire contents in at that point. iostream stands for input and output streams. The angle brackets say: look in the library's own locations. After the paste, your short file is many thousands of lines long, including the declarations that tell the compiler what std::cout is. Then the compiler checks and translates it, and the linker joins in the library code, producing a file you can run. One command triggers that whole sequence. Leave out the include, and the compiler simply says it has never heard of std::cout.

Line Explained

Main Is Where Execution Starts

Every C++ program has exactly one function named main, and that's where execution starts. Not at the first line of the file, but at the first statement inside main. When main finishes, the program is over. The int in front says main hands back a whole number when it finishes. The empty parentheses say it takes nothing in. That number is the program's exit code, and it isn't for you. It's for whatever started the program. By convention, 0 means success, and anything else means something went wrong. You can see it. Build and run the program, then ask the shell for the last exit code. Here, it's 0.

Exit Codes

Return 0 Means Success

Return 0 means finished successfully. Write it, even though you don't strictly have to, because it states the intent. Return 1, or any nonzero value, means finished, but something went wrong. Which number means which failure is up to you. Writing nothing at all is treated as return 0. Main is the one function allowed to leave its return out. And void main is not valid C++. It shows up in old material, and some compilers tolerate it, but the standard requires int. This matters more than it seems. Automated systems that build, test and deploy software check each step's exit code before continuing.

Line Explained

Sending Text Through std::cout

The one working statement sends text to the screen, and it has three parts. std::cout is a stream: an object representing a destination characters can be sent to. Here, that's standard output, normally the terminal. The two arrows are the insertion operator. Read it as: send this into that. And notice that the arrows point toward the destination. That's a useful memory aid. The third part is what gets sent: a string literal, fixed text between double quotation marks. One statement can send as many items as you like, each with its own arrows. They arrive left to right, with nothing inserted between them. So this prints Total, 40, plus 2 items, as one line. The spaces around the plus sign were inside the literals, put there on purpose.

Definition

Escape Sequences for Special Characters

Almost everything inside a string literal is taken exactly as typed. Two things can't be. A double quotation mark would end the literal. And a newline can't be typed directly, because a literal can't span two lines of source. The fix is the backslash. Inside a literal, a backslash means: read this pair as one special character. The pair is an escape sequence. Backslash n is a new line, by far the most used. Backslash t is a tab. Backslash quote is a double quotation mark that doesn't end the literal. Two backslashes make one backslash. And backslash single quote is a single quotation mark. Here they are together: a tab between Name and Score, escaped quotation marks around ready, and a doubled backslash, which prints a single one.

Common Mistakes

Missing Newline and Lone Backslash

Two mistakes catch everyone here. First, forgetting the line ending. Output doesn't move to a new line by itself. Take the newline off the first line and rebuild, and two statements run their text together. That looks like a bug in the program, and it isn't. Nobody asked for a new line. Second, a lone backslash. Writing C colon, backslash, new, doesn't print that path. The backslash n is read as a newline, so the path is split across two lines. What you wanted was a doubled backslash. Run it again, and the whole path prints, exactly as typed.

Comparison

Newline Versus std::endl Flushing

You'll often see lines ending with std::endl, instead of a newline. In a small program, the result looks identical. But they're not the same. Output is buffered. Characters sent to std::cout collect in a holding area in memory, and reach the terminal in batches, because handing them over one at a time is slow. Emptying that area early is called flushing. A newline character puts a line ending into the buffer, and nothing more. std::endl adds the same line ending, then forces a flush, every time. In a loop printing thousands of lines, that extra work is paid thousands of times, for no benefit. So use the newline, unless you have a reason to flush. The one beginners genuinely meet is debugging. If a program stops unexpectedly, output still in the buffer can be lost. A line printed with std::endl reaches the screen before the next statement runs.

Design Choice

Why Write std:: in Full

Everything the standard library provides lives inside a namespace called std. Writing std::cout means: the cout that belongs to std. Typing that prefix everywhere gets tiresome, which is why many examples open with using namespace std, switching it off. In a small file, that's not a mistake. But it brings every library name into your file at once, including ordinary words like count, distance and size. If your own code defines one of those, they collide, and the error is long and unhelpful. In a header that others include, the problem lands on them, which is why the directive is unacceptable there. The middle option, using std::cout, brings in just one name, with nearly all the convenience and almost none of the risk. While you're learning, write std:: in full. It makes visible which names came from the library, and which are yours.

Workflow

Building Versus Running Your Program

Building and running are two separate steps, and confusing them is the most common early frustration. Building turns your source file into an executable, once after each edit: g++ hello.cpp -o hello. It prints nothing when it succeeds. Silence means success. Running starts that executable, and can be repeated without rebuilding: ./hello. Four things go wrong first. No such file means your terminal is in the wrong folder, not that the file is broken. Old output after an edit means you didn't rebuild. And running hello.cpp tries to run the source, not the program. And command not found, with the file sitting right there, means you dropped the dot slash.

Quick Check

Predict the Score Output

Quick check. What does this line print: "Score: ", then 7, then 3? Think about what goes between the items. Pause and predict.

Answer

Score: 73 With No Separator

It prints Score: 73. Nothing is inserted between items, so 7 and 3 run together. And there's no newline at the end, so whatever prints next would continue on the same line.

Reading Errors

Anatomy of a Compiler Message

Compiler messages read as hostile, until you've seen a few. They all share one structure. Delete the semicolon after the output statement, and build again. First comes the file name, then the line, then the column, then how serious it is, and finally what the compiler expected. Here, Clang says it expected a semicolon after the expression, at line 6, column 35. G++ on Linux words it as: expected a semicolon before return. It only noticed when it reached the next line. So build this habit. When a message names a line that looks perfectly fine, look at the line above it. An error stops the build. A warning doesn't, but it's usually still worth fixing.

Hands-On Experiment

Breaking the Program on Purpose

The fastest way to get comfortable is to break a working program on purpose, one change at a time, rebuilding after each. Delete the include line, and Clang reports that std is an undeclared identifier. Without the library's declarations, the name means nothing. G++ says cout is not a member of std, and adds a note naming the missing include. So read the whole message, not just the first line. Put it back, and remove the std:: prefix instead. Now the message offers the fix outright: did you mean std::cout? The name exists, just not by that name here. Delete the closing brace, and it expects a brace at the end, with a note pointing back at the opening brace it's still waiting for. And one rule above all. Fix only the first error, then rebuild. One mistake often produces a cascade, and it's normal for fourteen messages to become zero after one corrected character.

Key Takeaways

Summary of Your First Program

To summarize. The include line asks the standard library for its printing machinery. Main is where execution starts, and it hands back an exit code when it finishes: 0 for success. std::cout, with the insertion arrows, sends text to the output. Chained items arrive with nothing between them. Escape sequences supply the characters you can't type directly, like the newline. And when the compiler complains, read the whole message, look one line up, and fix the first error only.

About C++ Programming at UPI Study

C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

C++ Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Your First C++ Output Program

What does each line of a minimal C++ output program do?
Each line has one job. The line #include <iostream> pastes in the library declarations that tell the compiler what std::cout is. int main() marks where execution starts and returns an exit code. The std::cout statement sends text to the screen. return 0 reports success, but main may omit it, because leaving it out is treated as return 0. Removing the include, main, or the output statement breaks the build or stops the program from printing.
How do I print several items with one std::cout statement in C++?
Chain the items with one insertion operator (<<) before each. For example, std::cout << "Total: " << 40 << " plus " << 2 << "\n"; prints Total: 40 plus 2 and then ends the line. The items arrive left to right, and nothing is inserted between them. Any spaces you want must be inside the string literals.
How do escape sequences work in C++ string literals?
Inside a string literal, a backslash plus a character is read as one special character. \n is a newline, \t is a tab, \" is a double quotation mark that does not end the literal, and \\ prints a single backslash. For example, std::cout << "Name\tScore\n"; prints Name, a tab, then Score, and then moves to a new line.
How do I read a C++ compiler error like "expected a semicolon"?
A compiler message gives the file name, line, column, severity, and what the compiler expected. If you delete the semicolon after a std::cout statement, Clang reports an expected semicolon. G++ may name the next line instead, so check the line above the one it points to. Fix only the first error and rebuild, since one mistake can cause many messages.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in C++ Programming.

84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

C++ Programming
3 credits · NCCRS
Enroll →