Introduction to Computing, C++ Program Execution, and Core Syntax

Academic Course Architecture and Assessment Schedule

The computing curriculum in Introduction to Computing and Programming (Course Code C-CS111) establishes a systematic evaluation schedule distributed across the academic semester. The assessment milestones are organized chronologically to evaluate theoretical understanding and practical programming proficiencies.

The course quiz structure includes five dedicated evaluation checkpoints. Week 66 administers a Lecture Quiz targeting theoretical concepts and language architecture. Week 77 features a practical Lab Quiz focusing on hands-on code writing and implementation. Week 1111 administers a second Lab Quiz testing cumulative programming development. Week 1212 presents a second theoretical Lecture Quiz evaluating syntactic and semantic concepts. Finally, Week 1313 concludes the quiz series with a final Lab Quiz focused on comprehensive program structure and debugging.

Hardware Architecture and the Program Execution Cycle

A computer program consists of an ordered sequence of stored instructions that direct the central processing unit to execute specific computational tasks. A program cannot be executed directly from secondary storage devices such as mechanical hard disks or solid-state media. Prior to execution, the operating system copies the target program code from secondary storage into main memory, commonly referred to as Random Access Memory (RAM). The Central Processing Unit (CPU) subsequently accesses and executes these instructions exclusively from RAM.

Program instructions copied from secondary storage to RAM and executed by the CPU

The Central Processing Unit is fundamentally engineered to perform basic atomic operations on discrete pieces of data. These baseline primitives include reading data from memory locations, performing arithmetic computations such as addition, subtraction, multiplication, and division, and transferring processed values back to storage. Because individual hardware operations are elementary, meaningful computing requires the execution of vast sequences containing thousands or millions of sequential instructions. The CPU interprets exclusively those instructions formulated in its native machine language, defined by the hardware architecture's specific instruction set. Distinct microprocessor families utilize entirely distinct instruction sets.

The three-step CPU instruction cycle: Fetch, Decode, and Execute

Program execution inside the CPU follows an infinite repetitive sequence known as the instruction cycle or the Fetch-Decode-Execute cycle. During the Fetch phase, the CPU retrieves the subsequent instruction in the program sequence from main memory into internal registers. During the Decode phase, the internal control circuitry inspects the fetched binary instruction to evaluate the required operation and identify the operands involved. During the Execute phase, the CPU activates the appropriate arithmetic logic circuitry or data bus channels to carry out the specified operation. Upon completion, the cycle immediately resumes with the fetch phase of the succeeding instruction.

Hierarchy of Programming Languages and Translation Paradigms

A programming language provides a structured linguistic mechanism enabling human software developers to write instructions executable by a computer. Programming languages occupy a hierarchy defined by their abstraction distance from the underlying physical hardware, categorized into low-level languages and high-level languages.

Low-level languages are closely bound to the physical hardware and processor architecture. Machine language represents the lowest layer, consisting strictly of binary patterns of 11s and 00s that hardware gates process directly. Writing raw binary code is profoundly inefficient and error-prone for humans. Assembly language resolves this limitation by substituting cryptic binary bit strings with short mnemonic words for instructions, such as using mov to transfer values or add to perform addition. Because a CPU cannot execute assembly mnemonics directly, a dedicated translation tool called an assembler converts assembly language source programs into machine language binaries for hardware execution.

Assembly language program converted by an assembler into machine language

High-level programming languages, including C++, Python, and Java, abstract developers away from hardware complexity. Programmers do not need detailed knowledge of CPU register configurations or specific microprocessor instruction sets to author software. High-level languages utilize human-readable syntax that allows complex logic to be expressed concisely. Because microprocessors cannot execute high-level instructions natively, intermediate translation programs are required to convert source text into hardware-compatible machine code.

Translators are bifurcated into two primary paradigms: compilers and interpreters. A compiler is a specialized translation program that processes an entire high-level source code file in its entirety, translating the code into a standalone machine language file known as an object or executable program. Once compiled, this generated machine code program can be executed independently at any time without the compiler present. Compilers are utilized by languages such as C++. Programs processed by compilers generally exhibit superior execution speeds.

High-level source code compiled into a machine code program and run on the CPU

An interpreter translates and executes instructions sequentially, one statement at a time, without generating a separate machine language binary file. The interpreter must remain active in memory to parse and execute statements concurrently. Interpreters support interactive modes, where typed statements run immediately upon entry. Python is an example of an interpreted language.

