Comprehensive Study Notes: Computer Science 1 (COMP0100) — Algorithms, Logic Design, and C++ Programming
Course Overview and Administrative Structure
Course Details:
- Course Code & Title: COMP0100-N1 Computer Science 1.
- Instructional Staff: Dr. Michael Hosein, Senior Lecturer.
- Weekly Contact Hours:
- Lecture hours per week.
- Lab hours per week (conducted as a single -hour laboratory session).
- Tutorial hour per week (from scheduled tutorial hours available).
- Delivery Format: Online instructional mode with defined student expectations and timetabling spanning weeks through .
Assessment Breakdown:
- Total Coursework Weighting: of the final course grade.
- Take-Home Assignments: assignments, each weighted at , totaling .
- Practicals: Total weighting of (partitioned into and components).
- Mid-Term Examination: Weighted at .
- Final Examination: Weighted at of the final course grade.
- Total Coursework Weighting: of the final course grade.
Curricular Objectives and Scope:
- Expose students to the fundamental nature of computing by exploring the internal hardware components of a computer.
- Develop competencies in manipulating hardware components via computer programs to accomplish defined computational tasks.
- Cultivate systematic problem-solving methodologies and algorithm design prior to implementation in a high-level programming language.
- Primary topical areas covered: Problem Solving, Programming Foundations, and Computer Architecture/Hardware Components.
Fundamentals of Computer Systems: Architecture, Hardware, and Software
System Components:
- Hardware: The physical, tangible electronic and electromechanical components of a computer system.
- Software: Collections of instructions and programs that direct, command, and coordinate the operation of the hardware equipment.
- Programs ("Apps"): Sequences of instructions written by programmers in a structured, logical manner to execute specific functions.
Three Core Computer Operations:
- Input: The mechanism of ingesting external data into an algorithm or computer program.
- Common data formats include textual representations and numerical values.
- Primary hardware input peripherals include keyboards, mice, and external data files.
- Processing: The transformation, computation, and evaluation of input data.
- Conducted primarily by the Central Processing Unit (CPU).
- Arithmetic Logic Unit (ALU): Performs fundamental arithmetic calculations (, , , ) and relational comparisons (, , ).
- Control Unit (CU): Directs the flow of data, manages instruction execution cycles, and coordinates timing across components.
- Output: The dissemination and presentation of processed information to external recipients or persistent media.
- Common output destinations include display screens (monitors), physical storage files, printers, and cloud storage repositories.
- Input: The mechanism of ingesting external data into an algorithm or computer program.
Programming Languages and Program Syntax:
- Programming Language: A formalized artificial notation designed to encode instructions executable by a computer system.
- Syntax: The precise structural, grammatical, and punctuation rules governing the formulation of valid statements within a specific language.
- Syntax Errors: Violations of grammatical rules (such as missing semicolons, unmatched parentheses, or incorrect keywords) detected by compilers or interpreters prior to execution.
- Integrated Development Environments (IDEs) & Text Editors: Software tools utilized by programmers to draft, edit, organize, compile, and run program code.
The Problem-Solving Framework and Algorithm Development
The Five Canonical Steps of Problem Solving:
- Define the Problem: Clearly identify the overarching task and explicit objectives that need to be accomplished.
- Analyze the Problem: Deconstruct the problem boundary into three foundational aspects: inputs required, mathematical/logical processing steps, and expected outputs.
- Design a Solution (Algorithm): Formulate a step-by-step logical blueprint using structured tools such as pseudocode or flowcharts.
- Code (Implement) the Solution: Translate the designed algorithm into a selected programming language (such as C++).
- Test the Solution and Revise: Execute the program using multiple diverse data sets, search for errors, verify results against anticipated baselines, and iterate back to earlier design/analysis steps if discrepancies arise.
Worked Demonstration — Area of a Square:
Step 1: Define the Problem: Read the numerical value representing the side of a square, calculate its area, and output the result.
Step 2: Analyze the Problem:
- Input(s): Side length of the square (, a non-negative real number).
- Processing: .
- Output(s): Calculated area, displayed with appropriate descriptive labeling.
Step 3: Design Algorithm (Pseudocode):
Print 'Please enter side of square:'Read sidearea = side * sidePrint 'Area is', area
Step 4: Code Implementation (C++): ```cpp
include
using namespace std;
int main() { double side; cout << "Please enter length of side of square: "; cin >> side; cout << "Area is " << side * side << endl; cout << "End of program." << endl; return 0; } ```
Step 5: Test the Solution:
- Test Execution: Input of
- Console Output:
text Please enter length of side of square: 5 Area is 25 End of program.
Error Classification and Program Maintenance:
- Syntax Errors: Mechanical violations of language syntax rules that prevent compilation.
- Logical Errors: Flaws in program reasoning, incorrect sequencing of operations, or mathematical inaccuracies that allow successful compilation but yield incorrect outputs or infinite execution loops. Logical errors are substantially more difficult to identify and rectify than syntax errors.
- Debugging: The rigorous process of isolating, tracing, and resolving known syntax and logical defects within program code.
- Desk-Checking: Manually walking through the logic of an algorithm or program on paper using sample data sets prior to computer implementation.
- Maintenance: The ongoing modification, enhancement, and updating of a software program over its lifecycle to fix newly detected defects or adapt to updated business and system requirements.
Logic Planning Tools: Flowcharts, Pseudocode, and Trace Tables
Logic Planning Artifacts:
- Algorithm: A finite, ordered sequence of unambiguous instructions designed to solve a specific problem.
- Pseudocode: An English-like informal structural notation representing the logical sequence of an algorithm without strict language-specific syntax.
- Flowchart: A standardized graphical diagram that utilizes geometric shapes and directed flowlines to visualize algorithmic logic and control flow.
- IPO Charts: Structured tabular tools specifying Inputs, Processing steps, and Outputs.
- TOE Charts: Tabular organizational tools cataloging Tasks, Objects, and Events.
Standard Flowchart Symbols:
- Terminal (Start/Stop): Oval or rounded rectangle denoting program initiation and termination points.
- Input/Output: Parallelogram representing data ingestion (
Read,cin) or data display (Print,cout). - Process Box: Rectangle indicating computational operations, variable manipulations, or assignments.
- Decision Box: Diamond indicating a conditional evaluation yielding binary outcomes (
Yes/NoorTrue/False), dictating divergent execution pathways. - Flowline (Connector): Directed arrows connecting symbols to explicitly establish sequential execution flow.

