Lesson 6
First Program in C++: Input and Output Using cin and cout
Introduce program structure, variables, `cin`, `cout`, and the flow of input/output in C++.
Lesson content
The first C++ program demonstrates program structure, variables, user input with `cin`, and output with `cout`.
First Program Example
#include <iostream>
using namespace std;
int main() {
int a;
cout << "Enter a number: ";
cin >> a;
cout << "The number is: " << a << endl;
return 0;
}Understanding the Program Step by Step
Header File
`#include <iostream>` includes the input/output stream library needed for `cin` and `cout`.
Namespace
`using namespace std;` lets you use `cin` and `cout` without the `std::` prefix.
Main Function
`int main()` is the program entry point where execution begins.
Variable Declaration
`int a;` declares an integer variable to store the user's input.
Input Statement (`cin`)
`cin >> a;` reads a value from the keyboard and stores it in `a`. The `>>` operator is the extraction operator.
Output Statement (`cout`)
`cout << "The number is: " << a;` prints text and the value of `a` to the console. The `<<` operator is the insertion operator.
Program Flow
- Ask the user for input using `cout`.
- Read the user's input with `cin`.
- Process or store the input in variables.
- Display results with `cout`.
Best Practices for Beginner Programs
- Use clear prompts for input (e.g., 'Enter a number: ').
- Validate input in real programs to avoid errors.
- Use meaningful variable names when appropriate.
- Keep code simple and add comments for clarity.
Frequently Asked Questions
What is the purpose of `cin`?
`cin` reads input from the standard input (keyboard) into variables.
What does `cout` do?
`cout` writes output to the standard output (console).