0% found this document useful (0 votes)
20 views11 pages

CS1181 Intro-To-Computer-Science ISU 2024 MIDTERM StudyGuideExplainedWeek1&2

Uploaded by

cyberguyhurst
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views11 pages

CS1181 Intro-To-Computer-Science ISU 2024 MIDTERM StudyGuideExplainedWeek1&2

Uploaded by

cyberguyhurst
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Week 1

Discuss compile time error vs runtime error with example.

In programming, errors can generally be classified into two categories: compile-time errors
and runtime errors. These terms refer to the stage in the program's execution where the error
is detected. Let's break them down with definitions and examples.

1. Compile-Time Error
• Definition: Compile-time errors occur during the compilation phase of a program, i.e., when
the source code is being translated into machine code or an intermediate form. These errors
prevent the program from being compiled successfully and typically arise due to issues in
the code that violate the syntax rules or type system of the language.
• Causes:
• Syntax Errors: Violations of the language’s grammar (e.g., missing semicolons,
unmatched brackets).
• Type Errors: Incorrect use of data types (e.g., assigning a string to an integer
variable).
• Declaration Errors: Using variables or functions that haven't been declared or
defined.
• Static Errors: Errors that the compiler can catch without running the program (e.g.,
dividing a number by zero in languages that catch this at compile time).
• Example (in C++):
int main() {

• int a = "Hello"; // Compile-time error: Type mismatch

• return 0;

• }

2. Runtime Error
• Definition: Runtime errors occur after the program has successfully compiled and is
executing. These errors arise due to unexpected or invalid conditions during the program's
runtime, such as dividing by zero, accessing invalid memory, or input errors.
• Causes:
• Logical Errors: The logic of the program is correct in terms of syntax, but it
performs an incorrect operation (e.g., infinite loops).
• Exceptions: Errors like attempting to divide by zero, file not found, or out-of-bounds
array access.
• Resource Errors: Insufficient memory, file access errors, or network connection
failures.
• Null Pointer De-referencing: Trying to access a memory location through a null
pointer.
• Example (in Python):

def divide(a, b):


return a / b

x = 10
y=0
result = divide(x, y) # Runtime error: Division by zero
print(result)

Key Differences Between Compile-Time and Runtime Errors


Aspect Compile-Time Errors Runtime Errors
When Detected During the compilation phase During the program's execution
Logical, resource, and exception-based
Nature Syntax, type, and declaration errors
errors
Program won't compile until all errors Program compiles, but execution will fail
Prevention
are fixed at the error point
Common Incorrect syntax, data type Division by zero, array out-of-bounds,
Causes mismatches, missing semicolons null pointer dereferencing
Usually requires exception handling or
Error Handling Compiler detects and reports the error
careful input validation
Impact on Program does not compile and cannot Program may crash or behave
Program run unpredictably at runtime

Handling Compile-Time vs. Runtime Errors:


1. Compile-Time Errors are easier to detect and fix because they prevent the program from
running. The compiler gives specific error messages, guiding the developer to the problem
area.
• Example solutions: Correcting syntax, properly declaring variables, and using proper
data types.
2. Runtime Errors can be trickier because the program runs and might encounter errors
depending on user input or certain conditions. To handle them, developers use:
• Exception Handling: Mechanisms like try, catch, or except blocks to handle
unexpected errors gracefully without crashing the program.
• Input Validation: Ensuring that inputs are valid before performing operations on
them.

What are the different levels (high, mid, and low) of programming languages
and discuss some differences among those?
Programming languages are often categorized into three levels based on their abstraction from the
hardware and ease of use. These levels are high-level, mid-level, and low-level languages. Each
level serves a different purpose and offers distinct advantages and disadvantages. Let's discuss each:

