Designed a comprehensive C++ encryption/decryption system as my final project, integrating OOP, arrays, and control structures. The EncryptionMachine class supports Caesar and substitution ciphers with methods for encryption, decryption, and brute-force Caesar decryption, handling 50-character strings with case preservation via a menu-driven interface.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, class definition, arrays, for loops, switch, header file (Encryption.h)
// Sam Macinsky
// 12/03/2024
// Final Project: Encrypt/Decrypt w/ two ciphers
#ifndef ENCRYPTION_MACHINE_H
#define ENCRYPTION_MACHINE_H
#include <iostream>
class EncryptionMachine {
public:
// Maximum string length
static const int MAX_LENGTH = 50;
// Constructors and Destructor
EncryptionMachine() {
// Initialize alphabets
const char* defaultAlpha = "abcdefghijklmnopqrstuvwxyz";
const char* defaultSubst = "qwertyuiopasdfghjklzxcvbnm";
for (int i = 0; i < 26; i++) {
alpha[i] = defaultAlpha[i];
subst[i] = defaultSubst[i];
}
alpha[26] = '\0';
subst[26] = '\0';
// Initialize other arrays
for (int i = 0; i < MAX_LENGTH; i++) {
clearText[i] = '\0';
encryptedData[i] = '\0';
decryptedData[i] = '\0';
}
}
//
// Input methods
//
void inputText() {
std::cout << "Enter text to encrypt (max 50 characters): ";
std::cin.getline(clearText, MAX_LENGTH);
}
void inputEncryptedText() {
std::cout << "Enter encrypted text to decrypt (max 50 characters): ";
std::cin.getline(encryptedData, MAX_LENGTH);
}
//
// Encryption methods
//
void caesarEncrypt(int shift) {
int textLength = getStringLength(clearText);
for (int i = 0; i < textLength; i++) {
char currentChar = clearText[i];
if (isLowerCase(currentChar)) {
// Find index in alphabet
int alphaIndex = 0;
while (alpha[alphaIndex] != currentChar) {
alphaIndex++;
}
// Apply shift with modulo to wrap around
int caesarIndex = (alphaIndex + shift) % 26;
encryptedData[i] = alpha[caesarIndex];
}
else if (isUpperCase(currentChar)) {
// Convert to lowercase, process, then convert back
char lowerChar = toLowerCase(currentChar);
int alphaIndex = 0;
while (alpha[alphaIndex] != lowerChar) {
alphaIndex++;
}
int caesarIndex = (alphaIndex + shift) % 26;
encryptedData[i] = toUpperCase(alpha[caesarIndex]);
}
else {
// Non-alphabet characters stay the same
encryptedData[i] = currentChar;
}
}
encryptedData[textLength] = '\0';
}
void substitutionEncrypt() {
int textLength = getStringLength(clearText);
for (int i = 0; i < textLength; i++) {
char currentChar = clearText[i];
if (isLowerCase(currentChar)) {
// Find index in alphabet
int alphaIndex = 0;
while (alpha[alphaIndex] != currentChar) {
alphaIndex++;
}
// Map to substitution cipher
encryptedData[i] = subst[alphaIndex];
}
else if (isUpperCase(currentChar)) {
// Convert to lowercase, process, then convert back
char lowerChar = toLowerCase(currentChar);
int alphaIndex = 0;
while (alpha[alphaIndex] != lowerChar) {
alphaIndex++;
}
encryptedData[i] = toUpperCase(subst[alphaIndex]);
}
else {
// Non-alphabet characters stay the same
encryptedData[i] = currentChar;
}
}
encryptedData[textLength] = '\0';
}
//
// Decryption methods
//
void caesarDecrypt(int shift) {
int textLength = getStringLength(encryptedData);
for (int i = 0; i < textLength; i++) {
char currentChar = encryptedData[i];
if (isLowerCase(currentChar)) {
// Find index in alphabet
int alphaIndex = 0;
while (alpha[alphaIndex] != currentChar) {
alphaIndex++;
}
// Apply reverse shift with modulo
int caesarIndex = (alphaIndex - shift + 26) % 26;
decryptedData[i] = alpha[caesarIndex];
}
else if (isUpperCase(currentChar)) {
// Convert to lowercase, process, then convert back
char lowerChar = toLowerCase(currentChar);
int alphaIndex = 0;
while (alpha[alphaIndex] != lowerChar) {
alphaIndex++;
}
int caesarIndex = (alphaIndex - shift + 26) % 26;
decryptedData[i] = toUpperCase(alpha[caesarIndex]);
}
else {
// Non-alphabet characters stay the same
decryptedData[i] = currentChar;
}
}
decryptedData[textLength] = '\0';
}
void substitutionDecrypt() {
int textLength = getStringLength(encryptedData);
for (int i = 0; i < textLength; i++) {
char currentChar = encryptedData[i];
if (isLowerCase(currentChar)) {
// Find index in substitution alphabet
int substIndex = 0;
while (subst[substIndex] != currentChar) {
substIndex++;
}
// Map back to original alphabet
decryptedData[i] = alpha[substIndex];
}
else if (isUpperCase(currentChar)) {
// Convert to lowercase, process, then convert back
char lowerChar = toLowerCase(currentChar);
int substIndex = 0;
while (subst[substIndex] != lowerChar) {
substIndex++;
}
decryptedData[i] = toUpperCase(alpha[substIndex]);
}
else {
// Non-alphabet characters stay the same
decryptedData[i] = currentChar;
}
}
decryptedData[textLength] = '\0';
}
void bruteForceDecrypt() {
std::cout << "Brute Force Caesar Decryption:\n";
for (int shift = 1; shift <= 25; shift++) {
// Reset decrypted data
for (int j = 0; j < MAX_LENGTH; j++) {
decryptedData[j] = '\0';
}
int textLength = getStringLength(encryptedData);
for (int i = 0; i < textLength; i++) {
char currentChar = encryptedData[i];
if (isLowerCase(currentChar)) {
// Find index in alphabet
int alphaIndex = 0;
while (alpha[alphaIndex] != currentChar) {
alphaIndex++;
}
// Apply reverse shift with modulo
int caesarIndex = (alphaIndex - shift + 26) % 26;
decryptedData[i] = alpha[caesarIndex];
}
else if (isUpperCase(currentChar)) {
// Convert to lowercase, process, then convert back
char lowerChar = toLowerCase(currentChar);
int alphaIndex = 0;
while (alpha[alphaIndex] != lowerChar) {
alphaIndex++;
}
int caesarIndex = (alphaIndex - shift + 26) % 26;
decryptedData[i] = toUpperCase(alpha[caesarIndex]);
}
else {
// Non-alphabet characters stay the same
decryptedData[i] = currentChar;
}
}
decryptedData[textLength] = '\0';
// Print result
std::cout << "Shift " << shift << ": " << decryptedData << std::endl;
}
}
//
// Display methods
//
void displayEncrypted() {
std::cout << "Encrypted Text: " << encryptedData << std::endl;
}
void displayDecrypted() {
std::cout << "Decrypted Text: " << decryptedData << std::endl;
}
// Public data members for direct access in main
char clearText[MAX_LENGTH];
char encryptedData[MAX_LENGTH];
char decryptedData[MAX_LENGTH];
private:
// Alphabet arrays
char alpha[27];
char subst[27];
// Utility method prototypes
int getStringLength(const char* str) const {
int length = 0;
while (str[length] != '\0' && length < MAX_LENGTH) {
length++;
}
return length;
}
//
// Character manipulation methods
//
bool isUpperCase(char c) const {
return (c >= 'A' && c <= 'Z');
}
bool isLowerCase(char c) const {
return (c >= 'a' && c <= 'z');
}
char toUpperCase(char c) const {
return isLowerCase(c) ? (c - 32) : c;
}
char toLowerCase(char c) const {
return isUpperCase(c) ? (c + 32) : c;
}
};
#endif // ENCRYPTION_MACHINE_H
// Sam Macinsky
// 12/03/2024
// Final Project: Encrypt/Decrypt w/ two ciphers
#include <iostream>
#include "encryption.h"
int main() {
EncryptionMachine machine;
char choice;
do {
std::cout << "\n=====================================\n";
std::cout << "+++ Encryption/Decryption Machine +++\n";
std::cout << "=====================================\n";
std::cout << "1. Caesar Cipher Encryption\n";
std::cout << "2. Substitution Cipher Encryption\n";
std::cout << "3. Caesar Cipher Brute Force Decryption\n";
std::cout << "4. Caesar Cipher Manual Decryption\n";
std::cout << "5. Substitution Cipher Decryption\n";
std::cout << "6. Exit\n";
std::cout << "Enter your choice: ";
std::cin >> choice;
std::cin.ignore(); // Clear input buffer
switch (choice) {
case '1': {
int shift;
machine.inputText();
std::cout << "Enter Caesar Cipher shift (1-25): ";
std::cin >> shift;
std::cin.ignore(); // Clear input buffer
machine.caesarEncrypt(shift);
machine.displayEncrypted();
break;
}
case '2': {
machine.inputText();
machine.substitutionEncrypt();
machine.displayEncrypted();
break;
}
case '3': {
machine.inputEncryptedText();
machine.bruteForceDecrypt();
break;
}
case '4': {
int shift;
machine.inputEncryptedText();
std::cout << "Enter Caesar Cipher shift used for encryption: ";
std::cin >> shift;
std::cin.ignore(); // Clear input buffer
machine.caesarDecrypt(shift);
machine.displayDecrypted();
break;
}
case '5': {
machine.inputEncryptedText();
machine.substitutionDecrypt();
machine.displayDecrypted();
break;
}
case '6':
std::cout << "Exiting...\n";
break;
default:
std::cout << "Invalid choice. Try again.\n";
}
} while (choice != '6');
}
// I thought about including an EULA with a clause that said by running
// this code, you agree to give the author a 100% on their project, but
// decided against it in case you decided to decline the EULA and not run
// the program and just give me a 0 instead haha. Anyway, thanks for an
// awesome semester, I'm really glad I decided to come to MVCC for a career
// change and only wish I had known at 16 that there's more to love about
// computers than just video games.
Interactive Calculator Script (BASH)
Developed a BASH script functioning as a calculator with options for addition, subtraction, multiplication, and division. Users specify the number of operands, input values, and the script computes the result using loops and bc for precise division, recursively calling itself until the user exits.
Fall 2023 | CI 121 - Microcomputer Technology for Science | Tools: BASH, Linux shell commands (case, for, read, bc)
#!/bin/bash
# Lab #10
# Sam Macinsky
echo
echo "Welcome to the Calculator!"
echo "Choose an option:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
"
# Menu for the user
read -p "Enter your option: " option
# Read in user input assign to option variable
case ${option} in
1) read -p "How many numbers do you want to add? " num1
sum=0
for (( a=1; a<=num1; a++ ))
do
read -p "Enter number $a: " num2
sum=$(($sum + $num2))
# Add to existing sum
done
echo "You sum is: " $sum
echo
# Display answer
./lab#10.sh
;;
2) read -p "How many numbers would you like to subtract? " num1
read -p "Please enter the first number: " base
for (( a=2; a<=num1; a++ ))
do
read -p "Enter number $a in the order you want subtracted: " num2
base=$(($base - $num2))
# subtract from existing sum
done
echo "Your difference is: " $base
echo
# Display answer
./lab#10.sh
;;
3) read -p "How many numbers do you want to multiply? " num1
sum=1
for (( a=1; a<=num1; a++ ))
do
read -p "Enter number $a: " num2
sum=$(($sum * $num2))
# multiply
done
echo "Your answer is: " $sum
echo
# Display answer
./lab#10.sh
;;
4) read -p "How many numbers do you want to divide? " num1
read -p "Enter first number: " base
for (( a=2; a<=num1; a++ ))
do
read -p "Enter number $a in the order you want divided: " num2
base=$(bc <<< "scale=2;$base/$num2")
done
echo "Your answer is: "$base
echo
# Display answer
./lab#10.sh
;;
5)exit
# Exits the script
;;
*)echo "Please try again!"
# Error handling
./lab#10.sh
;;
esac
Number Guessing Game (Python)
Crafted a Python script with functions for an interactive guessing game. The program generates a random number (1-100), tracks guesses, provides feedback, and offers replay logic, blending interactivity with modularity.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, random module, input(), int(), while loop, function definitions
# Chapter 5 Exercise 19
# Sam Macinsky
import random
#Define functions
def play_guessing_game():
# Generate a random number in the range of 1 through 100.
random_number = random.randint(1, 100)
guess_count = 0
while True:
guess = int(input("Guess the number (1-100): "))
guess_count += 1
if guess < random_number:
print("Too low, try again.")
elif guess > random_number:
print("Too high, try again.")
else:
print(f"Congratulations! You guessed the number {random_number} in {guess_count} guesses.")
break
def main():
print("Welcome to the Number Guessing Game!")
play_again = 'yes'
while play_again.lower() == 'yes':
play_guessing_game()
play_again = input("Do you want to play again? (yes/no): ")
print("Thank you for playing!")
# Call main
main()
Bank Account Manager (C++)
Implemented a C++ class Account in a header file and a driver program to manage bank accounts. The class includes a constructor, deposit and withdrawal methods with validation, and getter/setter functions, demonstrating encapsulation and class usage in OOP.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <string>, class definition, header file (Account.h)
// Sam Macinsky
// 09/24/2024
// Account Header
#include <string>
class Account {
public:
// Account constructor with two parameters
Account(std::string accountName, int initialBalance)
: name{accountName} {
if (initialBalance > 0) {
balance = initialBalance;
}
}
// function that deposits only a valid amount to the balance
void deposit(int depositAmount) {
if (depositAmount > 0) {
balance = balance + depositAmount;
}
}
// function returns the account balance
int getBalance() {
return balance;
}
// function that sets the name
void setName(std::string accountName) {
name = accountName;
}
// function that returns the name
std::string getName() {
return name;
}
void withdrawal(int withdrawalAmount) {
if (withdrawalAmount > balance) {
std::cout << "\nWithdrawal amount exceeded account balance." << std::endl;
} else if (withdrawalAmount > 0) {
balance -= withdrawalAmount;
}
}
private:
std::string name;
int balance{0};
};
// Sam Macinsky
// 09/24/2024
// Account
#include <iostream>
#include <string>
#include "Account.h"
int main()
{
Account account1{"Jane Green", 50};
Account account2{"John Blue", 300};
// display initial balance of each object
std::cout << "account1: " << account1.getName() << " balance is $"
<< account1.getBalance();
std::cout << "\naccount2: " << account2.getName() << " balance is $"
<< account2.getBalance();
std::cout << "\n\nEnter deposit amount for account1: "; // prompt
int depositAmount;
std::cin >> depositAmount; // obtain user input
std::cout << "adding " << depositAmount << " to account1 balance";
account1.deposit(depositAmount); // add to account1's balance
// display balances
std::cout << "\n\naccount1: " << account1.getName() << " balance is $"
<< account1.getBalance();
std::cout << "\naccount2: " << account2.getName() << " balance is $"
<< account2.getBalance();
std::cout << "\n\nEnter deposit amount for account2: "; // prompt
std::cin >> depositAmount; // obtain user input
std::cout << "adding " << depositAmount << " to account2 balance";
account2.deposit(depositAmount); // add to account2 balance
// display balances
std::cout << "\n\naccount1: " << account1.getName() << " balance is $"
<< account1.getBalance();
std::cout << "\naccount2: " << account2.getName() << " balance is $"
<< account2.getBalance() << std::endl;
// Withdrawal test for account1
std::cout << "\n\nEnter withdrawal amount for account1: "; // prompt
int withdrawalAmount;
std::cin >> withdrawalAmount; // obtain user input
std::cout << "\nAttempting withdrawal from account1 balance";
account1.withdrawal(withdrawalAmount);
std::cout << "\naccount1: " << account1.getName() << " balance is $" << account1.getBalance() << std::endl;
// Withdrawal test for account2
std::cout << "\nEnter withdrawal amount for account2: "; // prompt
std::cin >> withdrawalAmount; // obtain user input
std::cout << "\nAttempting withdrawal from account2 balance";
account2.withdrawal(withdrawalAmount);
std::cout << "\naccount2: " << account2.getName() << " balance is $" << account2.getBalance() << std::endl;
}
Rare Pepe ASCII Art Gallery (BASH)
Designed an interactive BASH script that creates a directory (rarepepes), generates ten text files with unique ASCII art of Pepe the Frog, and uses a case statement to display artwork based on user input (0-9), blending creativity with technical skill.
Fall 2023 | CI 121 - Microcomputer Technology for Science | Tools: BASH, Linux shell commands (if, rm, mkdir, touch, echo, read, case, cat)
Constructed a BASH script with a menu featuring three loop-driven options: displaying ten text lines, executing two Linux file system commands, and fetching an HTML webpage to show its first and last 17 lines using wget, head, and tail.
Fall 2023 | CI 121 - Microcomputer Technology for Science | Tools: BASH, Linux shell commands (while, case, wget, head, tail, read)
#!/bin/bash
# Interpreter Line
# Sam Macinsky
while true; do
echo "Lab #9 - Dice Roller and Randomizer Options:"
echo "a. Roll once"
echo "b. Multiple rolls"
echo "c. Randomizer"
echo "Enter your choice (a/b/c) or 'q' to quit: "
read choice
case $choice in
a)
# Option a: Roll once
echo "Result of a single roll: $((RANDOM % 6 + 1))"
;;
b)
# Option b: Multiple rolls
echo "Enter the number of rolls: "
read num_rolls
# Perform multiple rolls
for ((i=0; i randomized_file.txt
# Perform randomizations
for ((i=0; i
Name and Number Sorting Menu
Engineered a BASH script with a menu offering five sorting options: adding and sorting names A-Z, reverse sorting Z-A, extracting names at odd/even indices, and sorting numbers in ascending/descending order using arrays and loops.
Fall 2023 | CI 121 - Microcomputer Technology for Science | Tools: BASH, Linux shell commands (while, case, read, sort, for, arrays)
#!/bin/bash
# Interpreter Line
# Sam Macinsky
names=()
numbers=()
#Define Option 1
option_1() {
read -p "Enter names separated by space: " -a input
names+=("${input[@]}")
IFS=$'\n' sorted=($(sort <<<"${names[*]}"))
echo "Sorted Names: ${sorted[*]}"
}
# Define Option 2
option_2() {
read -p "Enter names separated by space: " -a input
names+=("${input[@]}")
IFS=$'\n' sorted=($(sort -r <<<"${names[*]}"))
echo "Reverse Sorted Names: ${sorted[*]}"
}
# Define Option 3
option_3() {
read -p "Enter names separated by space: " -a input
names+=("${input[@]}")
IFS=$'\n' sorted=($(sort <<<"${names[*]}"))
odd_indices=()
for ((i = 1; i < ${#sorted[@]}; i += 2)); do
odd_indices+=("${sorted[i]}")
done
echo "Names at Odd Indices: ${odd_indices[*]}"
}
# Define Option 4
option_4() {
read -p "Enter names separated by space: " -a input
names+=("${input[@]}")
IFS=$'\n' sorted=($(sort <<<"${names[*]}"))
even_indices=()
for ((i = 0; i < ${#sorted[@]}; i += 2)); do
even_indices+=("${sorted[i]}")
done
echo "Names at Even Indices: ${even_indices[*]}"
}
# Define Option 5
option_5() {
read -p "Enter numbers separated by space: " -a input
numbers+=("${input[@]}")
IFS=$'\n' sorted=($(sort -g <<<"${numbers[*]}"))
ascending=("${sorted[@]}")
IFS=$'\n' sorted=($(sort -g -r <<<"${numbers[*]}"))
descending=("${sorted[@]}")
echo "Sorted 0-~ Numbers: ${ascending[*]}"
echo "Sorted ~-0 Numbers: ${descending[*]}"
}
while true; do
echo "Options:"
echo "1. Add names and sort"
echo "2. Add names and reverse sort"
echo "3. Add names and sort (odd indices)"
echo "4. Add names and sort (even indices)"
echo "5. Add numbers and sort 0-~ and ~-0"
echo "X. Exit"
read -p "Enter your choice (1-6): " choice
case $choice in
1) option_1;;
2) option_2;;
3) option_3;;
4) option_4;;
5) option_5;;
X) echo "Goodbye!"; exit;;
*) echo "Invalid choice. Please select a valid option.";;
esac
done
Multi-Function Menu Script
Crafted an interactive BASH script featuring a looping menu with five options: creating a nested directory structure, generating a user-named blank file, comparing two letters, opening a text editor (vi), and searching for a file system-wide, running until the user exits.
Fall 2023 | CI 121 - Microcomputer Technology for Science | Tools: BASH, Linux shell commands (while, case, mkdir, touch, vi, find, grep)
#!/bin/bash
# Interpreter Line
# Sam Macinsky
# Greet the user
echo
echo "Welcome to Lab 6!"
echo
# Begin infinite loop of options until the user selects X.
while true; do
# Display menu options and prompt user for choice.
echo "LAB #6 MENU:"
echo "A. Create directory: foo/bar/test/blah"
echo "B. Create a blank file"
echo "C. Compare two letters"
echo "D. Open text editor"
echo "E. Search for a file"
echo "X. Exit"
echo
read -p "Please enter your choice: " choice
# Convert choice to lowercase for case insensitivity.
choice=$(echo "$choice" | tr '[:upper:]' '[:lower:]')
case $choice in
a)
# Option A: Create directory foo/bar/test/blah and do a long directory listing.
mkdir -p foo/bar/test/blah
ls -l foo/bar/test/blah
;;
b)
# Option B: Create a blank file with user-specified name.
read -p "Enter the filename: " filename
touch "$filename"
echo "File '$filename' successfully created."
;;
c)
# Option C: Compare two letters.
read -p "Enter first letter: " letter1
read -p "Enter second letter: " letter2
if [[ "$letter1" == "$letter2" ]]; then
echo "Letters are the same."
else
echo "Letters are different."
fi
;;
d)
# Option D: Open text editor and specify the intended file name.
read -p "Enter the filename: " filename
vi "$filename"
;;
e)
# Option E: Search for a file using user-provided search term.
read -p "Enter the search term: " search_term
find / -name "$search_term" 2>&1 | grep -v "Permission denied"
;;
x)
# Option X: Exit the script.
echo "Exiting the script. Goodbye!"
exit 0
;;
*)
# Handle invalid choices.
echo "Invalid choice. Please try again."
;;
esac
done
Comparator and Name Sorter Script
Built a BASH script to compare numbers and sort names, showcasing conditional logic and file-based sorting. The script prompts for three numbers, determines the largest using if-else statements, and saves the result to a file, then collects ten names and generates two sorted outputs (A-Z and Z-A).
Fall 2023 | CI 121 - Microcomputer Technology for Science | Tools: BASH, Linux shell commands (read, if, echo, sort, cat, rm)
#!/bin/bash
#Interpreter Line
#Sam Macinsky
echo "Welcome to the Comparator Script!"
# Compare 3 numbers and send the output to a file
read -p "Enter the first number: " num1
read -p "Enter the second number: " num2
read -p "Enter the third number: " num3
# Perform the comparison and save the result to a file
if [ "$num1" -gt "$num2" ] && [ "$num1" -gt "$num3" ]; then
result="The first number, ($num1), is the largest."
elif [ "$num2" -gt "$num1" ] && [ "$num2" -gt "$num3" ]; then
result="The second number, ($num2), is the largest."
elif [ "$num3" -gt "$num1" ] && [ "$num3" -gt "$num2" ]; then
result="The third number, ($num3), is the largest."
else
result="All three numbers are equal."
fi
# Write the result to a file and display results
echo "$result" > comparison_result.txt
cat comparison_result.txt
# Prompt the user to enter 10 names
echo "Please enter 10 names."
read -p "Enter the first name: " name1
read -p "Enter the second name: " name2
read -p "Enter the third name: " name3
read -p "Enter the fourth name: " name4
read -p "Enter the fifth name: " name5
read -p "Enter the sixth name: " name6
read -p "Enter the seventh name: " name7
read -p "Enter the eighth name: " name8
read -p "Enter the ninth name: " name9
read -p "Enter the tenth name: " name10
echo $name1 > names.txt
echo $name2 >> names.txt
echo $name3 >> names.txt
echo $name4 >> names.txt
echo $name5 >> names.txt
echo $name6 >> names.txt
echo $name7 >> names.txt
echo $name8 >> names.txt
echo $name9 >> names.txt
echo $name10 >> names.txt
# Sort the names A-Z and save the result to a file
sort names.txt > sorted_names_AZ.txt
# Sort the names Z-A and save the result to a file
sort -r names.txt > sorted_names_ZA.txt
# Display the content of the sorted files
echo "Names sorted A-Z:"
cat sorted_names_AZ.txt
echo "Names sorted Z-A:"
cat sorted_names_ZA.txt
# Clean up by removing temporary files
rm names.txt sorted_names_AZ.txt sorted_names_ZA.txt
Interactive Input and File Output Script
Created a BASH script split into two parts to explore user interaction and file handling. Part one engages the user with a playful prompt, collects a rating (1-10), and displays the script’s own source code. Part two requests six numbers, appends them to a file, displays the file’s contents, and cleans up by removing it.
Fall 2023 | CI 121 - Microcomputer Technology for Science | Tools: BASH, Linux shell commands (printf, read, echo, cat, rm)
#!/bin/sh
#Interpreter Line
#Sam Macinsky
#Lab #3 Part One and Two
#Part One
printf "\nThis is my lab. \n"
read -p "On a scale of 1 - 10, how excited are you about my lab? " NUMBER
echo "Only $NUMBER? I expected higher...after all, look how much coding I did for this!: "
cat lab3.sh
#Part Two
printf "Enter six numbers: \n"
read -p "Enter number one: " NUM1
read -p "Enter nubmer two: " NUM2
read -p "Enter number three: " NUM3
read -p "Enter number four: " NUM4
read -p "Enter number five: " NUM5
read -p "Enter number six: " NUM6
echo $NUM1 >> numberfile.txt
echo $NUM2 >> numberfile.txt
echo $NUM3 >> numberfile.txt
echo $NUM4 >> numberfile.txt
echo $NUM5 >> numberfile.txt
echo $NUM6 >> numberfile.txt
cat numberfile.txt
rm numberfile.txt
#I could not, for the life of me, figure out how to put all of those into one line commands. I eventually looked it up online, but it was all about arrays and loops and stuff that's beyond me.
Directory and File Management Script
Developed a BASH script to automate basic file system operations, demonstrating foundational command-line skills. The script prints the current working directory, creates a directory named tempdir, lists its contents in detail, navigates into it, generates a blank file, constructs a nested directory structure (tempdir2/tempdir3/tempdir4), and creates multiple blank files within the deepest directory.
Fall 2023 | CI 121 - Microcomputer Technology for Science | Tools: BASH, Linux shell commands (pwd, mkdir, ls -l, cd, touch)
#!/bin/sh
#Interpreter Line
#Written by Sam Macinsky
#Lab #2
pwd
#1. Print current working directory.
mkdir tempdir
#2. Create directory named tempdir.
ls -l
#3. Long directory listing.
cd tempdir
#4. Change directory into the tempdir directory.
touch blankfile.txt
# 5. Create a blank file called blankfile.txt.
mkdir - p tempdir2/tempdir3/tempdir4
# 6. Create a directory path "tempdir2/tempdir3/tempdir4" using one command.
cd tempdir2/tempdir3/tempdir4
# 7. Traverse into tempdir4.
touch blankfile1.txt blankfile2.txt blankfile3.txt
# 8. Creat 3 blank files called "blankfile1.txt","blankfile2.txt", and "blankfile3.txt"
ls -l
# 9. Show long list (detailed) of directories.
pwd
# 10. Print the current working directory.
Show All BASH Projects
Python Projects
Hide Python Projects
Pet Information Manager
Developed a Python script using a Pet class to manage pet data. The program defines a class with private attributes and methods, collects user input, and displays the data.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), class definition, methods
# Chapter 10 Exercise 1
# Sam Macinsky
class Pet:
def __init__(self, name, animal_type, age):
self.__name = name
self.__animal_type = animal_type
self.__age = age
# The init method initializes the attributes
def set_name(self, name):
self.__name = name
# The set_name method sets the pet's name
def set_animal_type(self, animal_type):
self.__animal_type = animal_type
# The set_animal_type method sets the pet's type
def set_age(self, age):
self.__age = age
# The set_age method sets the pet's age
def get_name(self):
return self.__name
# The get_name method returns the pet's name
def get_animal_type(self):
return self.__animal_type
#The get_animal_type method returns the pet's type
def get_age(self):
return self.__get_age
# The get_age method returns the pet's age
name = input("What is your pet's name? ")
animal_type = input("What type of animal is that? ")
age = input("How old is your pet? ")
# Get the pet's name, type, and age
my_pet = pet.Pet(name, animal_type, age)
# Create an instance of the Pet class
print("Here is the information you entered:")
print("Pet Name: ", my_pet.get_name())
print("Animal Type: ", my_pet.get_animal_type())
print("Age: ", my_pet.get_age())
#Display results
Prime Number Identifier
Crafted a Python script with functions to identify prime numbers in a range. The program checks primality and labels numbers up to a user input as prime or composite.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), int(), range(), for loop, function definitions
# Chapter 7 Exercise 12
# Sam Macinsky
# Define prime checking function (I needed help to work out the math for this):
def is_prime(number):
"""
Check if a given number is prime.
Parameters:
- number (int): The number to check.
Returns:
bool: True if the number is prime, False otherwise.
"""
if number < 2:
return False
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False
return True
# Define prime status display function:
def display_prime_status(numbers):
"""
Display whether each number in the list is prime or composite.
Parameters:
- numbers (list): A list of integers.
"""
for num in numbers:
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is a composite number.")
# Define main function:
def main():
try:
user_input = int(input("Enter an integer greater than 1: "))
if user_input <= 1:
print("Please enter a positive integer greater than 1.")
return
number_list = list(range(2, user_input + 1))
display_prime_status(number_list)
except ValueError:
print("Please enter a valid integer.")
if __name__ == "__main__":
main()
Number Filter by Threshold
Designed a Python script with a function to filter numbers greater than a threshold. The program extracts and displays numbers exceeding a user-specified value from a list.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, list comprehension, function definitions
# Chapter 7 Exercise 6
# Sam Macinsky
# Define number filter function:
def display_numbers_greater_than_n(numbers, n):
"""
Display numbers in the list that are greater than the specified number.
Parameters:
- numbers (list): A list containing numbers.
- n (float): The threshold number.
"""
filtered_numbers = [num for num in numbers if num > n]
if filtered_numbers:
print(f"Numbers greater than {n}: {filtered_numbers}")
else:
print(f"No numbers in the list are greater than {n}.")
Number List Statistics
Built a Python script with a function to analyze a list of 20 numbers. The program computes lowest, highest, total, and average, displaying the results with error handling.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), float(), list operations, min(), max(), sum(), len()
# Chapter 7 Exercise 4
# Sam Macinsky
# Define analyze numbers function:
def analyze_numbers(numbers):
"""
Analyze a list of numbers and display statistics.
Parameters:
- numbers (list): A list containing the entered numbers.
"""
if not numbers:
print("No numbers entered.")
return
# Calculate statistics:
lowest = min(numbers)
highest = max(numbers)
total = sum(numbers)
average = total / len(numbers)
# Display results:
print("Lowest number:", lowest)
print("Highest number:", highest)
print("Total:", total)
print("Average:", average)
# Define main function:
def main():
entered_numbers = []
# Get 20 numbers from the user:
for i in range(20):
try:
number = float(input(f"Enter number #{i + 1}: "))
entered_numbers.append(number)
except ValueError:
print("Please enter a valid number.")
# Analyze and display the statistics:
analyze_numbers(entered_numbers)
if __name__ == "__main__":
main()
Lottery Number Generator
Created a Python script with functions to generate and display a seven-digit lottery number. The program uses list comprehension to create random digits and displays them.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, random module, list comprehension, function definitions
# Chapter 7 Exercise 2
# Sam Macinsky
# Import random (I spent an embarassingly long time forgetting to do this):
import random
# Define number generation function:
def generate_lottery_number():
"""
Generate a seven-digit lottery number.
Returns:
list: A list containing seven random digits.
"""
return [random.randint(0, 9) for _ in range(7)]
# Define results display function:
def display_lottery_number(lottery_number):
"""
Display the contents of the lottery number list.
Parameters:
- lottery_number (list): A list containing the lottery numbers.
"""
print("Lottery Number:")
for digit in lottery_number:
print(digit, end=" ")
print() # Move to the next line after displaying the numbers
# Define main function:
def main():
lottery_number = generate_lottery_number()
display_lottery_number(lottery_number)
if __name__ == "__main__":
main()
Weekly Sales Analyzer
Developed a Python script with a function to calculate total weekly sales. The program collects sales for seven days into a list, computes the total, and handles input errors.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), float(), list operations, sum(), try-except
# Chapter 7 Exercise 1
# Sam Macinsky
# Define the daily sales list function:
def calculate_total_sales(daily_sales):
"""
Calculate the total sales for the week.
Parameters:
- daily_sales (list): A list containing the store's sales for each day of the week.
Returns:
float: The total sales for the week.
"""
return sum(daily_sales)
# Define the main function (days of the week and weekly sales):
def main():
days_of_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
weekly_sales = []
# Loop to gather sales data for each day
for day in days_of_week:
try:
sales = float(input(f"Enter sales for {day}: $"))
weekly_sales.append(sales)
except ValueError:
print("Please enter a valid number.")
# Calculate and display total sales for the week
total_sales = calculate_total_sales(weekly_sales)
print("\nTotal sales for the week: $", total_sales)
if __name__ == "__main__":
main()
Rock Paper Scissors Game
Built a Python script with functions for a rock-paper-scissors game. The program manages gameplay, randomization, and replays using multiple functions.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, random module, input(), function definitions, if-elif-else
# Chapter 5 Exercise 20
# Sam Macinsky
# Define functions
import random
def get_user_choice():
while True:
user_choice = input("Choose rock, paper, or scissors: ").lower()
if user_choice in ["rock", "paper", "scissors"]:
return user_choice
else:
print("Invalid choice. Please choose rock, paper, or scissors.")
def get_computer_choice():
return random.choice(["rock", "paper", "scissors"])
def determine_winner(user_choice, computer_choice):
if user_choice == computer_choice:
return "It's a tie!"
elif (user_choice == "rock" and computer_choice == "scissors") or \
(user_choice == "scissors" and computer_choice == "paper") or \
(user_choice == "paper" and computer_choice == "rock"):
return "You win!"
else:
return "Computer wins!"
# Define Main
def main():
print("Welcome to Rock, Paper, Scissors!")
play_again = "yes"
while play_again.lower() == "yes":
computer_choice = get_computer_choice()
user_choice = get_user_choice()
print(f"Computer chooses: {computer_choice}")
print(determine_winner(user_choice, computer_choice))
play_again = input("Play again? (yes/no): ")
print("Thank you for playing!")
# Call main
main()
Test Score Grader
Developed a Python script with functions to average test scores and assign grades. The program computes the mean of five scores and assigns letter grades, displaying each score’s grade and the average.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), float(), function definitions, if-elif-else
Designed a Python script with a function to convert feet to inches. The program defines a function, takes a feet input, multiplies by 12, and displays the result.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), float(), function definitions, string formatting (f-string)
# Chapter 5 Exercise 9
# Sam Macinsky
# Define functions
def feet_to_inches(feet):
inches = feet * 12
return inches
def main():
feet = float(input("Enter a number of feet: "))
inches = feet_to_inches(feet)
print(f"{feet} feet is equal to {inches} inches.")
# Call the main function
main()
Modular Tax Calculator
Built a Python script with multiple functions to calculate and display purchase taxes. The program uses functions to handle input, compute taxes, and format output.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), float(), function definitions, string formatting (f-string)
Created a Python script with a function to convert kilometers to miles. The program defines a function, takes a kilometer input, converts it, and displays the result.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), float(), function definition, string formatting (f-string)
# Chapter 5 Exercise 1
# Sam Macinsky
def kilometers_to_miles(kilometers):
miles = kilometers * 0.6214
return miles
# Ask user for input in kilometers
kilometers = float(input("Enter a distance in kilometers: "))
# Call the function to convert kilometers to miles
miles = kilometers_to_miles(kilometers)
# Print the converted distance in miles
print(f"{kilometers} kilometers is equal to {miles} miles.")
Star Pattern Printer
Developed a Python script using nested for loops to print a decreasing star pattern. The program outputs a right-aligned triangle of stars, reducing from 7 to 1 per row.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, nested for loops, print() with end parameter
#Chapter 4 Exercise 13
for i in range (7):
for j in range (i,7):
print ("*", end = " ")
print()
Penny Doubling Salary Simulator
Crafted a Python script to simulate a salary doubling daily from one penny using a for loop. The program takes a number of days, calculates daily pay, and displays a table with cumulative totals.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), int(), for loop, string formatting (format())
#Chapter 4 Exercise 7
# Ask the user for the number of days
num_days = int(input("Enter the number of days: "))
# Initial salary is one penny
total_pay = 0.01
print("Day\tSalary")
print("1\t$0.01")
# Double the salary
for day in range(2, num_days + 1):
salary = total_pay * 2
total_pay += salary
print(f"{day}\t${salary:.2f}")
print("\nTotal pay after", num_days, "days: $" + format(total_pay, '.2f'))
Celsius to Fahrenheit Table Generator
Designed a Python script to generate a Celsius-to-Fahrenheit conversion table using a for loop. The program converts temperatures from 0 to 20°C, displaying each pair with formatted precision.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, for loop, arithmetic operations, string formatting (f-string)
#Chapter 4 Exercise 6: Celsius to Fahrenheit Table
print("Celsius:", "\t", "Fahrenheit:")
print("___________________________")
print(" ")
for celsius in range (21):
fahrenheit = (9/5) * celsius + 32
print(f"{celsius} \t\t {fahrenheit:.2f}")
Distance Traveled Calculator
Built a Python script to compute distance traveled over time using a for loop. The program takes speed and time, then calculates and displays distance for each hour.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), float(), int(), for loop, string formatting
#Chapter 4 Exercise 4
speed = float(input("Enter speed: "))
time = int(input("Time: "))
for i in range(time):
distance = (i+1) * speed
print(i+1, "\t", distance)
Calories Burned Estimator
Developed a Python script to estimate calories burned over time intervals using a for loop. The program calculates calories (4.2 per minute) for specified minutes and displays each result.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, for loop, arithmetic operations, string formatting (f-string)
#Chapter Four Exercise Two: Calories Burned
#Store calories per minute
CPM = 4.2
calories_burned = 0
for minutes in range (10, 31, 5):
calories_burned = CPM * minutes
print(f"Minutes: {minutes} Calories Burned: {calories_burned}")
Bug Collection Tracker
Created a Python script using a for loop to track bugs collected over five days. The program prompts for daily counts, accumulates them, and displays the total.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), int(), for loop, string formatting (f-string)
#Chapter 4 Exercise 1: Bug Collector
total = 0
for i in range (5):
bugs =int(input(f"Enter the number of bugs collected for day #{i+1}: " ))
total = total + bugs
print(f"The total number of bugs collected is {total}.")
WiFi Troubleshooting Flowchart
Built a Python script simulating a WiFi troubleshooting flowchart. The program guides the user through steps, asking yes/no questions and tracking resolution status with nested conditionals.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), if-else, boolean variables
# Initialize a variable to track whether the problem is fixed
problem_fixed = False
print("Welcome to Macinsky Enterprises' free WiFi Connectivity Troubleshooter!")
# Step 1: Reboot the computer and try to connect
reboot_computer = input("Reboot the computer and try to connect. Did that fix the problem? (yes or no): ")
if reboot_computer == "yes":
problem_fixed = True
else:
# Step 2: Reboot the router and try to connect
reboot_router = input("Reboot the router and try to connect. Did that fix the problem? (yes or no): ")
if reboot_router == "yes":
problem_fixed = True
else:
# Step 3: Make sure the cables between the router and modem are plugged in firmly
check_cables = input("Make sure the cables between the router and modem are plugged in firmly. Did that fix the problem? (yes or no): ")
if check_cables == "yes":
problem_fixed = True
else:
# Step 4: Move the router to a new location and try to connect
move_router = input("Move the router to a new location and try to connect. Did that fix the problem? (yes or no): ")
if move_router == "yes":
problem_fixed = True
else:
# Step 5: Get a new router
get_new_router = input("Get a new router. Did that fix the problem? (yes or no): ")
if get_new_router == "yes":
problem_fixed = True
# Display final message based on whether the problem is fixed or not
if problem_fixed:
print("Thank you for using Macinsky Enterprises' free WiFi Connectivity Troubleshooter! Enjoy your WiFi connection!")
else:
print("The problem could not be fixed. Please contact your service provider for further assistance.")
Shipping Charge Estimator
Crafted a Python script to determine shipping charges based on package weight. The program takes a weight in pounds and assigns a rate based on tiers, displaying the result formatted.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), float(), if-elif-else, string formatting (f-string)
# Get the weight of the package from user
weight = float(input("Enter the weight of the package (in pounds): "))
# Calculate the shipping charges
if weight <= 2:
shipping_charge = 1.50
elif weight <= 6:
shipping_charge = 3.00
elif weight <= 10:
shipping_charge = 10.00
else:
shipping_charge = 4.75
# Display the shipping charges to the user
print(f"The shipping charge for a {weight} pound package is ${shipping_charge:.2f}")
Software Discount Calculator
Developed a Python script to calculate software package discounts based on quantity. The program takes the number of packages, applies tiered discounts, and displays subtotal, discount, and total.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), int(), if-elif-else, arithmetic operations, string formatting (f-string)
#Prompt for the number of packages from the User
package_price = 99.00
#Calculate subtotal based on number of packages
num_packages = int(input("Enter the number of packages: "))
subtotal = package_price * num_packages
#Check for discount
if num_packages <10:
discount = 0
elif num_packages >= 10 and num_packages <= 19:
discount = subtotal * 0.10
elif num_packages >= 20 and num_packages <=49:
discount = subtotal * 0.20
elif num_packages >= 50 and num_packages <=99:
discount = subtotal * 0.30
elif num_packages >= 100:
discount = subtotal * 0.40
#Calculate total
total = subtotal - discount
#Output amounts
print(f"The subtotal is: ${subtotal:.2f}")
print(f"The amount of the discount is: ${discount:.2f}")
print(f"The total after the discount is: ${total:.2f}")
Roman Numeral Converter
Designed a Python script to convert numbers (1-10) to Roman numerals using conditionals. The program prompts for a number, maps it to its Roman numeral equivalent, and handles invalid inputs with an error message.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), int(), if-elif-else
#Prompt the user for a number between 1 and 10
number = int(input("Pick a number between 1 and 10: "))
#Correspond input with a Roman Numeral
if number == 1:
print("The Roman Numeral is I")
elif number == 2:
print("The Roman Numeral is II")
elif number == 3:
print("The Roman Numeral is III")
elif number == 4:
print("The Roman Numeral is IV")
elif number == 5:
print("The Roman Numeral is V")
elif number == 6:
print("The Roman Numeral is VI")
elif number == 7:
print("The Roman Numeral is VII")
elif number == 8:
print("The Roman Numeral is VIII")
elif number == 9:
print("The Roman Numeral is IX")
elif number == 10:
print("The Roman Numeral is X")
else:
print("You didn't enter a number between 1 and 10")
Rectangle Area Comparator
Built a Python script to compare the areas of two rectangles. The program collects length and width for two rectangles, calculates their areas, and uses if-elif-else logic to determine which is larger or if they’re equal.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), float(), arithmetic operations, if-elif-else
# Get the dimensions of the first rectangle
length1 = float(input("Enter the length of the first rectangle: "))
width1 = float(input("Enter the width of the first rectangle: "))
# Calculate the area of the first rectangle
area1 = length1 * width1
# Get the dimensions of the second rectangle
length2 = float(input("Enter the length of the second rectangle: "))
width2 = float(input("Enter the width of the second rectangle: "))
# Calculate the area of the second rectangle
area2 = length2 * width2
# Compare the areas and print the result
if area1 > area2:
print("The first rectangle has a greater area.")
elif area2 > area1:
print("The second rectangle has a greater area.")
else:
print("Both rectangles have the same area.")
Day of the Week Selector
Created a Python script using if-elif-else statements to map a number (1-7) to a day of the week. The program prompts for a number, matches it to a day, and provides error handling for invalid inputs.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), int(), if-elif-else
#Prompt the user for a number between 1 and 7
dayofweek = int(input("Pick a number between 1 and 7: "))
#Correspond input with day of week
if dayofweek == 1:
print("The day is Monday")
elif dayofweek == 2:
print("The day is Tuesday")
elif dayofweek == 3:
print("The day is Wednesday")
elif dayofweek == 4:
print("The day is Thursday")
elif dayofweek == 5:
print("The day is Friday")
elif dayofweek == 6:
print("The day is Saturday")
elif dayofweek == 7:
print("The day is Sunday")
else:
print("You didn't enter a number between 1 and 7")
Celsius to Fahrenheit Converter
Developed a Python script to convert Celsius to Fahrenheit. The program takes a Celsius temperature, applies the conversion formula (9/5 * C + 32), and displays the Fahrenheit result with two decimal places.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), float(), arithmetic operations, string formatting (f-string)
#Prompt for Celsius Temperature
c = float(input('Enter Temperature in Celsius: '))
#Convert
f = ((9/5)*c) + 32
#Display
print(f"{c} degrees C is : {f:.2f} degrees F")
Restaurant Bill Calculator
Crafted a Python script to compute a restaurant bill, including tax and tip. The program prompts for a meal cost, calculates a 7% tax and 18% tip, and sums everything into a total, displaying each component.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), float(), arithmetic operations, string formatting (f-string)
#Get input for meal
meal= float(input('Enter amount for meal: '))
#Calculate
tax = meal * 0.07
tip = meal * 0.18
total = meal + tax + tip
#Display
print(f"Subotal: ${meal:.2f}")
print(f"Tax: ${tax:.2f}")
print(f"Tip: ${tip:.2f}")
print(f"Total: ${total:.2f}")
MPG Calculator
Designed a Python script to compute miles per gallon (MPG) from user inputs. The program collects miles driven and gallons used, calculates MPG, and displays it with two decimal places.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), float(), arithmetic operations, string formatting (f-string)
#Prompt for miles driven and fuel used
miles_driven = float(input('Enter miles driven: '))
gallons_used = float(input('Enter gallons of fuel used: '))
#Calculate MPG
mpg = miles_driven / gallons_used
#Display results
print(f'Your MPG is: {mpg:.2f}')
Tax and Total Calculator
Built a Python script to calculate taxes and total cost for a purchase. The program takes a purchase amount, computes a 5% state tax and 2.5% county tax, sums them, and adds to the purchase price, displaying all values formatted.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), float(), arithmetic operations, string formatting (f-string)
#Ask for the amount of purchase
purchase = float(input('Enter Purchase Price:$ '))
#Calculate taxes and sale
state_tax = 0.05 * purchase
county_tax = 0.025 *purchase
total_tax = state_tax + county_tax
total = purchase + total_tax
#Display results
print(f'Purchase: ${purchase:.2f}')
print(f'State Tax: ${state_tax:.2f}')
print(f'County Tax: ${county_tax:.2f}')
print(f'Total: ${total:.2f}')
Retail Checkout Simulator
Created a Python script simulating a retail checkout. The program collects prices for five items, calculates the subtotal, applies a 7% sales tax, and computes the total cost, displaying each value with two decimal places.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), float(), arithmetic operations, string formatting (f-string)
Developed a Python script to compute projected profit from user-input sales. The program collects a total sales figure, calculates a 23% profit margin, and displays it formatted to two decimal places.
Fall 2023 | CI 110 - Principles of Programming | Tools: Python, input(), float(), string formatting (f-string)
# Get the projected total sales from the user
total_sales = float(input('Enter projected total sales: '))
# Calculate the profit (23 percent of total sales)
profit = 0.23 * total_sales
# Display the calculated profit
print(f'Profit from projected total sales: ${profit:.2f}')
Show All Python Projects
C++ Projects
Hide C++ Projects
Salesperson Salary Range Analyzer
Modified a C++ program to categorize salesperson salaries into predefined ranges using arrays, tallying earnings across 10 ranges.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <iomanip>, <array>, for loops, std::setw
// Sam Macinsky
// 11/29/2024
// Saleperson Salary Ranges
/*
#include <iostream>
#include <iomanip>
int main() {
int SALESPEOPLE;
// Input number of salespeople
std::cout << "Enter the number of salespeople: ";
std::cin >> SALESPEOPLE;
const int BASE_SALARY = 200;
const double COMMISSION_RATE = 0.09;
double salesArray[SALESPEOPLE];
int salaryRanges[SALESPEOPLE] = {0}; // Array to track salary ranges
// Input sales for each salesperson
std::cout << "Enter the weekly sales for " << SALESPEOPLE << " salespeople:" << std::endl;
for (int i = 0; i < SALESPEOPLE; ++i) {
std::cout << "Salesperson " << (i + 1) << ": ";
std::cin >> salesArray[i];
}
// Calculate salaries and track ranges
for (int i = 0; i < SALESPEOPLE; ++i) {
int commission = static_cast<int>(salesArray[i] * COMMISSION_RATE);
int salary = BASE_SALARY + commission;
for (int j = 0; j < SALESPEOPLE; ++j) {
if (salary < 300 + 100 * j) {
++salaryRanges[j];
break;
}
}
}
// Display results
std::cout << "\nSalary Range Distribution:" << std::endl;
int lowerBound = 200;
for (int i = 0; i < SALESPEOPLE; ++i) {
std::cout << "$" << lowerBound << " - $" << (lowerBound + 99)
<< ": " << salaryRanges[i] << " salespeople" << std::endl;
lowerBound += 100;
}
}
*/
#include <iostream>
#include <iomanip>
#include <array>
int main() {
int SALESPEOPLE;
// Input number of salespeople
std::cout << "Enter the number of salespeople: ";
std::cin >> SALESPEOPLE;
const int BASE_SALARY = 200;
const double COMMISSION_RATE = 0.09;
// Fixed-size array for specific salary ranges
const int NUM_RANGES = 10;
std::array<int, NUM_RANGES> salaryRanges = {0};
// Sales array for input
std::array<int, NUM_RANGES * 10> salesArray;
// Input sales for each salesperson
std::cout << "Enter the weekly sales for " << SALESPEOPLE << " salespeople:" << std::endl;
for (int i = 0; i < SALESPEOPLE; ++i) {
std::cout << "Salesperson " << (i + 1) << ": ";
std::cin >> salesArray[i];
}
// Calculate salaries and track ranges
for (int i = 0; i < SALESPEOPLE; ++i) {
int commission = static_cast<int>(salesArray[i] * COMMISSION_RATE);
int salary = BASE_SALARY + commission;
// Determine salary range
if (salary >= 1000) {
++salaryRanges[9];
} else {
int rangeIndex = (salary - 100) / 100;
++salaryRanges[rangeIndex];
}
}
// Display results
std::cout << "\nSalary Range Distribution:" << std::endl;
// Predefined ranges
std::array<std::string, NUM_RANGES> ranges = {
"$100 - $199",
"$200 - $299",
"$300 - $399",
"$400 - $499",
"$500 - $599",
"$600 - $699",
"$700 - $799",
"$800 - $899",
"$900 - $999",
"$1000+"
};
// Print ranges and their counts
for (int i = 0; i < NUM_RANGES; ++i) {
std::cout << ranges[i] << ": " << salaryRanges[i] << " salespeople" << std::endl;
}
}
Duplicate Eliminator
Built a C++ program using an array to eliminate duplicates from 20 user-input numbers, checking with nested loops.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <array>, nested for loops, std::cin, std::cout
// Sam Macinsky
// 12/03/2024
// Duplicate Elimination
#include <iostream>
#include <array>
int main() {
const int SIZE = 20;
std::array<int, SIZE> uniqueNumbers = {0};
int uniqueCount = 0;
std::cout << "Enter 20 numbers:" << std::endl;
for (int i = 0; i < SIZE; ++i) {
int input;
std::cout << "Number " << (i + 1) << ": ";
std::cin >> input;
// Check for duplicates
bool isDuplicate = false;
for (int j = 0; j < uniqueCount; ++j) {
if (uniqueNumbers[j] == input) {
isDuplicate = true;
break;
}
}
// Store if not a duplicate
if (!isDuplicate) {
uniqueNumbers[uniqueCount++] = input;
}
}
std::cout << "\nUnique numbers entered:" << std::endl;
for (int i = 0; i < uniqueCount; ++i) {
std::cout << uniqueNumbers[i] << " ";
}
std::cout << std::endl;
}
Factorial Visualizer
Modified a C++ factorial program to visualize recursion with depth tracing, computing 0! to 10! with indented steps.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <iomanip>, recursive function, for loop, std::setw
// Sam Macinsky
// 11/29/2024
// Visualizing Recursion
/*
#include <iostream>
#include <iomanip>
unsigned long factorial (unsigned long); // function prototype
int main() {
// calculate the factorials of 0 through 10
for (unsigned int counter{0}; counter <= 10; ++counter) {
std::cout << std::setw(2) << counter << "! = " << factorial(counter) << std::endl;
}
}
// recursive definition of function factorial
unsigned long factorial(unsigned long number) {
if (number <= 1) { // test for base case
return 1;
}
else { // recursions step
return number * factorial(number - 1);
}
}
*/
#include <iostream>
#include <iomanip>
#include <string>
unsigned long factorial(unsigned long, int = 0); // function prototype with depth parameter
int main() {
// calculate the factorials of 0 through 10
for (unsigned int counter{0}; counter <= 10; ++counter) {
std::cout << std::setw(2) << counter << "! = " << factorial(counter) << std::endl;
}
}
// recursive definition of function factorial with tracing
unsigned long factorial(unsigned long number, int depth) {
// Create indentation string based on recursion depth
std::string indent(depth * 2, ' ');
// Print local variable and recursive call parameter
std::cout << indent << "Calculating factorial(" << number << ")" << std::endl;
if (number <= 1) { // test for base case
std::cout << indent << "Base case: returning 1" << std::endl;
return 1;
}
else { // recursions step
unsigned long result = number * factorial(number - 1, depth + 1);
std::cout << indent << "Returning: " << number << " * factorial("
<< number - 1 << ") = " << result << std::endl;
return result;
}
}
Pass-by-Value vs. Reference Demo
Developed a C++ program to compare pass-by-value and pass-by-reference parameter passing, tripling a value with both methods.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, function definitions, pass-by-value, pass-by-reference, std::cout
// Sam Macinsky
// 11/22/2024
// Pass by Value/Reference
#include <iostream>
int tripleByValue(int number) {
number = number * 3;
return number;
}
void tripleByReference(int& number) {
number = number * 3;
}
int main() {
int count = 1;
std::cout << "Original value of count: " << count << std::endl;
int result = tripleByValue(count);
std::cout << "After tripleByValue, count is: " << count << std::endl;
std::cout << "Value returned by tripleByValue: " << result << std::endl << std::endl;
std::cout << "Original value of count: " << count << std::endl;
tripleByReference(count);
std::cout << "After tripleByReference, count is: " << count << std::endl;
}
Generic Maximum Finder
Created a C++ program with a function template maximum to find the larger of two values, testing with integers, characters, and doubles.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, function template, if-else, std::cout
Modified a C++ craps game to include wagering and casino chatter, managing gameplay and bets with a $1000 bank balance.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <cstdlib>, <ctime>, <string>, while loops, function definitions, enum class
// Sam Macinsky
// 11/22/2024
// Craps Game Modification
/*
#include <iostream>
#include <cstdlib>
#include <ctime>
unsigned int rollDice (); // Rolls dice, calculates and displays sum
int main() {
// Scoped enumeration with constants that represent the game status
enum class Status {CONTINE, WON, LOST}; // All caps in constants
// Randomize random number generator using current time
srand(static_cast<unsigned int>(time(0)));
unsigned int myPoint{0}; // Point if no win or loss on first roll
Status gameStatus; // Can be CONTINUE, WON, or LOST
unsigned int sumOfDice{rollDice()}; // First roll of the dice
// Determine game status and point (if needed) based on first roll
switch (sumOfDice){
case 7: // Win with 7 on first roll
case 11: // Win with 11 on first roll
gameStatus = Status::WON;
break;
case 2: // Lose with 2 on first roll
case 3: // Lose with 3 on first roll
case 12: // Lose with 12 on first roll
gameStatus = Status::LOST;
break;
default: // Did not win or lose, so remember point
gameStatus = Status::CONTINE; // Game is not over
myPoint = sumOfDice; // Remember the point
std::cout << "Point is: " << myPoint << std::endl;
break; // Optional at end of switch
}
// While game is not complete
while (Status::CONTINE == gameStatus) { // Not WON or LOST
sumOfDice = rollDice(); // Roll dice again
// Determine game status
if (sumOfDice == myPoint){
gameStatus = Status::WON;
}
else {
if (sumOfDice == 7) { // Lose by rolling 7 before point
gameStatus = Status::LOST;
}
}
}
// Display won or lost message
if (Status::WON == gameStatus){
std::cout << "Player wins!" << std::endl;
}
else{
std::cout << "Player loses!" << std::endl;
}
}
// Roll dice, calculate sum and display results
unsigned int rollDice() {
int die1{1 + rand() % 6}; // First die roll
int die2{1 + rand() % 6}; // Second die roll
int sum{die1 + die2}; // Compute sum of die values
// Display results of this roll
std::cout << "Player rolled: " << die1 << " + " << die2 << " = " << sum << std::endl;
return sum;
}
*/
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
// Function prototypes
unsigned int rollDice();
bool playCraps();
std::string getCasinoChatter(double bankBalance, double wager);
int main() {
// Initialize random number generator
srand(static_cast<unsigned int>(time(0)));
double bankBalance{1000.0};
char playAgain{'y'};
std::cout << "Welcome to the THAW Casino! You're starting with $" << bankBalance << std::endl;
while (playAgain == 'y' && bankBalance > 0) {
double wager;
// Get and validate wager
do {
std::cout << "\nEnter your wager ($1-$" << bankBalance << "): $";
std::cin >> wager;
if (wager > bankBalance) {
std::cout << "Sorry, that bet is too big for your budget!" << std::endl;
}
else if (wager <= 0) {
std::cout << "Come on, you have to bet something!" << std::endl;
}
} while (wager > bankBalance || wager <= 0);
// Display some casino chatter based on the wager
std::cout << getCasinoChatter(bankBalance, wager) << std::endl;
// Play one game of craps
bool won = playCraps();
// Update bank balance based on game result
if (won) {
bankBalance += wager;
std::cout << "\nCongratulations! Your new balance is $" << bankBalance << std::endl;
if (bankBalance >= 2000) {
std::cout << "You're up big! Maybe it's time to cash in those chips!" << std::endl;
}
}
else {
bankBalance -= wager;
std::cout << "\nTough luck! Your new balance is $" << bankBalance << std::endl;
if (bankBalance == 0) {
std::cout << "Sorry, you busted!" << std::endl;
break;
}
}
if (bankBalance > 0) {
std::cout << "\nWould you like to play again? (y/n): ";
std::cin >> playAgain;
}
}
std::cout << "\nThanks for playing! You're leaving with $" << bankBalance << std::endl;
return 0;
}
// Function to play one game of craps, returns true if player wins
bool playCraps() {
enum class Status {CONTINUE, WON, LOST};
unsigned int myPoint{0};
Status gameStatus;
unsigned int sumOfDice{rollDice()};
// First roll
switch (sumOfDice) {
case 7:
case 11:
gameStatus = Status::WON;
break;
case 2:
case 3:
case 12:
gameStatus = Status::LOST;
break;
default:
gameStatus = Status::CONTINUE;
myPoint = sumOfDice;
std::cout << "Point is: " << myPoint << std::endl;
break;
}
// Continue rolling until game is complete
while (Status::CONTINUE == gameStatus) {
sumOfDice = rollDice();
if (sumOfDice == myPoint) {
gameStatus = Status::WON;
}
else if (sumOfDice == 7) {
gameStatus = Status::LOST;
}
}
return gameStatus == Status::WON;
}
// Roll dice, calculate sum and display results
unsigned int rollDice() {
int die1{1 + rand() % 6};
int die2{1 + rand() % 6};
int sum{die1 + die2};
std::cout << "Player rolled: " << die1 << " + " << die2 << " = " << sum << std::endl;
return sum;
}
// Generate casino chatter based on bank balance and wager
std::string getCasinoChatter(double bankBalance, double wager) {
if (wager == bankBalance) {
return "On behalf of THAW Casino, thank you for your generous dona- I mean, your exciting wager.";
}
else if (wager >= bankBalance * 0.75) {
return "That's...a large wager. I hope you know what you're doing.";
}
else if (wager <= bankBalance * 0.1) {
return "That's it? Fortune favors the bold!";
}
else if (bankBalance >= 1500) {
return "Must be nice to have that much money to risk!";
}
else if (bankBalance <= 500) {
return "Don't worry, your luck's about to turn around!";
}
else {
return "Good luck!";
}
}
Multiplication Tutor
Developed a C++ program with a generateNewQuestion function for a multiplication tutor, generating random problems and checking answers in an infinite loop.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <cstdlib>, <ctime>, while loop, function definition, std::rand
Implemented a C++ number guessing game in a header file with a driver program, generating a random number (1-1000) and offering replay.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <cstdlib>, <ctime>, while loops, function definition, header file (Guess.h)
#ifndef NUMBER_GUESS_H
#define NUMBER_GUESS_H
#include <iostream>
#include <cstdlib>
#include <ctime>
void playNumberGuessingGame() {
char playAgain;
do {
// Seed the random number generator
srand(time(0));
// Generate random number between 1 and 1000
int secretNumber = 1 + rand() % 1000;
int guess;
int guessCount = 0;
std::cout << "I have a number between 1 and 1000." << std::endl;
std::cout << "Can you guess the number?" << std::endl;
std::cout << "Please type your first guess: ";
// Corrected loop structure
while (guess != secretNumber) {
std::cin >> guess;
guessCount++;
if (guess == secretNumber) {
// Correct guess
std::cout << "Excellent! You guessed the number!" << std::endl;
// Count guesses
if (guessCount <= 10) {
if (guessCount == 10) {
std::cout << "Aha! You know the secret!" << std::endl;
} else {
std::cout << "Either you know the secret or you got lucky!" << std::endl;
}
} else {
std::cout << "You should be able to do better than that!" << std::endl;
}
break;
}
else if (guess < secretNumber) {
std::cout << "Too low. Try again." << std::endl;
}
else {
std::cout << "Too high. Try again." << std::endl;
}
}
// Ask to play again
std::cout << "Would you like to play again? (y or n): ";
std::cin >> playAgain;
} while (playAgain == 'y' || playAgain == 'Y');
}
#endif
// Sam Macinsky
// 11/22/2024
// Guess the Number Modification
#include "Guess.h"
int main() {
playNumberGuessingGame();
return 0;
}
Prime Number Finder
Created a C++ program with two prime-checking functions to list primes up to 10,000, using both full divisor checks and square root optimization.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <cmath>, for loops, function definitions, std::sqrt
// Sam Macinsky
// 11/19/2024
// Prime Numbers
#include <iostream>
#include <cmath>
// First method
bool isPrimeMethod1(int number) {
if (number < 2) {
return false;
}
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
// Second method
bool isPrimeMethod2(int number) {
if (number < 2) {
return false;
}
if (number == 2) {
return true;
}
if (number % 2 == 0) {
return false;
}
int squareRoot = sqrt(number);
for (int i = 3; i <= squareRoot; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
int main() {
const int UPPER_LIMIT = 10000;
std::cout << "Finding prime numbers from 2 to " << UPPER_LIMIT << std::endl << std::endl;
std::cout << "Method 1 (checking all numbers):" << std::endl;
for (int number = 2; number <= UPPER_LIMIT; number++) {
if (isPrimeMethod1(number)) {
std::cout << number << " ";
}
}
std::cout << std::endl << std::endl << "Method 2 (checking up to square root):" << std::endl;
for (int number = 2; number <= UPPER_LIMIT; number++) {
if (isPrimeMethod2(number)) {
std::cout << number << " ";
}
}
std::cout << std::endl;
}
Parking Charge Calculator
Designed a C++ program with a calculateCharges function to compute parking fees for three cars, applying a base fee, hourly rate, and cap.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <iomanip>, <cmath>, function definition, std::ceil, std::setw
Created a C++ program with functions to generate Celsius-to-Fahrenheit and Fahrenheit-to-Celsius tables using for loops and .
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <iomanip>, for loops, function definitions, std::setw
// Sam Macinsky
// 11/19/2024
// Celsius and Fahrenheit Temperatures
#include <iostream>
#include <iomanip>
int celsius(int fahrenheit) {
return (5 * (fahrenheit - 32)) / 9;
}
int fahrenheit(int celsius) {
return (9 * celsius) / 5 + 32;
}
int main() {
std::cout << "Celsius to Fahrenheit Table\n";
std::cout << "==========================\n\n";
std::cout << std::setw(10) << "Celsius"
<< std::setw(15) << "Fahrenheit" << "\n";
std::cout << "-------------------------\n";
for (int c = 0; c <= 100; c += 10) {
std::cout << std::setw(10) << c
<< std::setw(15) << fahrenheit(c) << "\n";
}
std::cout << "\n\nFahrenheit to Celsius Table\n";
std::cout << "==========================\n\n";
std::cout << std::setw(12) << "Fahrenheit"
<< std::setw(13) << "Celsius" << "\n";
std::cout << "-------------------------\n";
for (int f = 32; f <= 212; f += 20) {
std::cout << std::setw(12) << f
<< std::setw(13) << celsius(f) << "\n";
}
}
Twelve Days of Christmas Song
Built a C++ program to print the "Twelve Days of Christmas" lyrics using nested switch statements within a for loop.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <string>, for loop, switch, std::cout
// Sam Macinsky
// 11/05/2024
// Twelve Days of Christmas Song
#include <iostream>
#include <string>
int main() {
for (int day = 1; day <= 12; day++) {
std::cout << "On the ";
switch (day) {
case 1:
std::cout << "first";
break;
case 2:
std::cout << "second";
break;
case 3:
std::cout << "third";
break;
case 4:
std::cout << "fourth";
break;
case 5:
std::cout << "fifth";
break;
case 6:
std::cout << "sixth";
break;
case 7:
std::cout << "seventh";
break;
case 8:
std::cout << "eighth";
break;
case 9:
std::cout << "ninth";
break;
case 10:
std::cout << "tenth";
break;
case 11:
std::cout << "eleventh";
break;
case 12:
std::cout << "twelfth";
break;
}
std::cout << " day of Christmas, my true love gave to me: ";
switch (day) {
case 12:
std::cout << "Twelve drummers drumming, ";
case 11:
std::cout << "Eleven pipers piping, ";
case 10:
std::cout << "Ten lords a-leaping, ";
case 9:
std::cout << "Nine ladies dancing, ";
case 8:
std::cout << "Eight maids a-milking, ";
case 7:
std::cout << "Seven swans a-swimming, ";
case 6:
std::cout << "Six geese a-laying, ";
case 5:
std::cout << "Five gold rings, ";
case 4:
std::cout << "Four calling birds, ";
case 3:
std::cout << "Three French hens, ";
case 2:
std::cout << "Two turtle doves, ";
case 1:
std::cout << "A partridge in a pear tree." << std::endl << std::endl;
break;
}
}
}
Peter Minuit Investment Simulator
Modified a C++ program to simulate the growth of a $24 investment over 398 years at various rates using a for loop.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <iomanip>, <cmath>, for loop, std::pow
// Sam Macinsky
// 11/05/2024
// Peter Minuit Problem
#include <iostream>
#include <iomanip>
#include <cmath>
int main() {
/*
std::cout << std::fixed << std::setprecision(2);
double principal{1000.00};
double rate{0.05};
std::cout << "Initial principal: " << principal << std::endl;
std::cout << " Interest rate:" << rate << std::endl;
std::cout << "\nYear" << std::setw(20) << "Amount on deposit" << std::endl;
for (unsigned int year{1}; year <= 10; year++){
double amount = principal * pow(1.0 + rate, year);
std::cout << std::setw(4) << year << std::setw(20) << amount << std::endl;
}
*/
\
std::cout << std::fixed << std::setprecision(2);
double principal{24.00};
unsigned int years{398};
std::cout << "Initial principal: $" << principal << std::endl;
std::cout << "\nInterest Rate" << std::setw(25) << "Amount on deposit" << std::endl;
for (double rate{0.05}; rate <= 0.10; rate += 0.01) {
double amount = principal * pow(1.0 + rate, years);
std::cout << std::setw(10) << (rate * 100) << "%" << std::setw(25) << amount << std::endl;
}
}
Global Warming Quiz
Developed a C++ interactive quiz on global warming using conditionals, asking five multiple-choice questions and providing feedback based on score.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <string>, if statements, std::cin, std::cout
// Sam Macinsky
// 11/05/2024
// Global Warming Quiz
#include <iostream>
#include <string>
int main() {
int correct_answers = 0;
// Question 1
std::cout << "What is the main cause of global warming?" << std::endl;
std::cout << "1) Natural climate changes" << std::endl;
std::cout << "2) Too much sun activity" << std::endl;
std::cout << "3) Big Business moved their industrial plants to the third world where emissions aren't regulated." << std::endl;
std::cout << "4) Hole in the ozone layer" << std::endl;
int q1_answer;
std::cin >> q1_answer;
// Question 2
std::cout << "What's one problem with Al Gore's movie about global warming?" << std::endl;
std::cout << "1) It exaggerates the problem" << std::endl;
std::cout << "2) Not enough proof" << std::endl;
std::cout << "3) It's too political" << std::endl;
std::cout << "4) All of these" << std::endl;
int q2_answer;
std::cin >> q2_answer;
// Question 3
std::cout << "Which of these is an argument used by people who don't believe in global warming?" << std::endl;
std::cout << "1) Temperatures have gone up" << std::endl;
std::cout << "2) CO2 levels are higher" << std::endl;
std::cout << "3) Climate models predict future warming" << std::endl;
std::cout << "4) Climate has changed naturally before" << std::endl;
int q3_answer;
std::cin >> q3_answer;
// Question 4
std::cout << "What impact of global warming is debated a lot?" << std::endl;
std::cout << "1) Sea levels rising" << std::endl;
std::cout << "2) More extreme weather" << std::endl;
std::cout << "3) Animals going extinct" << std::endl;
std::cout << "4) The effects are exaggerated" << std::endl;
int q4_answer;
std::cin >> q4_answer;
// Question 5
std::cout << "What can people do to reduce their carbon footprint?" << std::endl;
std::cout << "1) Fly more" << std::endl;
std::cout << "2) Eat more meat" << std::endl;
std::cout << "3) Use more electricity" << std::endl;
std::cout << "4) Hold Big Business accountable for their hypocricy" << std::endl;
int q5_answer;
std::cin >> q5_answer;
// Check answers and keep track of correct answers
if (q1_answer == 3) {
correct_answers++;
}
if (q2_answer == 4) {
correct_answers++;
}
if (q3_answer == 4) {
correct_answers++;
}
if (q4_answer == 4) {
correct_answers++;
}
if (q5_answer == 4) {
correct_answers++;
}
// Provide recommendations based on the user's score
if (correct_answers == 5) {
std::cout << "Great job, you really know about global warming!" << std::endl;
} else if (correct_answers >= 3) {
std::cout << "Good, you have a decent understanding of global warming." << std::endl;
} else {
std::cout << "You should learn more about global warming. Try these websites:" << std::endl;
std::cout << "- https://climate.gov/" << std::endl;
std::cout << "- https://www.ipcc.ch/" << std::endl;
std::cout << "- https://skepticalscience.com/" << std::endl;
std::cout << "- https://infowars.com/" << std::endl;
}
}
Triangle Patterns Generator
Created a C++ program to print four triangle patterns (A-D) using nested for loops, generating increasing, decreasing, right-aligned, and left-aligned asterisk triangles.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, nested for loops, std::cout
// Sam Macinsky
// 11/06/2024
// Triangle Printing Program
#include <iostream>
int main() {
// Pattern A
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= i; j++) {
std::cout << "*";
}
std::cout << "\n";
}
std::cout << "\n";
// Pattern B
for (int i = 10; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
std::cout << "*";
}
std::cout << "\n";
}
std::cout << "\n";
// Pattern C
for (int i = 10; i >= 1; i--) {
for (int k = 1; k <= 10 - i; k++) {
std::cout << " ";
}
for (int j = 1; j <= i; j++) {
std::cout << "*";
}
std::cout << "\n";
}
std::cout << "\n";
// Pattern D
for (int i = 1; i <= 10; i++) {
for (int k = 1; k <= 10 - i; k++) {
std::cout << " ";
}
for (int j = 1; j <= i; j++) {
std::cout << "*";
}
std::cout << "\n";
}
}
Hollow Square Printer
Designed a C++ program to print a hollow square of asterisks with user-specified size (1-20) using nested for loops and input validation.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, nested for loops, do-while, std::cin, std::cout
// Sam Macinsky
// 10/27/2024
// Square of Asterisks
#include <iostream>
int main() {
int size;
// Input validation
do {
std::cout << "Enter the size of the square (1-20): " << std::endl;
std::cin >> size;
if (size < 1 || size > 20) {
std::cout << "Invalid size. Please enter a number between 1 and 20." << std::endl;
}
} while (size < 1 || size > 20);
// Print the square
// Top of the square
for (int i = 0; i < size; i++) {
std::cout << "* "; // Style choice to use "* " rather than just "*"
}
std::cout << "\n";
// Middle rows of the square
for (int i = 0; i < size - 2; i++) {
std::cout << "* "; // First asterisk
// Print spaces for hollow part
for (int j = 0; j < size - 2; j++) {
std::cout << " ";
}
std::cout << "* \n"; // Last asterisk
}
// Last row (only if size > 1)
if (size > 1) {
for (int i = 0; i < size; i++) {
std::cout << "* "; // Same style choice as above.
}
std::cout << "\n";
}
}
Sales Commission Calculator
Built a C++ program to compute salesperson earnings using a while loop, calculating a base plus commission until -1 is entered.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, while loop, std::cin, std::cout
Developed a C++ class Date in a header file and a driver program to manage and display dates with month validation.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, class definition, header file (Date.h)
// Sam Macinsky
// 09/29/2024
// Date Header
#pragma once
#include <iostream>
class Date {
private:
int month;
int day;
int year;
public:
// Constructor
Date(int m, int d, int y) {
setMonth(m); // Use setMonth to ensure valid range
day = d;
year = y;
}
// Setter functions
void setMonth(int m) {
if (m >= 1 && m <= 12) {
month = m;
} else {
month = 1; // Default to 1 if out of range
}
}
void setDay(int d) {
day = d;
}
void setYear(int y) {
year = y;
}
// Getter functions
int getMonth() {
return month;
}
int getDay() {
return day;
}
int getYear() {
return year;
}
// Display function
void displayDate() {
std::cout << month << "/" << day << "/" << year << std::endl;
}
};
// Sam Macinsky
// 09/29/2024
// Date
#include<iostream>
#include "Date.h"
int main() {
int userMonth, userDay, userYear;
// Get user input for the date
std::cout << "Enter a month (1-12): ";
std::cin >> userMonth;
std::cout << "Enter a day: ";
std::cin >> userDay;
std::cout << "Enter a year: ";
std::cin >> userYear;
// Create a Date object with user input
Date userDate(userMonth, userDay, userYear);
// Display the date
std::cout << "You entered the date: ";
userDate.displayDate();
// Test invalid month
std::cout << "\nTo test the Month, enter an invalid month (e.g., 13): ";
std::cin >> userMonth;
userDate.setMonth(userMonth);
std::cout << "After setting invalid month: ";
userDate.displayDate();
}
Car Information Tracker
Created a C++ class Car in a header file and a driver program to track car details with getter/setter methods and a display function.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <string>, class definition, header file (Car.h)
// Sam Macinsky
// 09/24/2024
// Car Header
#pragma once
#include <string>
#include <iostream>
class Car
{
public:
// Constructor that initializes all attributes
Car(std::string cMake, std::string cModel, std::string cColor, int cYear, int cMileage)
{
setMake(cMake);
setModel(cModel);
setColor(cColor);
setYear(cYear);
setMileage(cMileage);
}
// "setter and getter" methods
void setMake(std::string carMake) { make = carMake; }
std::string getMake() { return make; }
void setModel(std::string carModel) { model = carModel; }
std::string getModel() { return model; }
void setColor(std::string carColor) { color = carColor; }
std::string getColor() { return color; }
void setYear(int carYear) { year = carYear; }
int getYear() { return year; }
void setMileage(int carMileage) { mileage = carMileage; }
int getMileage() { return mileage; }
// Method to display car information
void displayCar() {
std::cout << getYear() << " " << getMake() << " " << getModel()
<< " (" << getColor() << ") with " << getMileage() << " miles" << std::endl;
}
private:
std::string make;
std::string model;
std::string color;
int year;
int mileage;
};
// Sam Macinsky
// 09/24/2024
// Car
#include <iostream>
#include "Car.h"
int main()
{
// Creating the first car object
Car SamCar("Volkswagen", "Jetta", "Blue", 2010, 198850);
std::cout << "First Car Details:\n";
SamCar.displayCar();
// Creating the second car object
Car CatherineCar("GMC", "Acadia", "Black", 2016, 88650);
std::cout << "\nSecond Car Details:\n";
CatherineCar.displayCar();
}
Geometric Shapes Display
Designed a C++ program to print ASCII representations of a square, triangle, and diamond using cout statements across 9 lines.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, std::cout
Developed a C++ program to print the sequence "1 2 3 4" in a single line without spaces using a single cout statement.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, std::cout
// Sam Macinsky
// 09/05/2024
// Printing
#include<iostream>
int main()
{
std::cout << "1 2 3 4";
}
Odd or Even Detector
Created a C++ program to determine if a user-input number is odd or even using the modulus operator and conditional statements.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, std::cin, std::cout, if-else
// Sam Macinsky
// 09/05/2024
// Odd or Even
#include <iostream>
int main()
{
int number;
// Ask the user for a number
std::cout << "Enter a number: ";
std::cin >> number;
// Check if the number is even or odd using the modulus operator
if (number % 2 == 0) {
std::cout << number << " is even." << std::endl;
} else {
std::cout << number << " is odd." << std::endl;
}
}
Five-Digit Number Separator
Built a C++ program to extract and display individual digits of a five-digit number using division and modulus operations with input validation.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, std::cin, std::cout, arithmetic operators (/, %)
// Sam Macinsky
// 09/05/2024
// Digits of an Integer
#include <iostream>
int main()
{
int number;
// Input
std::cout << "Enter a 5-digit number: ";
std::cin >> number;
// Check if the number has exactly 5 digits
if (number < 10000 || number > 99999) {
std::cout << "Please enter a 5-digit number." << std::endl;
return 1; // Exit with an error code
}
// Extract and print each digit
int digit1 = number / 10000;
int digit2 = (number % 10000) / 1000;
int digit3 = (number % 1000) / 100;
int digit4 = (number % 100) / 10;
int digit5 = number % 10;
// Print digits separated by three spaces
std::cout << digit1 << " " << digit2 << " " << digit3 << " " << digit4 << " " << digit5 << std::endl;
return 0;
}
Checkerboard Pattern Printer (Version 2)
Crafted a concise C++ program to print an 8x8 checkerboard pattern using a single cout statement with newline characters.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, std::cout
Created a C++ program to calculate BMI from user-provided weight and height. The program computes BMI using pow and displays it with a reference table of categories.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <cmath>, std::cin, std::cout, std::pow
// Sam Macinsky
// 09/05/2024
// BMI
#include <iostream>
#include <cmath>
int main()
{
double weight, height, bmi;
// Input weight in kilograms
std::cout << "Enter your weight in kilograms: ";
std::cin >> weight;
// Input height in meters
std::cout << "Enter your height in meters: ";
std::cin >> height;
// Calculate BMI
bmi = weight / (std::pow(height, 2));
// Output BMI
std::cout << "Your BMI is: " << bmi << std::endl;
std::cout << "\n";
std::cout << "Information from the Department of Health and Human Services/National Institute of Health:\n";
std::cout << "BMI VALUES\n";
std::cout << "Underweight: less than 18.5\n";
std::cout << "Normal: between 18.5 and 24.9\n";
std::cout << "Overweight: between 25 and 29.9\n";
std::cout << "Obese: 30 or greater\n";
}
Arithmetic Operations Calculator
Developed a C++ program to perform basic arithmetic operations on three user-input numbers. The program calculates their sum, average, product, smallest, and largest values using std::min and std::max.
Fall 2024 | CI 130 - Programming in C++ | Tools: C++, <iostream>, <cmath>, std::cin, std::cout, std::min, std::max
// Sam Macinsky
// 09/05/2024
// Arithmetic
#include <iostream>
#include <cmath>
int main()
{
double num1, num2, num3;
// Input
std::cout << "Enter three numbers: ";
std::cin >> num1 >> num2 >> num3;
// Calculations
double sum = num1 + num2 + num3;
double average = sum / 3;
double product = num1 * num2 * num3;
double smallest = std::min(std::min(num1, num2), num3);
double largest = std::max(std::max(num1, num2), num3);
// Output
std::cout << "Sum is " << sum << std::endl;
std::cout << "Average is " << average << std::endl;
std::cout << "Product is " << product << std::endl;
std::cout << "Smallest is " << smallest << std::endl;
std::cout << "Largest is " << largest << std::endl;
}