An interpreter translating and executing source statements directly on hardware

Language Theory: Syntax, Semantics, and Error Classification

All human natural languages, such as English and Arabic, and artificial programming languages are governed by formal linguistic rules comprising syntax and semantics. A fully functional program requires strict compliance with both syntactic structure and semantic logic.

Syntax denotes the strict grammatical framework and formal structural rules dictating the arrangement of characters, keywords, and punctuation symbols. Syntax defines whether an expression is written correctly. In human language, the phrase "Hello there, hao are you?" contains a spelling and syntactic breakdown. In programming, any violation of character order or keyword structure causes a syntax error that halts translation immediately.

Semantics denotes the underlying meaning, conceptual logic, and functional intent of syntactically valid constructs. Code may follow perfect structural syntax while being entirely nonsensical. This is exemplified in theoretical linguistics by Noam Chomsky's sentence: "Colorless green ideas sleep furiously." The sentence follows grammatical English syntax, yet it is semantically meaningless. In software development, semantic errors produce incorrect outputs despite clean syntactic compilation.

Software defects are divided into three distinct classes: syntax errors, run-time errors, and logic errors. Syntax errors constitute direct violations of language grammar rules, detected during translation by the compiler or interpreter. A compiler refuses to produce an executable program if syntax errors exist. Run-time errors occur while the program is actively executing, triggered when the hardware or runtime environment encounters an impossible operation, such as division by zero or invalid memory access. Logic errors occur when flaws exist in the underlying algorithm. The computer executes all instructions without interruption, but the program yields incorrect computational results. Logic errors are the most difficult defects to diagnose because development tools cannot flag them automatically.

Program Debugging and the Historical Genesis of the Computer Bug

Program debugging is the analytical process of isolating, diagnosing, and correcting errors or bugs within a software system. Because computing hardware lacks cognitive reasoning, machines execute instructions strictly as written, without evaluating developer intent. Consequently, programmers must actively track data flows to eliminate flaws.

Harvard Mark II logbook entry from September 9, 1947, displaying the first actual computer bug

The formal adoption of the terms "bug" and "debugging" stems from an incident in the 1940s. On September 9, 1947, operators and engineers working on the electromechanical Mark II Aiken Relay Calculator at Harvard University encountered an unexpected hardware failure. Upon inspecting the system's internal hardware, the team discovered a physical moth trapped inside Relay #70 of Panel F, which physically blocked the circuit connection. The technicians carefully removed the moth, adhered it onto their official engineering logbook page with adhesive tape, and inscribed the historical note: "First actual case of bug being found." That original logbook, along with the preserved insect specimen, remains permanently archived and exhibited at the Smithsonian Institution in Washington, D.C.

The C++ Development Toolchain and Build Architecture

The C++ programming language was created by Bjarne Stroustrup as an enhancement to the C language. The moniker incorporates the ++ increment operator, which increments a numerical variable by 11. This naming represents a pun signifying that C++ is the evolutionary successor to C.

Professional C++ software construction relies on an Integrated Development Environment (IDE), which bundles development utilities into a unified graphical interface. A standard IDE integrates three foundational tools: an interactive text editor for composing and revising source code, a language translator (preprocessor, compiler, and linker) for building executables, and an interactive debugger to inspect execution states and variable memory addresses. Standard industry C and C++ IDEs include Microsoft Visual Studio, Eclipse, and Code::Blocks.

The complete software build workflow follows three successive phases. First, a programmer writes C++ source statements and saves them to disk as a source text file with the .cpp extension. Second, a preprocessor parses lines starting with # directives, followed by the compiler converting the preprocessed source text into low-level machine instructions known as object code, creating an .obj file. Third, a utility called a linker combines the generated object code with pre-compiled runtime libraries and system functions to produce the final binary executable file, typically having an .exe extension on Windows systems.

Structural Components of C++ Source Code

Every functional program consists of five primary components: statements, keywords, operators, punctuation separators, and comments. A statement represents a complete operational command instructing the computer to perform an action. Statements in C++ end with a semicolon ;, which serves as the statement terminator.

Keywords, also called reserved words, are predefined lexical tokens reserved by the C++ language specification. Each keyword holds an immutable syntactic meaning and cannot be repurposed as a variable name or identifier. Operators are specialized symbols that perform operational manipulations on variables and literals, including arithmetic operations (+, -, *, /) and stream interactions. Punctuations, or separators, organize syntax groupings; examples include commas to separate parameter lists and semicolons to terminate expressions.