1. High-Level Languages
• Definition: High-level programming languages provide strong abstraction from the
hardware, making them easy to learn and use. They are designed to be user-friendly, with
features that simplify coding, debugging, and maintenance.
• Examples: Python, Java, C#, Ruby, JavaScript, and Swift.
• Key Characteristics:
• Human-Readable Syntax: The syntax closely resembles human languages or
mathematical notations, making the code easier to read and write.
• Portability: Programs written in high-level languages are often portable across
different platforms and operating systems (machine-independent).
• Automatic Memory Management: Many high-level languages manage memory
automatically (e.g., garbage collection in Java).
• Larger Libraries and Frameworks: High-level languages typically have extensive
standard libraries and frameworks to aid in development.
• Advantages:
• Easier to write, maintain, and debug.
• Faster development time.
• Strong portability across platforms.
• Disadvantages:
• Less control over hardware-specific optimizations.
• Generally slower execution speed compared to lower-level languages because they
require interpretation or compilation into machine code.

2. Mid-Level (or Intermediate-Level) Languages


• Definition: Mid-level languages have a blend of features from both high-level and low-level
languages. They allow programmers to write code that is closer to the machine but still offer
more abstraction than low-level languages.
• Examples: C, C++, Rust, Go.
• Key Characteristics:
• Mix of High and Low-Level Features: Mid-level languages provide features for
direct hardware manipulation (e.g., pointers in C) but also offer higher-level
abstractions like functions and modules.
• Memory Management: They often provide manual memory management features,
giving programmers more control over performance (e.g., malloc and free in C).
• System Programming: These languages are frequently used for system-level
programming (e.g., writing operating systems, device drivers, etc.).
• Compilation to Machine Code: Mid-level languages are typically compiled into
efficient machine code, resulting in better performance than interpreted high-level
languages.
• Advantages:
• Greater control over system resources and hardware.
• Efficient performance due to the ability to optimize at a lower level.
• Suitable for developing operating systems, real-time applications, and performance-
critical software.
• Disadvantages:
• More complex to learn and use than high-level languages.
• Requires explicit memory management, which can lead to bugs (e.g., memory leaks).

3. Low-Level Languages
• Definition: Low-level programming languages are very close to machine code and provide
little or no abstraction from a computer's hardware. Programmers working with low-level
languages have full control over system resources.
• Examples: Assembly language, Machine code (binary).
• Key Characteristics:
• Hardware Specific: Low-level languages are usually tied to a specific hardware
architecture. For example, assembly language is specific to a particular CPU.
• Direct Memory Access: Programmers can directly access memory addresses and
manipulate hardware registers.
• No Abstraction: There is little or no abstraction from the hardware, which means
programmers must manage everything manually, including memory allocation and
CPU instructions.
• Efficient Execution: Since low-level languages are directly translated into machine
code, they are highly efficient and have minimal overhead.
• Advantages:
• Maximum control over hardware and system performance.
• Extremely efficient execution, suitable for embedded systems, firmware, and
performance-critical applications.
• Disadvantages:
• Very difficult to learn and use.
• Highly machine-dependent, meaning code written for one type of hardware may not
work on another.
• Time-consuming to develop, debug, and maintain.

Key Differences:
Mid-Level
Aspect High-Level Languages Low-Level Languages
Languages
Abstraction High Moderate Low
Ease of Use Easy Moderate Hard
Slower than mid and low High, but slightly
Performance Extremely fast and efficient
levels lower than low-level
High (machine-
Portability Moderate Low (machine-dependent)
independent)
Mid-Level
Aspect High-Level Languages Low-Level Languages
Languages
Memory Manual and/or
Automatic Fully manual
Management automatic
Control Over
Limited Moderate to High Complete control
Hardware
System software,
Common Use Application development, Operating systems, hardware
game engines,
Cases web development drivers, real-time systems
embedded software
Example
Python, Java, JavaScript C, C++, Rust, Go Assembly, Machine code
Languages
Each level has its advantages based on the type of project and its requirements. High-level
languages are preferred for general application development due to ease of use, while mid-level and
low-level languages are favored for system programming, performance-critical tasks, and hardware
control.

What is Algorithm, discuss the approach of an algorithm that may help you
organize a number of integers in non-decreasing order

What is an Algorithm?
An algorithm is a step-by-step procedure or set of well-defined instructions designed to perform a
specific task or solve a particular problem. In computing, algorithms are used to process data, carry
out computations, and automate reasoning. An algorithm takes an input, processes it, and produces
an output after performing a series of operations.

Characteristics of an Algorithm:
1. Input: One or more inputs are provided.
2. Output: The algorithm produces one or more outputs.
3. Definiteness: The steps in the algorithm are clearly defined and unambiguous.
4. Finiteness: The algorithm must terminate after a finite number of steps.
5. Effectiveness: Each step must be simple enough to be executed by a human or a machine
within a finite amount of time.

Example of an Algorithm: Sorting a List of Integers in Non-Decreasing Order


To organize a list of integers in non-decreasing order (also called ascending order), one common
algorithm is Bubble Sort. Although there are more efficient algorithms for sorting, such as Merge
Sort, Quick Sort, or Insertion Sort, Bubble Sort is a simple and intuitive algorithm to understand.

Approach of Bubble Sort Algorithm:


Bubble Sort repeatedly steps through the list of integers, compares adjacent elements, and swaps
them if they are in the wrong order (i.e., if the first element is greater than the second). This process
continues until the list is sorted.
Steps of Bubble Sort Algorithm:
1. Start:
• Take a list of n integers as input.
2. Outer Loop:
• Iterate over the entire list n times (or until no more swaps are needed).
3. Inner Loop:
• For each iteration of the outer loop, compare each pair of adjacent integers. If the
first integer is greater than the second, swap them.
4. Check Condition:
• Continue this process for every pair of adjacent elements in the list for each pass.
5. Terminate:
• After one full pass through the list without any swaps, the list is sorted. The
algorithm terminates.
6. Return:
• The sorted list in non-decreasing order.
function bubbleSort(arr):
n = length(arr)
for i from 0 to n-1:
swapped = false
for j from 0 to n-i-1:
if arr[j] > arr[j+1]:
swap arr[j] and arr[j+1]
swapped = true
if not swapped:
break # No more swaps, the list is sorted
return arr
Conclusion:
An algorithm is a set of instructions to solve a problem, and sorting algorithms are commonly used
to organize data in a specific order. Bubble Sort is a simple, intuitive algorithm for sorting integers
in non-decreasing order, but for larger datasets, more efficient algorithms like Merge Sort or Quick
Sort are often preferred.
Tokens
• Tokens are the minimal chunks of program that are recognized by the compiler
• In this context, the smallest meaningful symbols in C++
• Things like keywords (int, double, for), Identifiers (cout, std, myFunction), literals (24, ‘c’),
Operators (+, --, &&), Punctuation, Whitespae
Week 2
Given a decimal number, show me the steps to convert it to the equivalent
binary number

To convert a decimal number (both integer and fractional parts) to its equivalent
binary number, there are two cases to consider: converting the integer part and
the fractional part separately. I'll walk you through the steps for each.

Case 1: Converting the Integer Part


The integer part of the decimal number is converted to binary by repeatedly dividing the number by
2 and keeping track of the remainders.

Steps:
1. Divide the decimal integer by 2.
2. Record the remainder (either 0 or 1).
3. Update the integer by dividing it by 2.
4. Repeat the process until the integer becomes 0.
5. The binary equivalent of the integer is the remainders read from bottom to top (last
remainder first).

Example:
Convert 25 (decimal) to binary:
1. 25÷2=12 remainder 1
2. 12÷2=6 remainder 0
3. 6÷2=3 remainder 0
4. 3÷2=1 remainder 1
5. 1÷2=0 remainder 1
Read the remainders from bottom to top: 11001.
So, 2510=110012.

Case 2: Converting the Fractional Part


The fractional part of a decimal number is converted to binary by multiplying the fraction by 2 and
recording the integer part of the result.

Steps:
1. Multiply the fractional part by 2.
2. Record the integer part (either 0 or 1) as the binary digit.
3. Update the fractional part by subtracting the integer part.
4. Repeat the process until the fractional part becomes 0 or you reach the desired level of
precision.
Example:
Convert 0.625 (decimal) to binary:
1. 0.625×2=1.25 → Integer part: 1 (new fraction: 0.25)
2. 0.25×2=0.5 → Integer part: 0 (new fraction: 0.5)
3. 0.5×2=1.0 → Integer part: 1 (new fraction: 0)
So, 0.62510=0.1012.

Case 3: Converting a Decimal Number with Both Integer and Fractional Parts
When the decimal number has both an integer and fractional part, simply convert each part
separately, then combine them.

