Midterm Review Computing Fundamentals
Key Concepts of Programming
Program: A program is a set of instructions that are executed sequentially, one at a time, to perform specific tasks. This can be likened to following a recipe in cooking, where each step must be completed in order to achieve the final dish.
Input: Programs receive data from various sources such as files, keyboards, or touchscreens. This data serves as the foundation for processing within the program.
Process: The core functionality of a program involves performing computations on the input data, such as arithmetic operations (e.g., adding two variables). This is where the program transforms input into meaningful results.
Output: After processing, the program generates output, which can be displayed on a screen, saved to a file, or sent to another program.
Variables: Variables are symbolic names (like x, y, z) that hold data values. They are essential for storing and manipulating data within a program.
Algorithm: An algorithm is a defined sequence of steps or instructions designed to solve a specific problem, serving as the blueprint for program development.
Example of a Program Structure
Analogy: Think of a program as a cooking recipe where each ingredient (input) is processed (cooked) to create a dish (output).
Example: A simple program that adds two numbers can be visualized as:
Input: Get two numbers from the user.
Process: Add the two numbers together.
Output: Display the result.
Section 1.2: Program Components and Flow
Flowchart and Program Structure
Flowchart: A flowchart is a visual representation of a program's logic and flow, using symbols to denote different types of actions or steps in the program.
Variable: A variable is a named storage location in memory that holds a value, which can be changed during program execution.
Statement: Each statement in a program carries out a specific task and is executed in sequence, contributing to the overall functionality of the program.
Node: In flowcharts, each statement is represented as a node, illustrating the flow of control from one statement to the next.
Interpreter: An interpreter is a program that executes the statements of another program line by line, allowing for immediate execution and testing of code.
Input Statement Example: The statement
variable = Get next inputillustrates how a program retrieves user input and assigns it to a variable.
Understanding Output and String Literals
Output Statement: To output the value of a variable, such as
numCars, the correct statement isPut numCars to output, which displays the value stored innumCarswithout quotations.String Literal: A string literal is a sequence of characters enclosed in double quotes, representing fixed text in the program.
Character: Any single letter, digit, or symbol is considered a character, which can be manipulated within the program.
Section 1.3: Code Readability and Structure
Importance of Comments and Whitespace
Comment: Comments are annotations in the code that help programmers understand the logic and purpose of the code. They are ignored by the compiler or interpreter during execution and start with
//.Whitespace: Whitespace refers to spaces, tabs, and newlines in the code that improve readability for humans but do not affect the execution of the program. Proper use of whitespace can make code easier to read and maintain.
Section 1.6: Data Representation
Bits and Bytes
Bit: A bit is the smallest unit of data in computing, represented as either a 0 or a 1. It can be thought of as a light switch that is either on (1) or off (0).
Byte: A byte consists of 8 bits, allowing for a wider range of values. For example, the binary number
11000101represents one byte.Character Encoding: Each character can be represented by a unique bit code, with ASCII being a common encoding standard. For instance, the character 'Z' is represented as
1011010in ASCII.
Section 1.10: Simplified Programming Concepts
Pseudocode and Output Formatting
Pseudocode: Pseudocode is a simplified, human-readable version of programming code that outlines the logic of a program without strict syntax rules. It helps in planning and understanding algorithms before actual coding.
Output Formatting: To format output correctly, using
at the end of a string moves the cursor to the next line in the output. For example:
Put "Goodbye\n" to output
Put "Cam\n" to outputThis results in:
Goodbye
Cam
LOOPS
A loop is a program construct that repeatedly executes the loop's statements (known as the loop body) while the loop's expression is true; when false, execution proceeds past the loop. Each time through a loop's statements is called an iteration.
- A for loop is a loop consisting of a loop variable initialization, a loop expression, and a loop variable update that typically describes iterating for a specific number of times.
Generally, a programmer uses a for loop when the number of iterations is known (like loop 5 times, or loop numItems times).
For loop example:
integer sum
integer i
sum = 5
for i = 0; i < 3; i = i + 1
Put sum to output
Put " " to output
sum = sum + 5
Put "\n" to output
A for loop is a loop with three parts at the top: a loop variable initialization, a loop expression, and a loop variable update.
for i = 0; i < 3; i = i + 1
First Part= for i = 0
Second Part= i < 3
Third Part= i = i + 1
- A while loop repeatedly executes the loop body while the loop's expression evaluates to true.
While loop example:
integer userNum
integer curPower
curPower = 2
userNum = Get next input
while userNum == 1
Put curPower to output
Put "\n" to output
curPower = curPower * 2
userNum = Get next input
Put "Done." to output
- A nested loop is a loop that appears in the body of another loop. The nested loops are commonly referred to as the inner loop and outer loop.
Nested loop example:
integer row integer col integer num_rows integer num_cols num_rows = 4 num_cols = 4 // Outer loop over each row for row = 1; row <= num_rows; row = row + 1 // Inner loop over each column for col = 1; col <= num_cols; col = col + 1 // Print the product of row and col Put row * col to output // Print a tab for spacing Put "\t" to output // After inner loop ends, go to the next line Put "\n" to output
*This Coral pseudocode uses nested loops to print a rectangle made of asterisks (*). The outer loop controls the number of rows (vertical lines), and the inner loop controls the number of columns (characters printed per line).
Why is Input Validation Important?
When writing programs that accept user input, we cannot assume that users will always enter valid data. Input validation ensures that a program:
• Prevents crashes caused by unexpected input.
• Ensures correct data types (e.g., numbers instead of letters).
• Improves user experience by giving clear feedback.
• Enhances security by preventing malicious inputs.
Invalid Input Example: A program asks for a user’s age, but they enter "twenty" instead of 20. If the program does not check for this, it may crash when trying to perform calculations
Valid Input Example:
// Example: Input Validation Loop requiring input be less than 5
// Declare variables
integer num
// Priming Read
num = Get next input
// Loop until a valid input read
while num >= 5
Put "Incorrect Input: Must be less than 5\n" to output
// Ask user for input again
num = Get next input
// Have a valid input, continue the program
Put "Yay! You entered: " to output
Put num to outputWhat is a Sentinel-Controlled Loop?
A sentinel-controlled loop is a loop that continues running until the user enters a special value (the sentinel) that signals the program to stop.
Why Use a Sentinel?
• The number of iterations is unknown in advance.
• The program should process input repeatedly until the user decides to stop.
• Used commonly in menus, user-driven input, and data processing.
Examples of Sentinels:
• A grade input program where -1 signals no more grades.
• A bank deposit system where entering 0"ends transactions.
Sentinel-controlled Loop Example:
// Example: Sentinel-Controlled Loop with a counter
// Declare variables
integer grade
integer count
// Initialize variables
count = 0
// Priming read: Get the first grade
grade = Get next input
// While input is not the sentinel value (-1)
while grade != -1
// Update Accumulator
count = count + 1
// Ask again (repeat priming read) as last line in while
grade = Get next input
// Continue with program after all grades entered
Put "Number of grades entered: " to output
Put count to outputWe use a while loop because the loop body can run any number of times (zero or more up to any large number). The loop runs until the event that the user enters an input of -1, indicating all grades have been entered.
ARRAYS
An array is a special variable having one name, but storing a list of data items, with each item being directly accessible. Some languages use a construct similar to an array called a vector. Each item in an array is known as an element. In an array, each element's location number is called the index
Example Question:
What is the value of peoplePerDay[8]?
peoplePerDay[9] = 5
peoplePerDay[8] = peoplePerDay[9] - 3Array declarations and accessing elements
A programmer commonly needs to maintain a list of items, just as people maintain a list of items like a grocery list or a course roster. An array variable is an ordered list of items of a given data type and size. Each item in an array is called an element. For array x, each element is accessed as x[0], x[1], ... In an array access, the number in brackets is called the index of that element. In Coral, the first array element is at index 0.
Some relevant terminology
[ ] are brackets
{ } are braces
( ) are parentheses
To contrast with array variables, a single-item (non-array) variable is called a scalar variable.
Array Code Example:
integer array(5) oldestPeople
integer nthPerson
integer personAge
// Died 1997 in France
oldestPeople[0] = 122
// Died 1999 in U.S.
oldestPeople[1] = 119
// Died 1993 in U.S.
oldestPeople[2] = 117
// Died 1998 in Canada
oldestPeople[3] = 117
// Died 2006 in Ecuador
oldestPeople[4] = 116
nthPerson = Get next input
if ((nthPerson >= 1) and (nthPerson <= 5))
personAge = oldestPeople[nthPerson - 1]
Put nthPerson to output
Put "the oldest person died at age " to output
Put personAge to output
Array Loop Example:
integer i
integer array(4) numsVar
integer minNum
for i = 0; i < numsVar.size; i = i + 1
numsVar[i] = Get next input
for i = 0 ; i < numsVar.size; i = i + 1
if numsVar[i] < minNum
minNum = numsVar[i]
Put "Smallest element: " to output
Put minNum to output
Another Array Loop Example:
Write code that loops through the array userNums. Each iteration: If userNums[i] is less than 10, put userNums[i] to output, and then put "_" to output. Else, assign userNums[i] with userNums[i] plus 3.
integer i
integer array(5) userNums
for i = 0; i < userNums.size; i = i + 1
userNums[i] = Get next input
for i = 0; i < userNums.size; i = i + 1
if userNums[i] < 10
Put userNums[i] to output
Put "_" to output
else
userNums[i] = userNums[i] + 3
Put "\nArray values: " to output
for i = 0; i < userNums.size; i = i + 1
Put userNums[i] to output
Put " " to output