Comments provide explanatory prose placed within source files to document technical algorithms for human maintainers. Translators discard all comments during compilation. In C++, single-line comments begin with a double slash // and extend to the end of that specific line. Alternatively, an end-line comment is positioned directly after executable code on the same line to clarify that statement's purpose. Multi-line comments begin with the delimiter /* and conclude with */, allowing explanatory text to span multiple successive lines without requiring prefixes on intermediate rows.

#include <iostream>
using namespace std;

/* Program that takes two numbers
   and display largest */
int main()
{
    int num1, num2;
    cout << "Welcome!" << endl;
    cout << "Please enter a number:" << endl;
    cin >> num1;
    cout << "Let's add another number.." << endl;
    cout << "Please enter a number:" << endl;
    cin >> num2;

    if (num1 > num2) {
        // Check if first number is larger
        cout << "First number is largest" << endl;
    }
    else {
        cout << "Second number is largest" << endl;
    }

    return 0;
}

The fundamental structure of every standard C++ application centers around the main function. The function declaration begins with the return type int, signifying that the function yields an integer whole number back to the host operating system upon termination. The identifier main is followed by opening and closing parentheses (), which designate main as a function block. Program execution begins at the first opening brace { of main and exits through the return 0; statement, where returning 00 signals to the operating system that execution succeeded without error. The program terminates when it hits the closing right brace }.

Compilers treat spaces, tab stops, and newline carriage returns collectively as whitespace. Aside from string literals, the compiler ignores whitespace variations. To maintain source code readability, standard style conventions dictate placing opening and closing braces on isolated lines, applying tab indentations within function blocks, placing a single statement per line, and ending every statement with a semicolon.

CharacterFormal NameMeaning and Syntactic Utility
//Double slashMarks the beginning of a single-line comment
#Pound signMarks the beginning of a preprocessor directive
< >Open/close bracketsEnclose library header filenames inside #include directives
( )Open/close parenthesesUsed when naming functions and enclosing parameter lists
{ }Open/close bracesEnclose a grouped block of executable programming statements
" "Open/close quotation marksEnclose literal character strings
;SemicolonActs as a statement terminator at the end of a programming statement

Language Keywords and Identifier Nomenclature Constraints

The C++ language reserves a distinct catalog of keywords. These reserved words cannot be used as programmer-defined identifiers:

auto       do         goto       signed     unsigned
break      double     if         sizeof     void
case       else       int        static     volatile
char       enum       long       struct     while
const      extern     register   switch
continue   float      return     typedef
default    for        short      union

Variables represent designated memory locations that store modifiable runtime data values. While the developer can read or overwrite the contents stored within a variable, the underlying hardware memory address cannot be removed. Prior to initialization, memory cells contain residual bit configurations, known as garbage values. Variable names are formally designated as identifiers.

Identifier construction must adhere to strict lexical rules. An identifier may consist exclusively of alphabetical letters (uppercase and lowercase), numerical digits, and underscore characters _. An identifier cannot start with a numerical digit. Identifiers cannot contain spaces, periods, or non-alphanumeric symbols such as $. Identifiers cannot match any C++ reserved keyword. In addition, C++ is case sensitive; therefore, the identifier a1 and the identifier A1 reference two separate memory locations.

Identifier NameValidity StatusDiagnostic Reason if Invalid
totalSalesValidComplies with all alphanumeric identifier rules
total_SalesValidCorrectly utilizes the underscore character separator
total.SalesInvalidIllegal character: cannot contain a period (.)
4thQtrSalesInvalidIllegal prefix: cannot begin with a numeric digit (4)
totalSale$InvalidIllegal character: cannot contain a dollar symbol ($)

Variable Declarations, Data Types, and Memory Allocations

Every variable must be formally declared before it can be utilized in code. Declaring a variable instructs the compiler to allocate the appropriate quantity of memory and determine how the binary bits at that location should be interpreted. Variables sharing a data type can be declared sequentially on separate lines or grouped together on a single line separated by commas. Variables belonging to disparate data types require separate declaration statements. Declarations can be situated at the beginning of a function scope or placed immediately prior to their first active point of usage.

Numeric data types handle integer and floating-point computations. The exact quantity of memory allocated for specific primitives varies across underlying computer architectures and compiler implementations. The built-in compile-time operator sizeof evaluates the memory allocation of any datatype or variable expression in bytes, such as evaluating sizeof(int).