- Basic Flowchart Examples:
- Read and Print an Integer ():
- Initiates at
START. - Reads value into variable .
- Outputs value of .
- Terminates at
STOP.
- Initiates at
- Read and Print an Integer ():

* **Pension Eligibility Verification:**
* A jurisdiction provides state pensions to citizens aged years and older.
* `START` `READ AGE` Decision:
* Branch `Yes`: Execute `PRINT "QUALIFIED"` Proceed to `STOP`.
* Branch `No`: Execute `PRINT "NOT QUALIFIED"` Proceed to `STOP`.

- Tracing Algorithmic Operations:
- Trace Demonstration 1: Number Tripling Pseudocode
text start read num ans = num * 3 print ans stop
- Trace Demonstration 1: Number Tripling Pseudocode
- Trace Demonstration 2: Sequential Variable Mutation
text x = 5 y = 10 x = x + y y = x / 3 z = y * y Print x, y, z - initially becomes .
- initially becomes .
- becomes .
- becomes .
- becomes .
- Values printed to console:
15 5 25.
Structured Programming Control Constructs
Structured Programming Foundations:
- Structured programming dictates that any computational algorithm can be expressed through three fundamental control structures: Sequence, Selection, and Iteration.
1. Sequence:
- Instructions execute strictly in linear, sequential order, one after the other, in the exact physical order of presentation.
- Example:
text Read A Read B - Parallel Computing Note: While conventional architectures execute sequential instructions serially, advanced computer science paradigms leverage parallel hardware architectures capable of executing independent instructions simultaneously.
2. Selection (Conditional Branching):
- Directs execution to choose among alternate execution pathways depending on whether a specified logical expression evaluates to
trueorfalse. - Example:
text if x = 0 then print "TEST" stop
- Directs execution to choose among alternate execution pathways depending on whether a specified logical expression evaluates to
3. Iteration (Repetition / Looping):
- Repeats the execution of a distinct block of instructions multiple times while a specified logical condition remains true.
- Example:
text repeat print "TEST" 5 times - Produces the output:
TEST TEST TEST TEST TEST.
- Produces the output:
Algorithmic Input and Output Conventions:
- Input Operations: Designated by keywords such as
Read,Input,Get,Accept.- Accepting multiple variables:
Read A, B, Cis logically equivalent to individual statements (Read A,Read B,Read C), offering programmatic conciseness. - User Prompts: Textual cues displayed on-screen prior to requesting input. Prompts prevent user confusion caused by unprompted blank input screens (e.g., displaying
"Please enter an integer: "beforeRead x).
- Accepting multiple variables:
- Output Operations: Designated by keywords such as
Print,Write,Output,Display.- Distinction between literals and variables:
Print 'a'outputs the character literala, whereasPrint aoutputs the current numerical/character value stored in variablea. - Composed output statements:
Print 'a is ', a, ' and b is ', boutputs structured strings containing dynamic memory contents (e.g.,a is 10 and b is 20).
- Distinction between literals and variables:
- Input Operations: Designated by keywords such as
Operators and Expressions: Arithmetic, Relational, and Logical
Assignment Operator (,
:=):- Signifies "becomes" or "takes the value of". Assigns the evaluated result of the right-hand operand into the memory storage location referenced on the left.
- Example:
a = 1sets to .a = breplaces the value in with the current value in .
Arithmetic Operators:
- Addition (, C++:
+), Subtraction (, C++:-), Multiplication (, Pseudocode/C++:*), Division (, Pseudocode/C++:/). - Modulus Operator (
mod,%): Computes the integer remainder resulting from division between two operands.- Formal syntax:
- Properties: The divisor cannot equal .
- Calculated Examples:
- (since , remainder is ).
- Precedence Hierarchy: Follows standard algebraic rules: Parentheses/brackets take precedence, followed by multiplication, division, and modulus, followed by addition and subtraction.
- Addition (, C++:
Relational Operators:
- Perform comparisons between operands and yield a Boolean evaluation (
trueorfalse). - Pseudocode vs. C++ Relational Operators:
- Equal to: Pseudocode
=, C++== - Not equal to: Pseudocode
<>, C++!= - Greater than:
> - Less than:
< - Greater than or equal to:
>=(no intervening whitespace allowed) - Less than or equal to:
<=(no intervening whitespace allowed)
- Equal to: Pseudocode
- Perform comparisons between operands and yield a Boolean evaluation (
Logical Operators and Truth Tables:
- Combine or invert Boolean propositions.
- Conjunction (
AND, C++:&&): Yieldstrueif and only if both operands evaluate totrue. - Disjunction (
OR, C++:||): Yieldstrueif at least one operand evaluates totrue. - Negation (
NOT, C++:!): Inverts the truth value of the operand.
Truth Tables for Logical Operations:
| Operand | Operand | Conjunction ( / AND) | Disjunction ( / OR) |
|---|---|---|---|
| F | F | F | F |
| F | T | F | T |
| T | F | F | T |
| T | T | T | T |
| Operand | Negation ( / NOT X) |
|---|---|
| F | T |
| T | F |
Selection Structures and Conditional Branching in C++
Syntactic Structures for Selection:
- Simple
ifStatement:cpp if (condition) { // statements to run if condition is true }
- Simple
Two-Way
if...elseStatement:cpp if (condition) { // true branch } else { // false branch } Multi-Way
if...else if...elseChain:cpp if (condition1) { // runs if condition1 is true } else if (condition2) { // runs if condition2 is true } else { // default branch if all previous conditions are false } - Syntactic Safety Rule: Always enclose both the
ifandelsestatement bodies in curly braces{}. Although single-statement branches compile without braces, omitting them leads to dangling-else bugs and maintenance errors.
- Syntactic Safety Rule: Always enclose both the
Common Programmer Error: Assignment vs. Equality:
==is the relational operator used to perform equality comparisons.=is the assignment operator used to store values into memory.- Error Analysis: Writing
if (x = 5)assigns the value to variable . In C++, non-zero integers evaluate totrue, causing the conditional branch to execute unconditionally regardless of 's previous value. The correct logical test isif (x == 5).
Comprehensive Code Demonstrations Across Primitive Data Types:
Integer Comparison (Pass/Fail Verification): ```cpp
include
using namespace std;
int main() { int mark = 72; if (mark >= 50) { cout << "Pass" << endl; } else { cout << "Fail" << endl; } return 0; } ```
Result: Outputs
Passbecause evaluates totrue.
Multi-Branch Integer Evaluation (Sign Determination): ```cpp #include
using namespace std; int main() { int number = -8; if (number > 0) { cout << "Positive" << endl; } else if (number < 0) { cout << "Negative" << endl; } else { cout << "Zero" << endl; } return 0; }```
- Result: Outputs
Negative.
- Result: Outputs
Compound
elseBlock (Calculating Deficit Points): ```cpp #includeusing namespace std; int main() { int mark; cout << "Please enter integer mark: "; cin >> mark; if (mark >= 50) { cout << "PASS" << endl; } else { cout << "FAIL" << endl; cout << "Missed pass by " << 50 - mark << endl; } return 0; }```
Character Equality and Case Handling: ```cpp #include
using namespace std; int main() { char answer = 'y'; if (answer == 'y' || answer == 'Y') { cout << "Continue" << endl; } else { cout << "Stop" << endl; } return 0; }```
Direct Evaluation of Boolean Variables: ```cpp #include
using namespace std; int main() { bool hasPaid = true; if (hasPaid) { cout << "Receipt printed" << endl; } else { cout << "Payment required" << endl; } return 0; }```
Floating-Point Numeric Comparisons: ```cpp #include
using namespace std; int main() { float temperature = 37.8; if (temperature > 37.5) { cout << "High temperature" << endl; } else { cout << "Normal temperature" << endl; } return 0; }```
Relational Logic with Float Balance and Withdrawal: ```cpp #include
using namespace std; int main() { float balance = 125.50; float withdrawal = 200.00; if (withdrawal <= balance) { cout << "Approved" << endl; } else { cout << "Insufficient funds" << endl; } return 0; }```
Compound Conjunction (
&&) and Range Verification: ```cpp #includeusing namespace std; int main() { int age = 18; bool hasID = true; if (age >= 18 && hasID) { cout << "Allowed" << endl; } else { cout << "Not allowed" << endl; } return 0; }```
Range Testing: ```cpp #include
using namespace std; int main() { float average = 84.5; if (average >= 80.0 && average <= 100.0) { cout << "Grade A range" << endl; } else { cout << "Not Grade A range" << endl; } return 0; }```
Nested
ifSelection Logic: ```cpp #includeusing namespace std; int main() { int mark = 68; if (mark >= 50) { cout << "Pass" << endl; if (mark >= 65) { cout << "Good pass" << endl; } } else { cout << "Fail" << endl; } return 0; }```
Result: Evaluates outer condition (:
true), printsPass; evaluates inner condition (:true), printsGood pass.
Character Data Handling and ASCII Architecture
- Character Representation Principles:
- A
charrepresents a single entity enclosed strictly within single quotation marks (e.g.,'1','A','a','$'). - Every character maps to an underlying numeric encoding defined by the American Standard Code for Information Interchange (ASCII).
- A

Key ASCII Values and Relational Offsets:
- Space character (
' '): Decimal value , Hexadecimal , Octal . - Uppercase
'A': Decimal value , Hexadecimal , Octal . - Uppercase
'B': Decimal value , Hexadecimal , Octal . - Lowercase
'a': Decimal value , Hexadecimal , Octal . - Lowercase
'b': Decimal value , Hexadecimal , Octal . - Case Conversion Mathematical Offset:
- Adding a space (
' ', decimal ) to an uppercase letter yields its lowercase counterpart: - Subtracting a space (
' ', decimal ) from a lowercase letter converts it to uppercase:
- Adding a space (
- Space character (
Character Inspection and Conversion Functions: ```cpp // Verifies whether character argument is a lowercase vowel bool isVowel(char ch) { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return true; else return false; }
// Verifies whether character falls within lowercase alphabetic range bool isLower(char ch) { return (ch >= 'a' && ch <= 'z'); }
// Verifies whether character falls within uppercase alphabetic range bool isUpper(char ch) { return (ch >= 'A' && ch <= 'Z'); }
// Verifies whether character is an alphabetic letter bool isLetter(char ch) { return ((ch >= 'a' && ch
// Converts lowercase character to uppercase via ASCII arithmetic char toUpper(char ch) { return ch - ' '; } ```
Character File Stream Analysis:
Specification: Ingest single characters separated by spaces from an input file (
input8.txt). The sequence terminates upon encountering the sentinel character'$'. Identify the alphabetically highest uppercase character and report the total character count.C++ File Parsing Implementation: ```cpp
include
include
include
using namespace std;
bool isUpper(char ch) { return (ch >= 'A' && ch <= 'Z'); }
int main() { ifstream infile; infile.open("input8.txt"); if (infile.is_open()) { cout << "File opened." << endl; } else { cout << endl << "Unable to open file"; system("PAUSE"); exit(1); }
int count = 0; char letter; infile >> letter; // Priming read char highLett = letter; while (letter != '$') { if (isUpper(letter) && letter > highLett) { highLett = letter; } count += 1; infile >> letter; // Subsequent read } cout << "Largest letter is " << highLett << endl; cout << "Char count is " << count << endl; infile.close(); return 0;} ```
Iteration Structures and Repetition Logic (While Loops)
Advantages of Algorithmic Looping:
- Enhances computational efficiency by executing a single instruction set against multiple distinct data inputs.
- Reduces design overhead, program source lines, and manual coding time.
- Decreases syntax and logical defect probability.
- Optimizes compilation time and runtime operational performance.
Structural Mechanics of a Loop:
- A loop executes its body repeatedly while a tested Boolean condition remains
true. - When the evaluated condition becomes
false, execution terminates and flow diverts past the loop boundary.
- A loop executes its body repeatedly while a tested Boolean condition remains

- Pseudocode Conventions for
whileLoops:- Standard format:
text while condition statements that execute when condition is true endwhile - Indentation visually identifies statements bound inside the loop structure.
- Standard format:

The Three Invariant Rules for Loop Control Variables (LCV):
- Initialize: The LCV must receive an initial starting value before entry into the loop structure.
- Test: The LCV must be tested in a Boolean condition prior to executing the loop body.
- Alter: The LCV must be modified within the loop body to eventually falsify the condition and prevent infinite execution.
Loop Classification: Definite vs. Indefinite Loops:
- Definite (Counter-Controlled) Loop: Executes a predetermined, fixed number of iterations tracked by an integer counter variable.
- The counter typically initializes to or .
- The variable alters via incrementing (
count = count + 1,count += 1,count++) or decrementing (count = count - 1,count -= 1,count--).
- Definite (Counter-Controlled) Loop: Executes a predetermined, fixed number of iterations tracked by an integer counter variable.

* **Indefinite (Sentinel-Controlled) Loop:** Executes when the total volume of input data is unknown prior to execution. Termination relies on reading a distinct, reserved flag value known as a **sentinel value**.
The Priming Read Technique:
- A priming read is an input operation executed immediately before entering the loop structure to provide the initial value for the sentinel evaluation.
- To sustain correct processing, a subsequent read operation must execute as the final statement within the loop body.
- Architectural Necessity: Without a priming read, the loop control variable holds uninitialized garbage data upon initial evaluation. Without a subsequent read inside the body, the loop cannot ingest subsequent data and enters an infinite loop.
Tracing Definite Counter Loops:
- Trace 1: Decrementing Loop
text counter = 4 while counter >= 1 do print counter counter = counter - 1 endwhile - Iterative states of
counter: - Console output:
4 3 2 1(Loop exits whencounterreaches ).
- Trace 1: Decrementing Loop
Trace 2: Stepping Offset Loop
text counter = 0 while counter <= 8 do print counter + 2 counter = counter + 3 endwhile
| Iteration | counter at Evaluation | Printed Expression (counter + 2) | counter post-update (+ 3) |
|---|---|---|---|
| Init | — | — | |
| 1 | (True) | ||
| 2 | (True) | ||
| 3 | (True) | ||
| Exit | (False) | Loop Terminated |
- Tracing Sentinel-Controlled Accumulation Loops:
- Trace 1: Summing Numbers Terminated by
- Input Sequence:
100 200 300 -1
- Input Sequence:
- Trace 1: Summing Numbers Terminated by
| Ingested Input | Stored in num | Accumulated sum () | Console Output |
|---|---|---|---|
| Initialization | — | — | |
100 | — | ||
200 | — | ||
300 | — | ||
-1 | Exit while condition (num != -1) | Sum is 600 |
Accumulator Variable Pitfalls:
- Uninitialized Accumulator: Failing to initialize
sum = 0causes the program to add inputs to undefined garbage memory, corrupting calculations. - Misplaced Accumulator Initialization: Placing
sum = 0inside the loop body resets the accumulator on every iteration, leavingsumcontaining only the final input value rather than the running total. - Efficiency Considerations: In a counter loop accumulating values from to , initialize the counter to rather than , since adding executes a redundant computational cycle.
- Uninitialized Accumulator: Failing to initialize
Comprehensive Sentinel Problem: Employee Payroll Algorithm:
- Problem Statement: Ingest an unspecified number of employee records containing Employee ID, hours worked, and hourly pay rate. The input stream terminates when Employee ID is . Calculate and output each individual employee's wage and the aggregate total wages paid.
- Pseudocode:
text start declarations int id float hours, rate, wage, totalWages = 0 Read id // priming read while id <> -1 do Read hours, rate wage = hours * rate Print ("Wage for worker ", id, ' is ', wage) totalWages = totalWages + wage Read id // subsequent read endwhile Print ("Total wages = ", totalWages) stop
Trace Table: Given input dataset:
111111 10 10,555555 20 10,777777 10 10,-1
id | hours | rate | Individual wage (hours * rate) | totalWages Accumulator |
|---|---|---|---|---|
| Init | ? | ? | ? | |
111111 | ||||
555555 | ||||
777777 | ||||
-1 | — | — | Exit while loop | Output: Total wages = 400 |
C++ Implementation: ```cpp #include
using namespace std; int main() { int id; float hours, rate, wage, totalWages = 0; cout << "Please enter id, -1 to stop: "; cin >> id; // priming read while (id != -1) { cin >> hours >> rate; wage = hours * rate; cout << "Wage for worker " << id << " is " << wage << endl; totalWages = totalWages + wage; cout << "Please enter id, -1 to stop "; cin >> id; } cout << "Total wages = " << totalWages << endl; return 0; }```
Advanced Looping Paradigms: Nested Loops and File Stream I/O
- Mainline Architectural Business Logic:
- Standard enterprise applications follow a tripartite structure:
- Housekeeping: Variable declarations, memory allocations, input source connections, and priming read operations.
- Detail Loop: Iterative logic executing while end-of-file (
not eof) or sentinel criteria remain unmet. - End of Job (
endOfJob): Summary reporting, buffer flushing, file stream closure, and resource deallocation.
- Standard enterprise applications follow a tripartite structure:

- Nested Loop Structures:
- Definition: An architectural arrangement where an inner loop is completely encapsulated within the body of an outer loop.
- Operational Principles:
- For every single iteration completed by the outer loop, the inner loop executes through its entire cycle from start to finish.
- The total number of inner loop executions is calculated by multiplying outer loop iterations by inner loop iterations:
- Demonstration (Part and Question Counter):
- Outer loop control:
partCounterruns from to . - Inner loop control:
questionCounterruns from to . - For each part ( parts total), questions execute, yielding total questions.
- Outer loop control:

File Stream Persistence ():
Reading and writing data directly to disk files using file stream buffers.
File Ingestion Specification: Ingest integer data from
input21.txtterminated by the sentinel . Compute the aggregate sum and output the final result intooutput21.txt.Implementation: ```cpp
include
include
include
using namespace std;
int main () { ifstream infile("input21.txt"); ofstream outfile("output21.txt");
if (infile.is_open()) { cout << "File opened." << endl; } else { cout << endl << "Unable to open file"; system("PAUSE"); exit(1); } int x; int sum = 0; infile >> x; // Priming read from file while (x != -999) { sum += x; infile >> x; // Subsequent read from file } outfile << "Sum is " << sum << endl; infile.close(); outfile.close(); return 0;} ```
- Sample Execution: If
input21.txtcontains1 2 3 4 5 -999, the loop accumulates and writesSum is 15intooutput21.txt.
- Sample Execution: If
Iterative Mathematical Exponentiation ():
Evaluating dynamic power calculations using
pow(x, n)within a sentinel while loop, where an entry of signals program termination.Implementation: ```cpp
include
include
using namespace std;
int main() { int x, n; cout << "Please enter x: "; cin >> x; // Priming read while (x != -1) { cout << "Please enter n (power): "; cin >> n; cout << x << " to power " << n << " is " << pow(x, n) << endl; cout << "Please enter x: "; cin >> x; // Subsequent read } return 0; } ```
Test Execution:
- Input , Output:
2 to power 3 is 8( - Input , Output:
4 to power 3 is 64( - Input , Output:
5 to power 3 is 125( - Input Loop terminates immediately.
- Input , Output: