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 like cin and cout available for use.
    • Critical Constraint: Never place a semicolon ;; at the end of an #include line.

Namespaces and Scope

To manage identifiers and avoid naming conflicts, C++ uses namespaces.

  • Namespace std: cin and cout are declared within the iostream header, but they reside within a specific declarative region called namespace 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. */ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    • 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.
  • 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.

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.
  • 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:

IdentifierValid?Reason if Invalid
totalSalesYesN/A
total_SalesYesN/A
total.SalesNoCannot contain a period ..
4thQtrSalesNoCannot begin with a digit 44
totalSale$NoIllegal 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: 0,,123,,-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 ` library and `using namespace std;`.\n * Syntax: `string day = "Tuesday";`\n * Input: `cin >> name;` (Only reads one word) or `getline(cin, mood);` (Reads the entire line including multiple words).\n\n# Scope and Memory Allocation\n\n* **Scope:** The specific part of the program where a variable is accessible. A variable cannot be used before it has been declared.\n* **Variable:** A memory location whose content **can** be changed during execution.\n* **Named Constant:** A memory location whose content **cannot** be changed during execution.\n\n# Types of Constants\n\n* **Named Constant:** Defined using the `const` reserved word.\n * Syntax: `const = value;` \n * Rule: Must be initialized during declaration; it is read-only.\n * Example: `const double PI = 3.14159;`\n* **Defined Constant:** Created using the `#define` preprocessor command.\n * Logic: Replaces the name in the program body with the associated expression before compilation.\n * Example: `#define GRAMS_PER_KG 1000`\n\n# Program Statements\n\nA statement causes the computer to perform an action. They are categorized as:\n\n* **Expression Statements:** Consist of an expression followed by a semicolon.\n * Example: `a = b + c;`\n* **Compound Statements:** Consist of multiple individual statements enclosed in braces `{ }`.\n * Example: \n ```cpp\n { \n pi = 3.141593; \n area = pi * radius * radius; \n }\n        ```\n* **Control Statements:** Used for logical tests, loops, and branching.\n * Example: `while (count