Data TypeTypical SizeTypical Value Range
short (or short int)2 bytes2\text{ bytes}−32,768-32,768 to 32,76732,767
unsigned short int2 bytes2\text{ bytes}00 to +65,535+65,535
int4 bytes4\text{ bytes}−2,147,483,648-2,147,483,648 to 2,147,483,6472,147,483,647
unsigned int4 bytes4\text{ bytes}00 to 4,294,967,2954,294,967,295
long (or long int)4 bytes4\text{ bytes}−2,147,483,648-2,147,483,648 to 2,147,483,6472,147,483,647
unsigned long int4 bytes4\text{ bytes}00 to 4,294,967,2954,294,967,295
long long int8 bytes8\text{ bytes}−9,223,372,036,854,775,808-9,223,372,036,854,775,808 to 9,223,372,036,854,775,8079,223,372,036,854,775,807
unsigned long long int8 bytes8\text{ bytes}00 to 18,446,744,073,709,551,61518,446,744,073,709,551,615

Beyond integer primitives, C++ provides double and float data types to store numbers that have fractional components, such as 1.341.34, 4.04.0, and −345.6-345.6.

The char data type stores single alphanumeric characters or small integer quantities, occupying 1 byte1\text{ byte} of storage. Instead of storing visual glyphs directly, memory cells store the corresponding integer character code defined by the character set. For example, executing letter = 'C'; maps the ASCII value 6767 into the variable's allocated memory byte.

The bool data type stores logical conditions representing boolean states. A boolean variable occupies a small integer memory representation where the state false evaluates to integer 00, and true evaluates to integer 11.

Literals, Assignment Statements, and Variable Initialization

A literal represents an explicit, unchanging value written directly into source code. In the statement apples = 20;, the token 20 constitutes an integer literal. In contrast, string literals comprise an arbitrary sequence of characters enclosed within double quotation marks, such as "Today we sold ".

An assignment statement modifies the contents of an allocated variable using the binary assignment operator =. The variable designated to receive the new value must be placed on the left side of the operator. The right-hand operand may consist of an explicit constant literal (such as age = 21;), another variable (such as my_cost = your_cost;), or an arithmetic expression (such as circumference = diameter * 3.14159;).

Variable initialization combines declaration with value assignment in a single statement. Declaring a variable without assigning a value leaves it with unpredictable garbage memory contents. C++ supports two distinct syntactical initialization styles: assignment initialization using the assignment operator (for example, double mpg = 26.3, area = 0.0, volume;) and constructor initialization using parentheses (for example, double mpg(26.3), area(0.0), volume;).

Stream Input and Output Operations via iostream

A data stream models the transmission of sequential data elements, typically expressed as sequences of characters or numbers. An input stream directs incoming data from sources such as a hardware keyboard or a storage file into the program. An output stream transports processed information from the program outward to display monitors or files.

Standard terminal communication is supported by the preprocessor include directive #include <iostream>. The iostream library defines the standard input stream object cin and the standard output stream object cout. The declaration using namespace std; informs the compiler that entities within the standard runtime libraries reside in the std namespace. This eliminates the requirement to prepend the scope resolution operator to standard library names, allowing developers to write cout and cin directly instead of writing std::cout and std::cin.

The cin object represents the standard input stream reading keyboard input, using the extraction operator >>. When extracting data, values are held in an input buffer until the user presses the Enter key, allowing corrections via the backspace key before input transmission occurs. Multiple data items entered into a single stream must be separated by spaces, tabs, or newlines. Sequential extractions can be chained together across variables, such as cin >> v1 >> v2 >> v3;.

The cout object directs character sequences to the standard terminal display using the stream insertion operator <<. Output sequences can be chained together within a single statement using multiple insertion operators, as shown in cout << "Hello " << "there!";.

// Line breaks using the endl stream manipulator
cout << "Hello " << endl;
cout << "there!";

// Line breaks using the 
 escape sequence
cout << "Hello
";
cout << "there!";

Line breaks can be emitted via two distinct mechanisms: the endl stream manipulator and the escape character sequence. The endl manipulator is written without quotation marks and ends with a lowercase letter l rather than the numeral 1. When passed to cout, endl inserts a newline character and flushes the buffer. Alternatively, the escape character can be embedded inside a double-quoted string literal to advance the terminal cursor to the next line.