C++ Programming: Introduction to Program Development Study Guide
Learning Objectives for C++ Program Development
The following objectives outline the core competencies to be acquired in this chapter regarding C++ programming:
- Program Components: Become familiar with basic components, including functions, special symbols, and identifiers.
- Data Types: Explore simple data types and the specific properties of the string data type.
- Arithmetic Operators: Discover how to utilize and implement logical arithmetic operators.
- Expression Evaluation: Examine the processes by which a program evaluates complex arithmetic expressions.
- Assignment Statements: Learn the definition, syntax, and functional purpose of assignment statements.
- Data Input: Discover the methodologies for inputting data into computer memory using input statements.
- Increment and Decrement: Become familiar with the syntax and application of increment and decrement operators.
- Output Results: Examine various ways to output computational results using output statements.
- Preprocessor Directives: Learn the usage and necessity of preprocessor directives in the C++ environment.
- Program Structure: Explore the proper structural organization of a program, including the effective use of comments.
- Writing Programs: Acquire the fundamental skills necessary to write a complete C++ program.
Basic Structure of a C++ Program
A standard C++ program follows a specific hierarchical structure:
- Preprocessor Directive:
#include <iostream> - Namespace Declaration:
using namespace std; - Main Function Header:
int main() - Function Body: Enclosed in braces
{ }containing:- Declaration statements
- Executable statements
Example Program Structure (Addition):
#include <iostream>
using namespace std;
int main(void) {
int x, y, total;
x = 10;
y = 20;
total = x + y;
cout << "Total:" << total;
return 0;
}
Preprocessor Directives and Header Files
C++ utilizes a collection of library files that contain pre-written code for common tasks.
- Header Files: Every library file has a unique name and is referred to as a "header file."
- Syntax for Inclusion:
#include <header file name> - The #include Directive:
- Usually placed at the very top of the program.
- Function: Inserts the literal contents of the specified header file into the program.
- Example:
#include <iostream>makes input/output functions likecinandcoutavailable for use. - Critical Constraint: Never place a semicolon
at the end of an#includeline.
Namespaces and Scope
To manage identifiers and avoid naming conflicts, C++ uses namespaces.
- Namespace std:
cinandcoutare declared within theiostreamheader, but they reside within a specific declarative region callednamespace std(standard). - Usage: To use these standard functions easily, the statement
using namespace std;provides a scope that allows the program to recognize them.
The Use of Comments in C++
Comments are essential for documenting code to help readers understand the logic. There are two primary types:
- Block Comments: Used for multi-line documentation. Enclosed between
/*and*/tokens.- Example Style 1:
cpp /* This is a block comment that covers two lines. */ - Example Style 2 (Common standard): Placing opening and closing tokens on their own lines, sometimes with asterisks at the start of each line to mark the comment clearly.
- Example Style 1:
- Line Comments: Used for single-line notes. Begins with
//and terminates at the end of the line.- Full line example:
// This is a whole line comment. - Partial line example:
a = 5; // This is a partial line comment.
- Full line example:
Identifiers: Naming Program Elements
An identifier is a name defined by the programmer for elements such as variables and functions.
Rules for Valid Identifiers:
- Must consist only of alphabets, digits, or underscores
_. - The first character must be an alphabet or an underscore.
- Identifiers cannot be identical to C++ keywords or reserved words.
- Must consist only of alphabets, digits, or underscores
C++ Keywords: These are reserved words with predefined meanings and must be written in lowercase. They cannot be repurposed as identifiers.
Valid vs. Invalid Identifiers Table:
| Identifier | Valid? | Reason if Invalid |
|---|---|---|
totalSales | Yes | N/A |
total_Sales | Yes | N/A |
total.Sales | No | Cannot contain a period |
4thQtrSales | No | Cannot begin with a digit |
totalSale$ | No | Illegal symbol `` |\n\n* **Best Practices:** Use meaningful and descriptive names. For a future value investment variable:\n * `f` or `fv` (Too short/vague)\n * `future_value_of_an_investment` (Too long)\n * `future_value` (Appropriate/Recommended)\n\n# Data Types and Memory Representation\n\nA data type defines a set of values and the set of operations applicable to those values.\n\n**Common C++ Data Types:**\n\n* **char:** Stores a single character. Values are enclosed in single quotes. Example: `'A'`, `'8'`, `'?'`.\n* **int:** Stores integer numbers. Example: 0123-456.\n* **bool:** Contains `true` or `false`. In memory, `1` represents `true` and `0` represents `false`.\n* **float:** Stores floating-point (decimal) numbers. Example: 12.34.\n* **double:** Stores double-precision floating-point numbers for higher accuracy. Example: 3.1415926535898.\n\n# Variables: Declaration, Assignment, and Initialization\n\n* **Declaration:** Identifying the data type and the name (identifier). This allocates a memory location.\n * Example: `int year;` creates a location for `year`.\n* **Assignment:** The process of storing a specific value into the declared memory location.\n * Example: `year = 2008;`\n * *Warning:* Ensure the value matches the declared type. A type mismatch can lead to errors.\n* **Initialization:** Assigning a value to a variable at the exact moment it is created.\n * Example: `float price = 25.99;`\n * *Warning:* Uninitialized variables contain "garbage values" (meaningless data). It is best practice to always initialize variables before use.\n\n# String Data Types\n\nA string is a sequence of characters. It can be implemented in two ways:\n\n* **C-String:** An array of characters.\n * Syntax: `char name[21];` (Indicates 20 characters plus one terminating null character `\0`).\n * Input: `cin >> name;` (Reads a single word) or `cin.getline(name, 21);` (Reads multiple words/entire line).\n* **String Class:** Requires the `#include |