Example:
Convert 13.375 (decimal) to binary.
1. Convert the integer part (13):
• 13÷2=6 remainder 1
• 6÷2=3 remainder 0
• 3÷2=1 remainder 1
• 1÷2=0 remainder 1
So, 1310=11012.
2. Convert the fractional part (0.375):
• 0.375×2=0.75 → Integer part: 0
• 0.75×2=1.5 → Integer part: 1
• 0.5×2=1.0 → Integer part: 1
So, 0.37510=0.0112.
3. Combine the two parts:
• 13.37510=1101.0112.

Summary of Steps:
1. For the Integer Part:
• Repeatedly divide the integer by 2 and record remainders.
• Write the remainders in reverse order.
2. For the Fractional Part:
• Repeatedly multiply the fraction by 2 and record the integer part.
• Continue until the fraction becomes 0 or reaches the desired precision.
3. Combine the results (if converting both integer and fractional parts).
These steps will allow you to convert any decimal number to its binary equivalent!
Given a binary number, show the steps to get its decimal equivalent

To convert a binary number to its decimal equivalent, you need to understand


the place value system used in binary. In a binary number, each digit (bit)
represents a power of 2, starting from 0 on the rightmost digit.

Steps to Convert a Binary Number to Decimal


1. Integer Part of a Binary Number:
For the integer part of the binary number, each bit represents a power of 2. The general formula to
convert the binary integer part to decimal is:
Decimal=i=0∑n−1biti×2i
Where:
• n is the number of bits in the binary number.
• biti is the bit value (0 or 1) at the i-th position, starting from 0 on the right.
• 2i represents the place value of that bit.

Example:
Convert the binary number 10112 (which represents the integer part) to decimal:
1. Start from the rightmost bit, assign powers of 2 to each bit:
• Rightmost bit (bit 0): 1×20=1
• Second bit (bit 1): 1×21=2
• Third bit (bit 2): 0×22=0
• Leftmost bit (bit 3): 1×23=8
2. Sum the results:
8+0+2+1=11
So, 10112=1110.

2. Fractional Part of a Binary Number:


For the fractional part of the binary number, each bit represents a negative power of 2. The formula
to convert the binary fraction to decimal is:
FractionDecimal Fraction=i=1∑nbiti×2−i
Where:
• biti is the bit value (0 or 1) at the i-th position after the binary point (starting from 1).
• 2−i represents the place value for the fractional part.

Example:
Convert the binary number 0.1012 (fractional part) to decimal:
1. Assign negative powers of 2 to each bit after the binary point:
• First bit (bit 1): 1×2−1=0.5
• Second bit (bit 2): 0×2−2=0
• Third bit (bit 3): 1×2−3=0.125
2. Sum the results:
0.5+0+0.125=0.625
So, 0.1012=0.62510.

3. Converting a Binary Number with Both Integer and Fractional Parts


If you have a binary number with both integer and fractional parts, convert them separately and then
add the results.

Example:
Convert the binary number 1101.0112 to decimal.
1. Integer part 11012:
• 1×23=8
• 1×22=4
• 0×21=0
• 1×20=1
Sum: 8+4+0+1=13
2. Fractional part 0.0112:
• 0×2−1=0
• 1×2−2=0.25
• 1×2−3=0.125
Sum: 0+0.25+0.125=0.375
3. Combine the integer and fractional parts:
13+0.375=13.375
So, 1101.0112=13.37510.

Summary of Steps:
1. For the Integer Part:
• Multiply each binary digit by its corresponding power of 2 (starting from 20).
• Sum the results.
2. For the Fractional Part:
• Multiply each binary digit after the point by its corresponding negative power of 2
(starting from 2−1).
• Sum the results.
3. Combine the integer and fractional parts to get the final decimal number.
This method works for any binary number!

Given a binary number, translate it to corresponding hexadecimal equivalent

Remember to take the binary in chunks of 4, 0000 → 1, …., 1111 → H . If it is a 8 bit signed
integer then the highest bit (the first one) is the sign. 1 = negative 0 = positive

Given a positive binary number, find the 2’s complement (which is its Negative)

Note that 00000001 + 11111111 = 00000000 as it should, take a positive integer 8 and
add its negative -8 you get 0

You might also like